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 collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline A__: Optional[Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): def __init__( self :Dict , **SCREAMING_SNAKE_CASE :List[Any] ) -> Dict: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) if self.framework != "pt": raise ValueError(f"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self :Any , SCREAMING_SNAKE_CASE :Union[np.ndarray, bytes, str] , **SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[int]: '''simple docstring''' return super().__call__(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple , **SCREAMING_SNAKE_CASE :Optional[int] ) -> List[str]: '''simple docstring''' _a : str ={} if "candidate_labels" in kwargs: _a : Tuple =kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: _a : Optional[int] =kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[Any]=None , SCREAMING_SNAKE_CASE :Any="This is a sound of {}." ) -> Tuple: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png _a : Tuple =requests.get(SCREAMING_SNAKE_CASE ).content else: with open(SCREAMING_SNAKE_CASE , """rb""" ) as f: _a : Dict =f.read() if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : List[Any] =ffmpeg_read(SCREAMING_SNAKE_CASE , self.feature_extractor.sampling_rate ) if not isinstance(SCREAMING_SNAKE_CASE , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) _a : Optional[Any] =self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) _a : str =candidate_labels _a : Optional[int] =[hypothesis_template.format(SCREAMING_SNAKE_CASE ) for x in candidate_labels] _a : int =self.tokenizer(SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =[text_inputs] return inputs def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Any ) -> List[Any]: '''simple docstring''' _a : Tuple =model_inputs.pop("""candidate_labels""" ) _a : Tuple =model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , SCREAMING_SNAKE_CASE ): _a : List[Any] =text_inputs[0] else: # Batching case. _a : Tuple =text_inputs[0][0] _a : str =self.model(**SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : Dict ={ """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :int ) -> Any: '''simple docstring''' _a : Tuple =model_outputs.pop("""candidate_labels""" ) _a : int =model_outputs["""logits"""][0] if self.framework == "pt": _a : Optional[int] =logits.softmax(dim=0 ) _a : Tuple =probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) _a : Any =[ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , key=lambda SCREAMING_SNAKE_CASE : -x[0] ) ] return result
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 ) -> int: if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""Input value must be a 'int' type""" ) return bin(_UpperCAmelCase ).count("""1""" ) if __name__ == "__main__": import doctest doctest.testmod()
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 = 100 ) -> int: _a : Optional[int] =n * (n + 1) * (2 * n + 1) / 6 _a : int =(n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) 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 os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Dict = CpmAntTokenizer __UpperCamelCase : Tuple = False def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' super().setUp() _a : Dict =[ """<d>""", """</d>""", """<s>""", """</s>""", """</_>""", """<unk>""", """<pad>""", """</n>""", """我""", """是""", """C""", """P""", """M""", """A""", """n""", """t""", ] _a : Dict =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) @tooslow def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[Any] =CpmAntTokenizer.from_pretrained("""openbmb/cpm-ant-10b""" ) _a : Optional[int] ="""今天天气真好!""" _a : Union[str, Any] =["""今天""", """天气""", """真""", """好""", """!"""] _a : List[Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Optional[int] ="""今天天气真好!""" _a : int =[tokenizer.bos_token] + tokens _a : Dict =[6, 9_8_0_2, 1_4_9_6_2, 2_0_8_2, 8_3_1, 2_4_4] self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) _a : List[str] =tokenizer.decode(SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
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 argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> Any: _a : Tuple =SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: _a : str =4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: _a : str =4 _a : Optional[int] =48 _a : int ="""pixelshuffle_aux""" elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: _a : Union[str, Any] =[6, 6, 6, 6] _a : Dict =60 _a : int =[6, 6, 6, 6] _a : Dict ="""pixelshuffledirect""" elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: _a : Union[str, Any] =4 _a : Union[str, Any] ="""nearest+conv""" elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: _a : Tuple =1 _a : List[Any] =1 _a : List[Any] =126 _a : List[Any] =7 _a : List[Any] =2_5_5.0 _a : List[Any] ="""""" return config def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[int] ) -> Dict: if "patch_embed.proj" in name and "layers" not in name: _a : str =name.replace("""patch_embed.proj""" ,"""embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: _a : str =name.replace("""patch_embed.norm""" ,"""embeddings.patch_embeddings.layernorm""" ) if "layers" in name: _a : Any =name.replace("""layers""" ,"""encoder.stages""" ) if "residual_group.blocks" in name: _a : Dict =name.replace("""residual_group.blocks""" ,"""layers""" ) if "attn.proj" in name: _a : Optional[Any] =name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name: _a : str =name.replace("""attn""" ,"""attention.self""" ) if "norm1" in name: _a : Union[str, Any] =name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: _a : int =name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: _a : List[str] =name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: _a : Dict =name.replace("""mlp.fc2""" ,"""output.dense""" ) if "q_bias" in name: _a : Union[str, Any] =name.replace("""q_bias""" ,"""query.bias""" ) if "k_bias" in name: _a : Any =name.replace("""k_bias""" ,"""key.bias""" ) if "v_bias" in name: _a : Dict =name.replace("""v_bias""" ,"""value.bias""" ) if "cpb_mlp" in name: _a : Dict =name.replace("""cpb_mlp""" ,"""continuous_position_bias_mlp""" ) if "patch_embed.proj" in name: _a : Union[str, Any] =name.replace("""patch_embed.proj""" ,"""patch_embed.projection""" ) if name == "norm.weight": _a : Dict ="""layernorm.weight""" if name == "norm.bias": _a : Any ="""layernorm.bias""" if "conv_first" in name: _a : Union[str, Any] =name.replace("""conv_first""" ,"""first_convolution""" ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: _a : Dict =name.replace("""conv_last""" ,"""final_convolution""" ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: _a : Optional[int] =name.replace("""conv_before_upsample.0""" ,"""conv_before_upsample""" ) if "upsample.0" in name: _a : List[str] =name.replace("""upsample.0""" ,"""upsample.convolution_0""" ) if "upsample.2" in name: _a : Any =name.replace("""upsample.2""" ,"""upsample.convolution_1""" ) _a : List[Any] ="""upsample.""" + name elif config.upsampler == "pixelshuffledirect": _a : Any =name.replace("""upsample.0.weight""" ,"""upsample.conv.weight""" ) _a : Tuple =name.replace("""upsample.0.bias""" ,"""upsample.conv.bias""" ) else: pass else: _a : List[str] ="""swin2sr.""" + name return name def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Dict ) -> Any: for key in orig_state_dict.copy().keys(): _a : Optional[Any] =orig_state_dict.pop(_UpperCAmelCase ) if "qkv" in key: _a : int =key.split(""".""" ) _a : List[Any] =int(key_split[1] ) _a : Union[str, Any] =int(key_split[4] ) _a : List[str] =config.embed_dim if "weight" in key: _a : Tuple =val[:dim, :] _a : Any =val[dim : dim * 2, :] _a : int =val[-dim:, :] else: _a : Any =val[:dim] _a : Optional[Any] =val[dim : dim * 2] _a : Optional[int] =val[-dim:] pass else: _a : Union[str, Any] =val return orig_state_dict def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ) -> List[Any]: _a : int =get_config(_UpperCAmelCase ) _a : Dict =SwinaSRForImageSuperResolution(_UpperCAmelCase ) model.eval() _a : Any =torch.hub.load_state_dict_from_url(_UpperCAmelCase ,map_location="""cpu""" ) _a : List[Any] =convert_state_dict(_UpperCAmelCase ,_UpperCAmelCase ) _a , _a : List[Any] =model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: raise ValueError("""Missing keys when converting: {}""".format(_UpperCAmelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F"Unexpected key {key} in state_dict" ) # verify values _a : str ="""https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true""" _a : Any =Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ).convert("""RGB""" ) _a : Optional[int] =SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values _a : List[str] =126 if """Jpeg""" in checkpoint_url else 256 _a : Dict =Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6] ,std=[0.2_2_9, 0.2_2_4, 0.2_2_5] ), ] ) _a : Optional[int] =transforms(_UpperCAmelCase ).unsqueeze(0 ) if config.num_channels == 1: _a : str =pixel_values[:, 0, :, :].unsqueeze(1 ) _a : List[str] =model(_UpperCAmelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: _a : List[str] =torch.Size([1, 3, 512, 512] ) _a : Optional[Any] =torch.tensor( [[-0.7_0_8_7, -0.7_1_3_8, -0.6_7_2_1], [-0.8_3_4_0, -0.8_0_9_5, -0.7_2_9_8], [-0.9_1_4_9, -0.8_4_1_4, -0.7_9_4_0]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: _a : Tuple =torch.Size([1, 3, 1024, 1024] ) _a : Union[str, Any] =torch.tensor( [[-0.7_7_7_5, -0.8_1_0_5, -0.8_9_3_3], [-0.7_7_6_4, -0.8_3_5_6, -0.9_2_2_5], [-0.7_9_7_6, -0.8_6_8_6, -0.9_5_7_9]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here _a : Any =torch.Size([1, 3, 1024, 1024] ) _a : List[str] =torch.tensor( [[-0.8_0_3_5, -0.7_5_0_4, -0.7_4_9_1], [-0.8_5_3_8, -0.8_1_2_4, -0.7_7_8_2], [-0.8_8_0_4, -0.8_6_5_1, -0.8_4_9_3]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: _a : Optional[Any] =torch.Size([1, 3, 512, 512] ) _a : Union[str, Any] =torch.tensor( [[-0.7_6_6_9, -0.8_6_6_2, -0.8_7_6_7], [-0.8_8_1_0, -0.9_9_6_2, -0.9_8_2_0], [-0.9_3_4_0, -1.0_3_2_2, -1.1_1_4_9]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: _a : int =torch.Size([1, 3, 1024, 1024] ) _a : Tuple =torch.tensor( [[-0.5_2_3_8, -0.5_5_5_7, -0.6_3_2_1], [-0.6_0_1_6, -0.5_9_0_3, -0.6_3_9_1], [-0.6_2_4_4, -0.6_3_3_4, -0.6_8_8_9]] ) assert ( outputs.reconstruction.shape == expected_shape ), F"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] ,_UpperCAmelCase ,atol=1e-3 ) print("""Looks ok!""" ) _a : Tuple ={ """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth""": ( """swin2SR-classical-sr-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth""": ( """swin2SR-classical-sr-x4-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth""": ( """swin2SR-compressed-sr-x4-48""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth""": ( """swin2SR-lightweight-x2-64""" ), """https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth""": ( """swin2SR-realworld-sr-x4-64-bsrgan-psnr""" ), } _a : List[Any] =url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCAmelCase ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: model.push_to_hub(F"caidas/{model_name}" ) processor.push_to_hub(F"caidas/{model_name}" ) if __name__ == "__main__": A__: List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') A__: Optional[int] = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
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 import requests A__: Union[str, Any] = set( '''approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports'''.split() ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : int = 1 ,_UpperCAmelCase : str = "new" ,_UpperCAmelCase : list | None = None ) -> dict: _a : int =wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(_UpperCAmelCase ) - valid_terms ) ): _a : Optional[Any] =F"Invalid search term: {invalid_search_terms}" raise ValueError(_UpperCAmelCase ) _a : List[str] =requests.get( F"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}" ,headers={"""User-agent""": """A random string"""} ,) if response.status_code == 429: raise requests.HTTPError _a : Dict =response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(_UpperCAmelCase )} _a : List[str] ={} for id_ in range(_UpperCAmelCase ): _a : str ={ item: data["""data"""]["""children"""][id_]["""data"""][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('''learnpython''', wanted_data=['''title''', '''url''', '''selftext''']))
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''' 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
'''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 pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class A__ ( pl.LightningModule ): def __init__( self :Tuple , SCREAMING_SNAKE_CASE :Any ) -> int: '''simple docstring''' super().__init__() _a : Optional[Any] =model _a : Any =2 _a : Union[str, Any] =nn.Linear(self.model.config.hidden_size , self.num_labels ) def __UpperCAmelCase ( self :Optional[int] ) -> str: '''simple docstring''' pass def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ,_UpperCAmelCase : str ) -> int: # load longformer model from model identifier _a : Any =LongformerModel.from_pretrained(_UpperCAmelCase ) _a : Dict =LightningModel(_UpperCAmelCase ) _a : Tuple =torch.load(_UpperCAmelCase ,map_location=torch.device("""cpu""" ) ) lightning_model.load_state_dict(ckpt["""state_dict"""] ) # init longformer question answering model _a : List[Any] =LongformerForQuestionAnswering.from_pretrained(_UpperCAmelCase ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(_UpperCAmelCase ) print(F"Conversion successful. Model saved under {pytorch_dump_folder_path}" ) if __name__ == "__main__": A__: Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--longformer_model''', default=None, type=str, required=True, help='''model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.''', ) parser.add_argument( '''--longformer_question_answering_ckpt_path''', default=None, type=str, required=True, help='''Path the official PyTorch Lightning Checkpoint.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) A__: int = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_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''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ) -> List[Any]: _a : List[Any] ={ """en""": """Machine learning is great, isn't it?""", """ru""": """Машинное обучение - это здорово, не так ли?""", """de""": """Maschinelles Lernen ist großartig, oder?""", } # BLUE scores as follows: # "pair": [fairseq, transformers] _a : Optional[Any] ={ """ru-en""": ["""[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)""", """39.20"""], """en-ru""": ["""[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)""", """33.47"""], """en-de""": ["""[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)""", """42.83"""], """de-en""": ["""[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)""", """41.35"""], } _a : int =F"{src_lang}-{tgt_lang}" _a : str =F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) _a : int =os.path.join(_UpperCAmelCase ,"""README.md""" ) print(F"Generating {path}" ) with open(_UpperCAmelCase ,"""w""" ,encoding="""utf-8""" ) as f: f.write(_UpperCAmelCase ) # make sure we are under the root of the project A__: List[Any] = Path(__file__).resolve().parent.parent.parent A__: Optional[int] = repo_dir / '''model_cards''' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: A__ , A__ , A__: List[str] = model_name.split('''-''') A__: List[Any] = model_cards_dir / '''facebook''' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
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 gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __UpperCAmelCase ( self :List[str] ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) _a : Any =UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return model @property def __UpperCAmelCase ( self :str ) -> int: '''simple docstring''' torch.manual_seed(0 ) _a : Dict =UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") , cross_attention_dim=1_0 , ) return model @property def __UpperCAmelCase ( self :Any ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) _a : Tuple =AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , ) _a : Optional[Any] =UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return vqvae, unet @slow def __UpperCAmelCase ( self :str ) -> Any: '''simple docstring''' _a : int ="""cpu""" # ensure determinism for the device-dependent torch.Generator _a : int =Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) _a : Dict =DDPMScheduler() _a : Optional[Any] =AudioDiffusionPipeline(vqvae=SCREAMING_SNAKE_CASE , unet=self.dummy_unet , mel=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) _a : List[str] =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Optional[int] =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(4_2 ) _a : Tuple =pipe(generator=SCREAMING_SNAKE_CASE , steps=4 ) _a : List[Any] =output.audios[0] _a : str =output.images[0] _a : str =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(4_2 ) _a : Union[str, Any] =pipe(generator=SCREAMING_SNAKE_CASE , steps=4 , return_dict=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _a : Union[str, Any] =np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] _a : Any =np.frombuffer(image_from_tuple.tobytes() , dtype="""uint8""" )[:1_0] _a : List[Any] =np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 _a : Union[str, Any] =Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) _a : Tuple =DDIMScheduler() _a : Tuple =self.dummy_vqvae_and_unet _a : List[str] =AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) _a : Optional[int] =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) np.random.seed(0 ) _a : Dict =np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) _a : List[str] =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(4_2 ) _a : Optional[Any] =pipe(raw_audio=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , start_step=5 , steps=1_0 ) _a : str =output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _a : List[str] =np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] _a : Tuple =np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 _a : List[str] =self.dummy_unet_condition _a : Tuple =AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=SCREAMING_SNAKE_CASE , mel=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) np.random.seed(0 ) _a : List[Any] =torch.rand((1, 1, 1_0) ) _a : List[Any] =pipe(generator=SCREAMING_SNAKE_CASE , encoding=SCREAMING_SNAKE_CASE ) _a : Dict =output.images[0] _a : str =np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] _a : Union[str, Any] =np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :Dict ) -> str: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self :Any ) -> Optional[int]: '''simple docstring''' _a : Optional[int] =torch_device _a : Tuple =DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256""" ) _a : int =pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Optional[int] =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(4_2 ) _a : Union[str, Any] =pipe(generator=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =output.audios[0] _a : Any =output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _a : int =np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] _a : int =np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
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''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A__: Optional[Any] = logging.get_logger(__name__) A__: Any = {'''vocab_file''': '''spm_char.model'''} A__: str = { '''vocab_file''': { '''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''', '''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''', '''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''', } } A__: Dict = { '''microsoft/speecht5_asr''': 1024, '''microsoft/speecht5_tts''': 1024, '''microsoft/speecht5_vc''': 1024, } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[str] = VOCAB_FILES_NAMES __UpperCamelCase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : Optional[Any] = ["input_ids", "attention_mask"] def __init__( self :str , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[Any]="<s>" , SCREAMING_SNAKE_CASE :Optional[Any]="</s>" , SCREAMING_SNAKE_CASE :Optional[int]="<unk>" , SCREAMING_SNAKE_CASE :str="<pad>" , SCREAMING_SNAKE_CASE :Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE :Tuple , ) -> None: '''simple docstring''' _a : Optional[Any] ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE , eos_token=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE , ) _a : str =vocab_file _a : Dict =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE ) @property def __UpperCAmelCase ( self :Any ) -> Optional[int]: '''simple docstring''' return self.sp_model.get_piece_size() def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''simple docstring''' _a : Optional[Any] ={self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self :Optional[int] ) -> Dict: '''simple docstring''' _a : Optional[Any] =self.__dict__.copy() _a : Union[str, Any] =None return state def __setstate__( self :str , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[int]: '''simple docstring''' _a : Dict =d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): _a : List[str] ={} _a : Optional[Any] =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :str ) -> List[str]: '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE , out_type=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int , SCREAMING_SNAKE_CASE :Dict ) -> int: '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : int =self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE ) return token def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :int ) -> int: '''simple docstring''' _a : int =[] _a : List[Any] ="""""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE ) + token _a : Dict =[] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE ) return out_string.strip() def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any]=None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :List[int] , SCREAMING_SNAKE_CASE :Optional[List[int]] = None , SCREAMING_SNAKE_CASE :bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE , token_ids_a=SCREAMING_SNAKE_CASE , already_has_special_tokens=SCREAMING_SNAKE_CASE ) _a : Dict =[1] if token_ids_a is None: return ([0] * len(SCREAMING_SNAKE_CASE )) + suffix_ones return ([0] * len(SCREAMING_SNAKE_CASE )) + ([0] * len(SCREAMING_SNAKE_CASE )) + suffix_ones def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return _a : str =os.path.join( SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE , """wb""" ) as fi: _a : Union[str, Any] =self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
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 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
'''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 transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def SCREAMING_SNAKE_CASE_ ( ) -> Tuple: _a : Optional[Any] =HfArgumentParser(_UpperCAmelCase ) _a : List[Any] =parser.parse_args_into_dataclasses()[0] _a : Dict =TensorFlowBenchmark(args=_UpperCAmelCase ) try: _a : Optional[Any] =parser.parse_args_into_dataclasses()[0] except ValueError as e: _a : Optional[int] ="""Arg --no_{0} is no longer used, please use --no-{0} instead.""" _a : int =""" """.join(str(_UpperCAmelCase ).split(""" """ )[:-1] ) _a : Tuple ="""""" _a : Tuple =eval(str(_UpperCAmelCase ).split(""" """ )[-1] ) _a : Union[str, Any] =[] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: _a : Optional[int] =full_error_msg + begin_error_msg + str(_UpperCAmelCase ) raise ValueError(_UpperCAmelCase ) benchmark.run() if __name__ == "__main__": main()
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 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
'''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 List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING A__: Optional[int] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class A__ ( UpperCAmelCase__ ): def __init__( self :List[Any] , *SCREAMING_SNAKE_CASE :Optional[int] , **SCREAMING_SNAKE_CASE :Tuple ) -> str: '''simple docstring''' super().__init__(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) requires_backends(self , """vision""" ) self.check_model_type(SCREAMING_SNAKE_CASE ) def __call__( self :int , SCREAMING_SNAKE_CASE :Union[str, List[str], "Image.Image", List["Image.Image"]] , **SCREAMING_SNAKE_CASE :Union[str, Any] ) -> Any: '''simple docstring''' return super().__call__(SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] , **SCREAMING_SNAKE_CASE :Any ) -> str: '''simple docstring''' return {}, {}, {} def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Optional[Any] ) -> int: '''simple docstring''' _a : Dict =load_image(SCREAMING_SNAKE_CASE ) _a : str =image.size _a : Tuple =self.image_processor(images=SCREAMING_SNAKE_CASE , return_tensors=self.framework ) return model_inputs def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :int ) -> Union[str, Any]: '''simple docstring''' _a : int =self.model(**SCREAMING_SNAKE_CASE ) return model_outputs def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[Any] ) -> int: '''simple docstring''' _a : List[str] =model_outputs.predicted_depth _a : Optional[int] =torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode="""bicubic""" , align_corners=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =prediction.squeeze().cpu().numpy() _a : Tuple =(output * 2_5_5 / np.max(SCREAMING_SNAKE_CASE )).astype("""uint8""" ) _a : List[str] =Image.fromarray(SCREAMING_SNAKE_CASE ) _a : List[Any] ={} _a : List[str] =predicted_depth _a : int =depth return output_dict
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 .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : bool = True ,*_UpperCAmelCase : Optional[Any] ,**_UpperCAmelCase : Dict ) -> List[str]: if not is_tqdm_available(): raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""" ) _a : Optional[int] =False if main_process_only: _a : Optional[int] =PartialState().local_process_index == 0 return _tqdm(*_UpperCAmelCase ,**_UpperCAmelCase ,disable=_UpperCAmelCase )
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 numpy as np import qiskit def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int = 8 ,_UpperCAmelCase : int | None = None ) -> str: _a : int =np.random.default_rng(seed=_UpperCAmelCase ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _a : Dict =6 * key_len # Measurement basis for Alice's qubits. _a : Optional[int] =rng.integers(2 ,size=_UpperCAmelCase ) # The set of states Alice will prepare. _a : Optional[int] =rng.integers(2 ,size=_UpperCAmelCase ) # Measurement basis for Bob's qubits. _a : List[str] =rng.integers(2 ,size=_UpperCAmelCase ) # Quantum Circuit to simulate BB84 _a : Optional[Any] =qiskit.QuantumCircuit(_UpperCAmelCase ,name="""BB84""" ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(_UpperCAmelCase ): if alice_state[index] == 1: bbaa_circ.x(_UpperCAmelCase ) if alice_basis[index] == 1: bbaa_circ.h(_UpperCAmelCase ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(_UpperCAmelCase ): if bob_basis[index] == 1: bbaa_circ.h(_UpperCAmelCase ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _a : Dict =qiskit.Aer.get_backend("""aer_simulator""" ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _a : Union[str, Any] =qiskit.execute(_UpperCAmelCase ,_UpperCAmelCase ,shots=1 ,seed_simulator=_UpperCAmelCase ) # Returns the result of measurement. _a : Optional[Any] =job.result().get_counts(_UpperCAmelCase ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _a : str ="""""".join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _a : List[Any] =gen_key[:key_len] if len(_UpperCAmelCase ) >= key_len else gen_key.ljust(_UpperCAmelCase ,"""0""" ) return key if __name__ == "__main__": print(F"The generated key is : {bbaa(8, seed=0)}") from doctest import testmod testmod()
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 tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin A__: Union[str, Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') A__: int = {'''target_lang''': '''fi''', '''source_lang''': '''en'''} A__: Dict = '''>>zh<<''' A__: Optional[Any] = '''Helsinki-NLP/''' if is_torch_available(): A__: Optional[int] = '''pt''' elif is_tf_available(): A__: int = '''tf''' else: A__: Optional[Any] = '''jax''' @require_sentencepiece class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : int = MarianTokenizer __UpperCamelCase : str = False __UpperCamelCase : int = True def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' super().setUp() _a : Tuple =["""</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est""", """\u0120""", """<pad>"""] _a : str =dict(zip(SCREAMING_SNAKE_CASE , range(len(SCREAMING_SNAKE_CASE ) ) ) ) _a : Optional[Any] =Path(self.tmpdirname ) save_json(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES["""vocab"""] ) save_json(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES["""tokenizer_config_file"""] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES["""source_spm"""] ) copyfile(SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES["""target_spm"""] ) _a : Union[str, Any] =MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase ( self :Tuple , **SCREAMING_SNAKE_CASE :List[Any] ) -> MarianTokenizer: '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> Any: '''simple docstring''' return ( "This is a test", "This is a test", ) def __UpperCAmelCase ( self :Any ) -> Dict: '''simple docstring''' _a : Tuple ="""</s>""" _a : Tuple =0 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 :Optional[Any] ) -> Optional[Any]: '''simple docstring''' _a : Dict =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """</s>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """<pad>""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , 9 ) def __UpperCAmelCase ( self :List[str] ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : Union[str, Any] =MarianTokenizer.from_pretrained(f"{ORG_NAME}opus-mt-en-de" ) _a : List[str] =en_de_tokenizer(["""I am a small frog"""] , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =[3_8, 1_2_1, 1_4, 6_9_7, 3_8_8_4_8, 0] self.assertListEqual(SCREAMING_SNAKE_CASE , batch.input_ids[0] ) _a : int =tempfile.mkdtemp() en_de_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE ) _a : List[Any] =[x.name for x in Path(SCREAMING_SNAKE_CASE ).glob("""*""" )] self.assertIn("""source.spm""" , SCREAMING_SNAKE_CASE ) MarianTokenizer.from_pretrained(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> str: '''simple docstring''' _a : Union[str, Any] =self.get_tokenizer() _a : List[str] =tok( ["""I am a small frog""" * 1_0_0_0, """I am a small frog"""] , padding=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(batch.input_ids.shape , (2, 5_1_2) ) def __UpperCAmelCase ( self :str ) -> int: '''simple docstring''' _a : Dict =self.get_tokenizer() _a : Optional[Any] =tok(["""I am a tiny frog""", """I am a small frog"""] , padding=SCREAMING_SNAKE_CASE , return_tensors=SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) self.assertEqual(batch_smaller.input_ids.shape , (2, 1_0) ) @slow def __UpperCAmelCase ( self :Optional[int] ) -> Optional[Any]: '''simple docstring''' # fmt: off _a : List[Any] ={"""input_ids""": [[4_3_4_9_5, 4_6_2, 2_0, 4_2_1_6_4, 1_3_6_9, 5_2, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 7_4_9_1, 3_8_9_9_9, 6, 8, 4_6_4, 1_3_2, 1_7_0_3, 4_9_2, 1_3, 4_6_6_9, 3_7_8_6_7, 1_3, 7_5_2_5, 2_7, 1_5_9_3, 9_8_8, 1_3, 3_3_9_7_2, 7_0_2_9, 6, 2_0, 8_2_5_1, 3_8_3, 2, 2_7_0, 5_8_6_6, 3_7_8_8, 2, 2_3_5_3, 8_2_5_1, 1_2_3_3_8, 2, 1_3_9_5_8, 3_8_7, 2, 3_6_2_9, 6_9_5_3, 1_8_8, 2_9_0_0, 2, 1_3_9_5_8, 8_0_1_1, 1_1_5_0_1, 2_3, 8_4_6_0, 4_0_7_3, 3_4_0_0_9, 2_0, 4_3_5, 1_1_4_3_9, 2_7, 8, 8_4_6_0, 4_0_7_3, 6_0_0_4, 2_0, 9_9_8_8, 3_7_5, 2_7, 3_3, 2_6_6, 1_9_4_5, 1_0_7_6, 1_3_5_0, 3_7_8_6_7, 3_2_8_8, 5, 5_7_7, 1_0_7_6, 4_3_7_4, 8, 5_0_8_2, 5, 2_6_4_5_3, 2_5_7, 5_5_6, 4_0_3, 2, 2_4_2, 1_3_2, 3_8_3, 3_1_6, 4_9_2, 8, 1_0_7_6_7, 6, 3_1_6, 3_0_4, 4_2_3_9, 3, 0], [1_4_8, 1_5_7_2_2, 1_9, 1_8_3_9, 1_2, 1_3_5_0, 1_3, 2_2_3_2_7, 5_0_8_2, 5_4_1_8, 4_7_5_6_7, 3_5_9_3_8, 5_9, 3_1_8, 1_9_5_5_2, 1_0_8, 2_1_8_3, 5_4, 1_4_9_7_6, 4_8_3_5, 3_2, 5_4_7, 1_1_1_4, 8, 3_1_5, 2_4_1_7, 5, 9_2, 1_9_0_8_8, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0], [3_6, 6_3_9_5, 1_2_5_7_0, 3_9_1_4_7, 1_1_5_9_7, 6, 2_6_6, 4, 4_5_4_0_5, 7_2_9_6, 3, 0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0, 5_8_1_0_0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE , model_name="""Helsinki-NLP/opus-mt-en-de""" , revision="""1a8c2263da11e68e50938f97e10cd57820bd504c""" , decode_kwargs={"""use_source_tokenizer""": True} , ) def __UpperCAmelCase ( self :Tuple ) -> str: '''simple docstring''' _a : Union[str, Any] =MarianTokenizer.from_pretrained("""hf-internal-testing/test-marian-two-vocabs""" ) _a : Dict ="""Tämä on testi""" _a : Tuple ="""This is a test""" _a : Any =[7_6, 7, 2_0_4_7, 2] _a : int =[6_9, 1_2, 1_1, 9_4_0, 2] _a : List[Any] =tokenizer(SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : str =tokenizer(text_target=SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tokenizer.decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
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 from typing import Any def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list[Any] ) -> None: create_state_space_tree(_UpperCAmelCase ,[] ,0 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list[Any] ,_UpperCAmelCase : list[Any] ,_UpperCAmelCase : int ) -> None: if index == len(_UpperCAmelCase ): print(_UpperCAmelCase ) return create_state_space_tree(_UpperCAmelCase ,_UpperCAmelCase ,index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(_UpperCAmelCase ,_UpperCAmelCase ,index + 1 ) current_subsequence.pop() if __name__ == "__main__": A__: list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['''A''', '''B''', '''C''']) generate_all_subsequences(seq)
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 argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": A__: List[str] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '''--original_config_file''', default=None, type=str, help='''The YAML config file corresponding to the original architecture.''', ) parser.add_argument( '''--num_in_channels''', default=None, type=int, help='''The number of input channels. If `None` number of input channels will be automatically inferred.''', ) parser.add_argument( '''--scheduler_type''', default='''pndm''', type=str, help='''Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']''', ) parser.add_argument( '''--pipeline_type''', default=None, type=str, help=( '''The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'''' '''. If `None` pipeline will be automatically inferred.''' ), ) parser.add_argument( '''--image_size''', default=None, type=int, help=( '''The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2''' ''' Base. Use 768 for Stable Diffusion v2.''' ), ) parser.add_argument( '''--prediction_type''', default=None, type=str, help=( '''The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable''' ''' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.''' ), ) parser.add_argument( '''--extract_ema''', action='''store_true''', help=( '''Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights''' ''' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield''' ''' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.''' ), ) parser.add_argument( '''--upcast_attention''', action='''store_true''', help=( '''Whether the attention computation should always be upcasted. This is necessary when running stable''' ''' diffusion 2.1.''' ), ) parser.add_argument( '''--from_safetensors''', action='''store_true''', help='''If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.''', ) parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') parser.add_argument( '''--stable_unclip''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.''', ) parser.add_argument( '''--stable_unclip_prior''', type=str, default=None, required=False, help='''Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.''', ) parser.add_argument( '''--clip_stats_path''', type=str, help='''Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.''', required=False, ) parser.add_argument( '''--controlnet''', action='''store_true''', default=None, help='''Set flag if this is a controlnet checkpoint.''' ) parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--vae_path''', type=str, default=None, required=False, help='''Set to a path, hub id to an already converted vae to not convert it again.''', ) A__: Optional[int] = parser.parse_args() A__: Dict = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
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 collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A__: Optional[Any] = logging.get_logger(__name__) A__: Optional[Any] = { '''xlm-mlm-en-2048''': '''https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json''', '''xlm-mlm-ende-1024''': '''https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json''', '''xlm-mlm-enfr-1024''': '''https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json''', '''xlm-mlm-enro-1024''': '''https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json''', '''xlm-mlm-tlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json''', '''xlm-mlm-xnli15-1024''': '''https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json''', '''xlm-clm-enfr-1024''': '''https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json''', '''xlm-clm-ende-1024''': '''https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json''', '''xlm-mlm-17-1280''': '''https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json''', '''xlm-mlm-100-1280''': '''https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json''', } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[str] = "xlm" __UpperCamelCase : Tuple = { "hidden_size": "emb_dim", "num_attention_heads": "n_heads", "num_hidden_layers": "n_layers", "n_words": "vocab_size", # For backward compatibility } def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :int=3_0_1_4_5 , SCREAMING_SNAKE_CASE :str=2_0_4_8 , SCREAMING_SNAKE_CASE :Union[str, Any]=1_2 , SCREAMING_SNAKE_CASE :List[str]=1_6 , SCREAMING_SNAKE_CASE :Tuple=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :Union[str, Any]=True , SCREAMING_SNAKE_CASE :List[Any]=False , SCREAMING_SNAKE_CASE :Union[str, Any]=False , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :str=1 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[Any]=5_1_2 , SCREAMING_SNAKE_CASE :str=2_0_4_8**-0.5 , SCREAMING_SNAKE_CASE :Tuple=1e-12 , SCREAMING_SNAKE_CASE :str=0.02 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :Tuple=2 , SCREAMING_SNAKE_CASE :Any=3 , SCREAMING_SNAKE_CASE :List[Any]=5 , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[Any]="first" , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Tuple=5 , SCREAMING_SNAKE_CASE :Dict=5 , SCREAMING_SNAKE_CASE :str=0 , SCREAMING_SNAKE_CASE :int=0 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Tuple=0 , **SCREAMING_SNAKE_CASE :List[Any] , ) -> int: '''simple docstring''' _a : List[str] =vocab_size _a : Optional[Any] =emb_dim _a : Optional[int] =n_layers _a : List[str] =n_heads _a : Any =dropout _a : Tuple =attention_dropout _a : Dict =gelu_activation _a : Optional[Any] =sinusoidal_embeddings _a : Dict =causal _a : List[str] =asm _a : Tuple =n_langs _a : Any =use_lang_emb _a : Tuple =layer_norm_eps _a : Optional[Any] =bos_index _a : Tuple =eos_index _a : Dict =pad_index _a : List[str] =unk_index _a : Union[str, Any] =mask_index _a : int =is_encoder _a : Tuple =max_position_embeddings _a : Optional[int] =embed_init_std _a : str =init_std _a : Optional[int] =summary_type _a : Union[str, Any] =summary_use_proj _a : Tuple =summary_activation _a : Optional[int] =summary_proj_to_labels _a : Tuple =summary_first_dropout _a : List[str] =start_n_top _a : List[Any] =end_n_top _a : Any =mask_token_id _a : List[Any] =lang_id if "n_words" in kwargs: _a : Tuple =kwargs["""n_words"""] super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) class A__ ( UpperCAmelCase__ ): @property def __UpperCAmelCase ( self :List[Any] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": _a : Optional[int] ={0: """batch""", 1: """choice""", 2: """sequence"""} else: _a : Any ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
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 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
'''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 abc import ABC, abstractmethod from argparse import ArgumentParser class A__ ( UpperCAmelCase__ ): @staticmethod @abstractmethod def __UpperCAmelCase ( SCREAMING_SNAKE_CASE :ArgumentParser ) -> List[Any]: '''simple docstring''' raise NotImplementedError() @abstractmethod def __UpperCAmelCase ( self :List[str] ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError()
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 os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Any = LxmertTokenizer __UpperCamelCase : int = LxmertTokenizerFast __UpperCamelCase : Optional[Any] = True __UpperCamelCase : List[str] = True def __UpperCAmelCase ( self :Optional[int] ) -> List[str]: '''simple docstring''' super().setUp() _a : Dict =[ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] _a : Union[str, Any] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Tuple: '''simple docstring''' _a : Dict ="""UNwant\u00E9d,running""" _a : Dict ="""unwanted, running""" return input_text, output_text def __UpperCAmelCase ( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Any =self.tokenizer_class(self.vocab_file ) _a : Union[str, Any] =tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(SCREAMING_SNAKE_CASE , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE ) , [7, 4, 5, 1_0, 8, 9] ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' if not self.test_rust_tokenizer: return _a : int =self.get_tokenizer() _a : Union[str, Any] =self.get_rust_tokenizer() _a : Tuple ="""I was born in 92000, and this is falsé.""" _a : str =tokenizer.tokenize(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Dict =tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) _a : int =rust_tokenizer.encode(SCREAMING_SNAKE_CASE , add_special_tokens=SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[Any] =self.get_rust_tokenizer() _a : Dict =tokenizer.encode(SCREAMING_SNAKE_CASE ) _a : Optional[int] =rust_tokenizer.encode(SCREAMING_SNAKE_CASE ) self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
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 Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging A__: List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = ["pixel_values"] def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Union[int, float] = 1 / 2_5_5 , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :bool = True , **SCREAMING_SNAKE_CASE :Optional[int] , ) -> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =size if size is not None else {"""shortest_edge""": 2_2_4} _a : Dict =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) _a : int =crop_size if crop_size is not None else {"""height""": 2_2_4, """width""": 2_2_4} _a : Any =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE , param_name="""crop_size""" ) _a : Any =do_resize _a : Union[str, Any] =size _a : Union[str, Any] =resample _a : Any =do_center_crop _a : Dict =crop_size _a : List[Any] =do_rescale _a : Union[str, Any] =rescale_factor _a : Optional[int] =do_normalize _a : Tuple =image_mean if image_mean is not None else OPENAI_CLIP_MEAN _a : Any =image_std if image_std is not None else OPENAI_CLIP_STD _a : Dict =do_convert_rgb def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , SCREAMING_SNAKE_CASE :PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :List[str] , ) -> np.ndarray: '''simple docstring''' _a : List[Any] =get_size_dict(SCREAMING_SNAKE_CASE , default_to_square=SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) _a : Optional[int] =get_resize_output_image_size(SCREAMING_SNAKE_CASE , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE ) return resize(SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE , resample=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Dict[str, int] , 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` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[int, float] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :Optional[Any] , ) -> List[Any]: '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :np.ndarray , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Union[float, List[float]] , SCREAMING_SNAKE_CASE :Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE :List[Any] , ) -> np.ndarray: '''simple docstring''' return normalize(SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE , data_format=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :ImageInput , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Dict[str, int] = None , SCREAMING_SNAKE_CASE :PILImageResampling = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :int = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :float = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE :bool = None , SCREAMING_SNAKE_CASE :Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE :Optional[ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE :int , ) -> 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 : List[Any] =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""size""" , default_to_square=SCREAMING_SNAKE_CASE ) _a : Any =resample if resample is not None else self.resample _a : Any =do_center_crop if do_center_crop is not None else self.do_center_crop _a : Optional[Any] =crop_size if crop_size is not None else self.crop_size _a : Optional[Any] =get_size_dict(SCREAMING_SNAKE_CASE , param_name="""crop_size""" , default_to_square=SCREAMING_SNAKE_CASE ) _a : Any =do_rescale if do_rescale is not None else self.do_rescale _a : Union[str, Any] =rescale_factor if rescale_factor is not None else self.rescale_factor _a : List[Any] =do_normalize if do_normalize is not None else self.do_normalize _a : Optional[int] =image_mean if image_mean is not None else self.image_mean _a : Tuple =image_std if image_std is not None else self.image_std _a : int =do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _a : Any =make_list_of_images(SCREAMING_SNAKE_CASE ) if not valid_images(SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: _a : Tuple =[convert_to_rgb(SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. _a : Any =[to_numpy_array(SCREAMING_SNAKE_CASE ) for image in images] 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] if do_center_crop: _a : Tuple =[self.center_crop(image=SCREAMING_SNAKE_CASE , size=SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: _a : List[Any] =[self.rescale(image=SCREAMING_SNAKE_CASE , scale=SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: _a : Union[str, Any] =[self.normalize(image=SCREAMING_SNAKE_CASE , mean=SCREAMING_SNAKE_CASE , std=SCREAMING_SNAKE_CASE ) for image in images] _a : List[Any] =[to_channel_dimension_format(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for image in images] _a : Tuple ={"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE , tensor_type=SCREAMING_SNAKE_CASE )
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''' from collections import defaultdict def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ) -> bool: _a : Optional[Any] =first_str.lower().strip() _a : List[str] =second_str.lower().strip() # Remove whitespace _a : int =first_str.replace(""" """ ,"""""" ) _a : List[Any] =second_str.replace(""" """ ,"""""" ) # Strings of different lengths are not anagrams if len(_UpperCAmelCase ) != len(_UpperCAmelCase ): return False # Default values for count should be 0 _a : defaultdict[str, int] =defaultdict(_UpperCAmelCase ) # For each character in input strings, # increment count in the corresponding for i in range(len(_UpperCAmelCase ) ): count[first_str[i]] += 1 count[second_str[i]] -= 1 return all(_count == 0 for _count in count.values() ) if __name__ == "__main__": from doctest import testmod testmod() A__: Tuple = input('''Enter the first string ''').strip() A__: Optional[int] = input('''Enter the second string ''').strip() A__: int = check_anagrams(input_a, input_b) print(F"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
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 argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ) -> List[str]: _a : Optional[Any] =[] embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", F"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", F"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", F"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", F"stage{idx}.patch_embed.norm.bias", ) ) return embed def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : str ) -> Optional[int]: _a : Optional[Any] =[] attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", F"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", F"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", F"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", F"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", F"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", F"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", F"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", F"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", F"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", F"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", F"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", F"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: _a : Union[str, Any] =[] token.append((F"cvt.encoder.stages.{idx}.cls_token", """stage2.cls_token""") ) return token def SCREAMING_SNAKE_CASE_ ( ) -> int: _a : str =[] head.append(("""layernorm.weight""", """norm.weight""") ) head.append(("""layernorm.bias""", """norm.bias""") ) head.append(("""classifier.weight""", """head.weight""") ) head.append(("""classifier.bias""", """head.bias""") ) return head def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[int] ) -> Tuple: _a : Optional[int] ="""imagenet-1k-id2label.json""" _a : str =1000 _a : str ="""huggingface/label-files""" _a : Union[str, Any] =num_labels _a : Optional[int] =json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type="""dataset""" ) ) ,"""r""" ) ) _a : Any ={int(_UpperCAmelCase ): v for k, v in idalabel.items()} _a : Optional[int] =idalabel _a : Dict ={v: k for k, v in idalabel.items()} _a : Optional[Any] =CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("""/""" ,1 )[-1][4:6] == "13": _a : int =[1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("""/""" ,1 )[-1][4:6] == "21": _a : int =[1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: _a : Dict =[2, 2, 20] _a : Optional[Any] =[3, 12, 16] _a : Union[str, Any] =[192, 768, 1024] _a : Union[str, Any] =CvtForImageClassification(_UpperCAmelCase ) _a : str =AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) _a : Any =image_size _a : Tuple =torch.load(_UpperCAmelCase ,map_location=torch.device("""cpu""" ) ) _a : Optional[Any] =OrderedDict() _a : List[Any] =[] for idx in range(len(config.depth ) ): if config.cls_token[idx]: _a : Union[str, Any] =list_of_state_dict + cls_token(_UpperCAmelCase ) _a : List[Any] =list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): _a : Tuple =list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) _a : Tuple =list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): _a : List[Any] =original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__: str = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=384, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__: int = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
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 re from filelock import FileLock try: import nltk A__: Optional[Any] = True except (ImportError, ModuleNotFoundError): A__: Optional[Any] = False if NLTK_AVAILABLE: with FileLock('''.lock''') as lock: nltk.download('''punkt''', quiet=True) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> str: re.sub("""<n>""" ,"""""" ,_UpperCAmelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_UpperCAmelCase ) )
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 gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[Any]: '''simple docstring''' _a , _a : Optional[Any] =FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-canny""" , from_pt=SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa ) _a , _a : Union[str, Any] =FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=SCREAMING_SNAKE_CASE , from_pt=SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa ) _a : Any =controlnet_params _a : List[str] ="""bird""" _a : List[str] =jax.device_count() _a : Dict =pipe.prepare_text_inputs([prompts] * num_samples ) _a : Any =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png""" ) _a : Any =pipe.prepare_image_inputs([canny_image] * num_samples ) _a : Optional[int] =jax.random.PRNGKey(0 ) _a : Union[str, Any] =jax.random.split(SCREAMING_SNAKE_CASE , jax.device_count() ) _a : Tuple =replicate(SCREAMING_SNAKE_CASE ) _a : int =shard(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =shard(SCREAMING_SNAKE_CASE ) _a : int =pipe( prompt_ids=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , params=SCREAMING_SNAKE_CASE , prng_seed=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , jit=SCREAMING_SNAKE_CASE , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) _a : Optional[int] =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _a : Any =images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] _a : str =jnp.asarray(jax.device_get(image_slice.flatten() ) ) _a : List[Any] =jnp.array( [0.167_969, 0.116_699, 0.081_543, 0.154_297, 0.132_812, 0.108_887, 0.169_922, 0.169_922, 0.205_078] ) print(f"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def __UpperCAmelCase ( self :List[Any] ) -> Union[str, Any]: '''simple docstring''' _a , _a : List[Any] =FlaxControlNetModel.from_pretrained( """lllyasviel/sd-controlnet-openpose""" , from_pt=SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa ) _a , _a : Dict =FlaxStableDiffusionControlNetPipeline.from_pretrained( """runwayml/stable-diffusion-v1-5""" , controlnet=SCREAMING_SNAKE_CASE , from_pt=SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa ) _a : List[str] =controlnet_params _a : List[str] ="""Chef in the kitchen""" _a : Optional[int] =jax.device_count() _a : str =pipe.prepare_text_inputs([prompts] * num_samples ) _a : Any =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png""" ) _a : List[str] =pipe.prepare_image_inputs([pose_image] * num_samples ) _a : List[Any] =jax.random.PRNGKey(0 ) _a : Optional[int] =jax.random.split(SCREAMING_SNAKE_CASE , jax.device_count() ) _a : Dict =replicate(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =shard(SCREAMING_SNAKE_CASE ) _a : Any =shard(SCREAMING_SNAKE_CASE ) _a : Any =pipe( prompt_ids=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , params=SCREAMING_SNAKE_CASE , prng_seed=SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , jit=SCREAMING_SNAKE_CASE , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) _a : List[Any] =images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) _a : Tuple =images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] _a : int =jnp.asarray(jax.device_get(image_slice.flatten() ) ) _a : List[Any] =jnp.array( [[0.271_484, 0.261_719, 0.275_391, 0.277_344, 0.279_297, 0.291_016, 0.294_922, 0.302_734, 0.302_734]] ) print(f"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
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 from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available A__: str = { '''configuration_conditional_detr''': [ '''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConditionalDetrConfig''', '''ConditionalDetrOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = ['''ConditionalDetrFeatureExtractor'''] A__: List[str] = ['''ConditionalDetrImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[Any] = [ '''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConditionalDetrForObjectDetection''', '''ConditionalDetrForSegmentation''', '''ConditionalDetrModel''', '''ConditionalDetrPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys A__: List[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''' from math import loga def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if a < 0: raise ValueError("""Input value must be a positive integer""" ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError("""Input value must be a 'int' type""" ) return 0 if (a == 0) else int(loga(a & -a ) ) if __name__ == "__main__": import doctest doctest.testmod()
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''' from ....utils import logging A__: Any = logging.get_logger(__name__) class A__ ( UpperCAmelCase__ ): def __init__( self :Dict , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any=None , SCREAMING_SNAKE_CASE :Dict=2_0_4_8 ) -> List[Any]: '''simple docstring''' _a : str =config.__dict__ _a : Tuple =modal_hidden_size if num_labels: _a : Tuple =num_labels
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''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer A__: Optional[Any] = logging.get_logger(__name__) A__: Tuple = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__: List[Any] = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } A__: Optional[Any] = { '''bert-base-uncased''': 512, '''bert-large-uncased''': 512, '''bert-base-cased''': 512, '''bert-large-cased''': 512, '''bert-base-multilingual-uncased''': 512, '''bert-base-multilingual-cased''': 512, '''bert-base-chinese''': 512, '''bert-base-german-cased''': 512, '''bert-large-uncased-whole-word-masking''': 512, '''bert-large-cased-whole-word-masking''': 512, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 512, '''bert-large-cased-whole-word-masking-finetuned-squad''': 512, '''bert-base-cased-finetuned-mrpc''': 512, '''bert-base-german-dbmdz-cased''': 512, '''bert-base-german-dbmdz-uncased''': 512, '''TurkuNLP/bert-base-finnish-cased-v1''': 512, '''TurkuNLP/bert-base-finnish-uncased-v1''': 512, '''wietsedv/bert-base-dutch-cased''': 512, } A__: List[str] = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = VOCAB_FILES_NAMES __UpperCamelCase : Dict = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase : int = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase : str = BertTokenizer def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :Optional[Any]=None , SCREAMING_SNAKE_CASE :int=None , SCREAMING_SNAKE_CASE :Optional[Any]=True , SCREAMING_SNAKE_CASE :List[str]="[UNK]" , SCREAMING_SNAKE_CASE :Tuple="[SEP]" , SCREAMING_SNAKE_CASE :Any="[PAD]" , SCREAMING_SNAKE_CASE :str="[CLS]" , SCREAMING_SNAKE_CASE :Tuple="[MASK]" , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :str=None , **SCREAMING_SNAKE_CASE :Dict , ) -> Dict: '''simple docstring''' super().__init__( SCREAMING_SNAKE_CASE , tokenizer_file=SCREAMING_SNAKE_CASE , do_lower_case=SCREAMING_SNAKE_CASE , unk_token=SCREAMING_SNAKE_CASE , sep_token=SCREAMING_SNAKE_CASE , pad_token=SCREAMING_SNAKE_CASE , cls_token=SCREAMING_SNAKE_CASE , mask_token=SCREAMING_SNAKE_CASE , tokenize_chinese_chars=SCREAMING_SNAKE_CASE , strip_accents=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) _a : str =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get("""strip_accents""" , SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): _a : Any =getattr(SCREAMING_SNAKE_CASE , normalizer_state.pop("""type""" ) ) _a : Optional[int] =do_lower_case _a : Tuple =strip_accents _a : Dict =tokenize_chinese_chars _a : Any =normalizer_class(**SCREAMING_SNAKE_CASE ) _a : List[str] =do_lower_case def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[str]=None ) -> Optional[int]: '''simple docstring''' _a : Tuple =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :List[int] , SCREAMING_SNAKE_CASE :Optional[List[int]] = None ) -> List[int]: '''simple docstring''' _a : List[Any] =[self.sep_token_id] _a : List[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[str] = None ) -> Tuple[str]: '''simple docstring''' _a : Any =self._tokenizer.model.save(SCREAMING_SNAKE_CASE , name=SCREAMING_SNAKE_CASE ) return tuple(SCREAMING_SNAKE_CASE )
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 ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> list: _a : Union[str, Any] =[] _a , _a : Any =input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) _a : Any =result + left + right return input_list def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : list ) -> list: if len(_UpperCAmelCase ) <= 1: return input_list _a : Union[str, Any] =list(_UpperCAmelCase ) # iteration for two-way merging _a : List[Any] =2 while p <= len(_UpperCAmelCase ): # getting low, high and middle value for merge-sort of single list for i in range(0 ,len(_UpperCAmelCase ) ,_UpperCAmelCase ): _a : Tuple =i _a : List[Any] =i + p - 1 _a : List[str] =(low + high + 1) // 2 _a : Dict =merge(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # final merge of last two parts if p * 2 >= len(_UpperCAmelCase ): _a : str =i _a : Dict =merge(_UpperCAmelCase ,0 ,_UpperCAmelCase ,len(_UpperCAmelCase ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": A__: str = input('''Enter numbers separated by a comma:\n''').strip() if user_input == "": A__: str = [] else: A__: int = [int(item.strip()) for item in user_input.split(''',''')] print(iter_merge_sort(unsorted))
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 sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 A__: str = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') A__: Any = get_tests_dir('''fixtures/vocab.json''') A__: List[str] = get_tests_dir('''fixtures''') class A__ ( unittest.TestCase ): __UpperCamelCase : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] def __UpperCAmelCase ( self :List[Any] ) -> int: '''simple docstring''' _a : int =0 def __UpperCAmelCase ( self :Dict ) -> Tuple: '''simple docstring''' _a : Tuple =AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: _a : Any =WavaVecaConfig() _a : Union[str, Any] =AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h""" ) # save in new folder model_config.save_pretrained(SCREAMING_SNAKE_CASE ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) _a : str =AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Any: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) copyfile(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , """vocab.json""" ) ) _a : Optional[int] =AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> Optional[int]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple =WavaVecaFeatureExtractor() _a : str =AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) _a : Union[str, Any] =WavaVecaProcessor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # save in new folder processor.save_pretrained(SCREAMING_SNAKE_CASE ) # drop `processor_class` in tokenizer with open(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , """r""" ) as f: _a : Any =json.load(SCREAMING_SNAKE_CASE ) config_dict.pop("""processor_class""" ) with open(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , """w""" ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE ) ) _a : List[Any] =AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :int ) -> Any: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] =WavaVecaFeatureExtractor() _a : Tuple =AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h""" ) _a : int =WavaVecaProcessor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # save in new folder processor.save_pretrained(SCREAMING_SNAKE_CASE ) # drop `processor_class` in feature extractor with open(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , """r""" ) as f: _a : List[Any] =json.load(SCREAMING_SNAKE_CASE ) config_dict.pop("""processor_class""" ) with open(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , """w""" ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE ) ) _a : List[str] =AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: _a : Optional[int] =WavaVecaConfig(processor_class="""Wav2Vec2Processor""" ) model_config.save_pretrained(SCREAMING_SNAKE_CASE ) # copy relevant files copyfile(SCREAMING_SNAKE_CASE , os.path.join(SCREAMING_SNAKE_CASE , """vocab.json""" ) ) # create emtpy sample processor with open(os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , """w""" ) as f: f.write("""{}""" ) _a : str =AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) self.assertIsInstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Optional[int]: '''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 : Union[str, Any] =AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE ): _a : Any =AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=SCREAMING_SNAKE_CASE ) _a : Dict =AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) _a : Optional[int] =processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) _a : str =processor.tokenizer 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 : Optional[Any] =AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=SCREAMING_SNAKE_CASE , use_fast=SCREAMING_SNAKE_CASE ) _a : List[Any] =new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , """NewTokenizer""" ) else: self.assertEqual(tokenizer.__class__.__name__ , """NewTokenizer""" ) def __UpperCAmelCase ( self :Tuple ) -> Dict: '''simple docstring''' try: AutoConfig.register("""custom""" , SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) AutoProcessor.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 ): AutoProcessor.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 : List[str] =CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: _a : Optional[int] =os.path.join(SCREAMING_SNAKE_CASE , """vocab.txt""" ) with open(SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) _a : int =CustomTokenizer(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =CustomProcessor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(SCREAMING_SNAKE_CASE ) _a : List[str] =AutoProcessor.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 FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def __UpperCAmelCase ( self :Tuple ) -> str: '''simple docstring''' class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = False class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Optional[int] = False class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = "AutoFeatureExtractor" __UpperCamelCase : Optional[int] = "AutoTokenizer" __UpperCamelCase : Tuple = False try: AutoConfig.register("""custom""" , SCREAMING_SNAKE_CASE ) AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) AutoTokenizer.register(SCREAMING_SNAKE_CASE , slow_tokenizer_class=SCREAMING_SNAKE_CASE ) AutoProcessor.register(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # If remote code is not set, the default is to use local classes. _a : Dict =AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor""" ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. _a : Optional[int] =AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. _a : Dict =AutoProcessor.from_pretrained( """hf-internal-testing/test_dynamic_processor""" , trust_remote_code=SCREAMING_SNAKE_CASE ) self.assertEqual(processor.__class__.__name__ , """NewProcessor""" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[int]: '''simple docstring''' _a : Dict =AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) self.assertEqual(processor.__class__.__name__ , """BertTokenizerFast""" ) def __UpperCAmelCase ( self :int ) -> Union[str, Any]: '''simple docstring''' _a : Tuple =AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext""" ) self.assertEqual(processor.__class__.__name__ , """ConvNextImageProcessor""" ) @is_staging_test class A__ ( unittest.TestCase ): __UpperCamelCase : str = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] @classmethod def __UpperCAmelCase ( cls :Optional[Any] ) -> Tuple: '''simple docstring''' _a : Any =TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls :Optional[int] ) -> Any: '''simple docstring''' try: delete_repo(token=cls._token , repo_id="""test-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-processor""" ) except HTTPError: pass def __UpperCAmelCase ( self :List[str] ) -> Any: '''simple docstring''' _a : Dict =WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(SCREAMING_SNAKE_CASE , """test-processor""" ) , push_to_hub=SCREAMING_SNAKE_CASE , use_auth_token=self._token ) _a : Any =WavaVecaProcessor.from_pretrained(f"{USER}/test-processor" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE , getattr(new_processor.feature_extractor , SCREAMING_SNAKE_CASE ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[int] =WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(SCREAMING_SNAKE_CASE , """test-processor-org""" ) , push_to_hub=SCREAMING_SNAKE_CASE , use_auth_token=self._token , organization="""valid_org""" , ) _a : Optional[Any] =WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org""" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(SCREAMING_SNAKE_CASE , getattr(new_processor.feature_extractor , SCREAMING_SNAKE_CASE ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def __UpperCAmelCase ( self :int ) -> List[Any]: '''simple docstring''' CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() _a : int =CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: _a : str =os.path.join(SCREAMING_SNAKE_CASE , """vocab.txt""" ) with open(SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens] ) ) _a : Optional[int] =CustomTokenizer(SCREAMING_SNAKE_CASE ) _a : Tuple =CustomProcessor(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(f"{USER}/test-dynamic-processor" , token=self._token ) _a : Optional[int] =Repository(SCREAMING_SNAKE_CASE , clone_from=f"{USER}/test-dynamic-processor" , token=self._token ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""", """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(SCREAMING_SNAKE_CASE , """tokenizer_config.json""" ) ) as f: _a : Dict =json.load(SCREAMING_SNAKE_CASE ) self.assertDictEqual( tokenizer_config["""auto_map"""] , { """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None], """AutoProcessor""": """custom_processing.CustomProcessor""", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE , """custom_feature_extraction.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE , """custom_tokenization.py""" ) ) ) self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE , """custom_processing.py""" ) ) ) repo.push_to_hub() _a : Dict =AutoProcessor.from_pretrained(f"{USER}/test-dynamic-processor" , trust_remote_code=SCREAMING_SNAKE_CASE ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , """CustomProcessor""" )
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''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ) -> Union[str, Any]: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> List[Any]: _a : List[str] =create_tensor(_UpperCAmelCase ) _a : Tuple =gather(_UpperCAmelCase ) assert gathered_tensor.tolist() == list(range(1 ,state.num_processes**2 + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ) -> Dict: _a : Any =[state.process_index] _a : List[Any] =gather_object(_UpperCAmelCase ) assert len(_UpperCAmelCase ) == state.num_processes, F"{gathered_obj}, {len(_UpperCAmelCase )} != {state.num_processes}" assert gathered_obj == list(range(state.num_processes ) ), F"{gathered_obj} != {list(range(state.num_processes ) )}" def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> Tuple: _a : Any =create_tensor(_UpperCAmelCase ) _a : Tuple =broadcast(_UpperCAmelCase ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 ,state.num_processes + 1 ) ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> int: # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: _a : Dict =torch.arange(state.num_processes + 1 ).to(state.device ) else: _a : List[Any] =torch.arange(state.num_processes ).to(state.device ) _a : Tuple =pad_across_processes(_UpperCAmelCase ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 ,state.num_processes ) ) + [0] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> List[str]: # For now runs on only two processes if state.num_processes != 2: return _a : Optional[Any] =create_tensor(_UpperCAmelCase ) _a : Optional[int] =reduce(_UpperCAmelCase ,"""sum""" ) _a : int =torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(_UpperCAmelCase ,_UpperCAmelCase ), F"{reduced_tensor} != {truth_tensor}" def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ) -> Union[str, Any]: # For now runs on only two processes if state.num_processes != 2: return _a : Tuple =create_tensor(_UpperCAmelCase ) _a : Any =reduce(_UpperCAmelCase ,"""mean""" ) _a : Any =torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(_UpperCAmelCase ,_UpperCAmelCase ), F"{reduced_tensor} != {truth_tensor}" def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ) -> Union[str, Any]: # For xla_spawn (TPUs) main() def SCREAMING_SNAKE_CASE_ ( ) -> str: _a : str =PartialState() state.print(F"State: {state}" ) state.print("""testing gather""" ) test_gather(_UpperCAmelCase ) state.print("""testing gather_object""" ) test_gather_object(_UpperCAmelCase ) state.print("""testing broadcast""" ) test_broadcast(_UpperCAmelCase ) state.print("""testing pad_across_processes""" ) test_pad_across_processes(_UpperCAmelCase ) state.print("""testing reduce_sum""" ) test_reduce_sum(_UpperCAmelCase ) state.print("""testing reduce_mean""" ) test_reduce_mean(_UpperCAmelCase ) if __name__ == "__main__": main()
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 json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class A__ ( unittest.TestCase ): def __init__( self :int , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict=7 , SCREAMING_SNAKE_CASE :Optional[Any]=3 , SCREAMING_SNAKE_CASE :List[str]=3_0 , SCREAMING_SNAKE_CASE :str=4_0_0 , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Optional[int]=None , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Tuple=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE :Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE :List[Any]=True , SCREAMING_SNAKE_CASE :str=1 / 2_5_5 , SCREAMING_SNAKE_CASE :Optional[int]=True , ) -> Dict: '''simple docstring''' # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p _a : Union[str, Any] =size if size is not None else {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} _a : int =parent _a : str =batch_size _a : Union[str, Any] =num_channels _a : Union[str, Any] =min_resolution _a : Dict =max_resolution _a : List[str] =do_resize _a : str =size _a : Any =do_normalize _a : Dict =image_mean _a : str =image_std _a : Dict =do_rescale _a : Optional[int] =rescale_factor _a : Optional[Any] =do_pad def __UpperCAmelCase ( self :List[str] ) -> int: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[int]=False ) -> Tuple: '''simple docstring''' if not batched: _a : Dict =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE , Image.Image ): _a , _a : Optional[Any] =image.size else: _a , _a : Optional[Any] =image.shape[1], image.shape[2] if w < h: _a : str =int(self.size["""shortest_edge"""] * h / w ) _a : Union[str, Any] =self.size["""shortest_edge"""] elif w > h: _a : Dict =self.size["""shortest_edge"""] _a : Tuple =int(self.size["""shortest_edge"""] * w / h ) else: _a : List[str] =self.size["""shortest_edge"""] _a : Tuple =self.size["""shortest_edge"""] else: _a : Optional[int] =[] for image in image_inputs: _a , _a : List[Any] =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _a : Optional[Any] =max(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : item[0] )[0] _a : Any =max(SCREAMING_SNAKE_CASE , key=lambda SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self :Tuple ) -> Optional[int]: '''simple docstring''' _a : List[str] =YolosImageProcessingTester(self ) @property def __UpperCAmelCase ( self :List[str] ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self :List[str] ) -> List[Any]: '''simple docstring''' _a : str =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' _a : List[str] =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE ) _a : Tuple =self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {"""shortest_edge""": 4_2, """longest_edge""": 8_4} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> int: '''simple docstring''' pass def __UpperCAmelCase ( self :Union[str, Any] ) -> Any: '''simple docstring''' # Initialize image_processing _a : Tuple =self.image_processing_class(**self.image_processor_dict ) # create random PIL images _a : Union[str, Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input _a : str =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _a , _a : Dict =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a , _a : List[Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE ) _a : Dict =image_processing(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self :Optional[int] ) -> Optional[int]: '''simple docstring''' # Initialize image_processing _a : List[str] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _a : Union[str, Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE , numpify=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input _a : Optional[Any] =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _a , _a : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a : Tuple =image_processing(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values _a , _a : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' # Initialize image_processing _a : str =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a : List[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE , torchify=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input _a : Optional[Any] =image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values _a , _a : str =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a : List[str] =image_processing(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values _a , _a : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE , batched=SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCAmelCase ( self :List[Any] ) -> List[str]: '''simple docstring''' # Initialize image_processings _a : int =self.image_processing_class(**self.image_processor_dict ) _a : Tuple =self.image_processing_class(do_resize=SCREAMING_SNAKE_CASE , do_normalize=SCREAMING_SNAKE_CASE , do_rescale=SCREAMING_SNAKE_CASE ) # create random PyTorch tensors _a : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE , torchify=SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors _a : List[Any] =image_processing_a.pad(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) _a : List[str] =image_processing_a(SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) self.assertTrue( torch.allclose(encoded_images_with_method["""pixel_values"""] , encoded_images["""pixel_values"""] , atol=1e-4 ) ) @slow def __UpperCAmelCase ( self :List[Any] ) -> Tuple: '''simple docstring''' # prepare image and target _a : List[str] =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: _a : int =json.loads(f.read() ) _a : List[str] ={"""image_id""": 3_9_7_6_9, """annotations""": target} # encode them _a : Union[str, Any] =YolosImageProcessor.from_pretrained("""hustvl/yolos-small""" ) _a : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE , annotations=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) # verify pixel values _a : int =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , SCREAMING_SNAKE_CASE ) _a : List[str] =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _a : int =torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , SCREAMING_SNAKE_CASE ) ) # verify boxes _a : Optional[Any] =torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , SCREAMING_SNAKE_CASE ) _a : str =torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _a : Optional[Any] =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , SCREAMING_SNAKE_CASE ) ) # verify is_crowd _a : str =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , SCREAMING_SNAKE_CASE ) ) # verify class_labels _a : Union[str, Any] =torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , SCREAMING_SNAKE_CASE ) ) # verify orig_size _a : Optional[int] =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , SCREAMING_SNAKE_CASE ) ) # verify size _a : List[Any] =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , SCREAMING_SNAKE_CASE ) ) @slow def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[Any]: '''simple docstring''' # prepare image, target and masks_path _a : Dict =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: _a : List[str] =json.loads(f.read() ) _a : Tuple ={"""file_name""": """000000039769.png""", """image_id""": 3_9_7_6_9, """segments_info""": target} _a : Union[str, Any] =pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them _a : Tuple =YolosImageProcessor(format="""coco_panoptic""" ) _a : int =image_processing(images=SCREAMING_SNAKE_CASE , annotations=SCREAMING_SNAKE_CASE , masks_path=SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) # verify pixel values _a : int =torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _a : int =torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , SCREAMING_SNAKE_CASE ) ) # verify boxes _a : Union[str, Any] =torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , SCREAMING_SNAKE_CASE ) _a : Dict =torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _a : Any =torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , SCREAMING_SNAKE_CASE ) ) # verify is_crowd _a : Tuple =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , SCREAMING_SNAKE_CASE ) ) # verify class_labels _a : Dict =torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , SCREAMING_SNAKE_CASE ) ) # verify masks _a : str =8_2_2_8_7_3 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , SCREAMING_SNAKE_CASE ) # verify orig_size _a : str =torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , SCREAMING_SNAKE_CASE ) ) # verify size _a : List[str] =torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , 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 inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class A__ ( UpperCAmelCase__ ): def __init__( self :str , SCREAMING_SNAKE_CASE :VQModel , SCREAMING_SNAKE_CASE :UNetaDModel , SCREAMING_SNAKE_CASE :DDIMScheduler ) -> Optional[Any]: '''simple docstring''' super().__init__() self.register_modules(vqvae=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self :Any , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :Optional[Union[torch.Generator, List[torch.Generator]]] = None , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , **SCREAMING_SNAKE_CASE :Dict , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' _a : Union[str, Any] =randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=SCREAMING_SNAKE_CASE , ) _a : Union[str, Any] =latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _a : Tuple =latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature _a : int ="""eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _a : Optional[int] ={} if accepts_eta: _a : List[Any] =eta for t in self.progress_bar(self.scheduler.timesteps ): _a : Union[str, Any] =self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # predict the noise residual _a : Any =self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ).sample # compute the previous noisy sample x_t -> x_t-1 _a : Tuple =self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample # decode the image latents with the VAE _a : Optional[Any] =self.vqvae.decode(SCREAMING_SNAKE_CASE ).sample _a : Optional[int] =(image / 2 + 0.5).clamp(0 , 1 ) _a : Tuple =image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _a : List[Any] =self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=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''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Dict = logging.get_logger(__name__) A__: int = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : Any = "biogpt" def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :List[str]=4_2_3_8_4 , SCREAMING_SNAKE_CASE :Optional[int]=1_0_2_4 , SCREAMING_SNAKE_CASE :Tuple=2_4 , SCREAMING_SNAKE_CASE :Optional[int]=1_6 , SCREAMING_SNAKE_CASE :Optional[int]=4_0_9_6 , SCREAMING_SNAKE_CASE :Optional[int]="gelu" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :List[str]=1_0_2_4 , SCREAMING_SNAKE_CASE :int=0.02 , SCREAMING_SNAKE_CASE :Any=1e-12 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :int=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=0.0 , SCREAMING_SNAKE_CASE :List[str]=1 , SCREAMING_SNAKE_CASE :Union[str, Any]=0 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , **SCREAMING_SNAKE_CASE :List[str] , ) -> Optional[Any]: '''simple docstring''' _a : str =vocab_size _a : Dict =max_position_embeddings _a : Optional[int] =hidden_size _a : Union[str, Any] =num_hidden_layers _a : List[Any] =num_attention_heads _a : Dict =intermediate_size _a : Any =hidden_act _a : Optional[int] =hidden_dropout_prob _a : int =attention_probs_dropout_prob _a : int =initializer_range _a : Union[str, Any] =layer_norm_eps _a : Union[str, Any] =scale_embedding _a : str =use_cache _a : List[str] =layerdrop _a : int =activation_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
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 pathlib import Path import numpy as np from PIL import Image def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ) -> np.ndarray: _a , _a , _a : Optional[int] =rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2_9_8_9 * r + 0.5_8_7_0 * g + 0.1_1_4_0 * b def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ) -> np.ndarray: return (gray > 127) & (gray <= 255) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : np.ndarray ) -> np.ndarray: _a : Optional[int] =np.zeros_like(_UpperCAmelCase ) _a : Tuple =np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image _a : int =image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): _a : Union[str, Any] =( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() _a : Dict =int(summation > 0 ) return output if __name__ == "__main__": # read original image A__: List[str] = Path(__file__).resolve().parent / '''image_data''' / '''lena.jpg''' A__: List[str] = np.array(Image.open(lena_path)) # kernel to be applied A__: List[Any] = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) A__: Optional[Any] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image A__: Optional[Any] = Image.fromarray(output).convert('''RGB''') pil_img.save('''result_dilation.png''')
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''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging A__: Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class A__ ( UpperCAmelCase__ ): def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :WhisperForConditionalGeneration , SCREAMING_SNAKE_CASE :WhisperProcessor , SCREAMING_SNAKE_CASE :AutoencoderKL , SCREAMING_SNAKE_CASE :CLIPTextModel , SCREAMING_SNAKE_CASE :CLIPTokenizer , SCREAMING_SNAKE_CASE :UNetaDConditionModel , SCREAMING_SNAKE_CASE :Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , SCREAMING_SNAKE_CASE :StableDiffusionSafetyChecker , SCREAMING_SNAKE_CASE :CLIPImageProcessor , ) -> Any: '''simple docstring''' super().__init__() if safety_checker is None: logger.warning( f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered""" """ results in services or applications open to the public. Both the diffusers team and Hugging Face""" """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling""" """ it only for use-cases that involve analyzing network behavior or auditing its results. For more""" """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 .""" ) self.register_modules( speech_model=SCREAMING_SNAKE_CASE , speech_processor=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Optional[Union[str, int]] = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": _a : int =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self :List[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :List[str]=1_6_0_0_0 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :int , ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =self.speech_processor.feature_extractor( SCREAMING_SNAKE_CASE , return_tensors="""pt""" , sampling_rate=SCREAMING_SNAKE_CASE ).input_features.to(self.device ) _a : Any =self.speech_model.generate(SCREAMING_SNAKE_CASE , max_length=4_8_0_0_0_0 ) _a : Dict =self.speech_processor.tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE , normalize=SCREAMING_SNAKE_CASE )[ 0 ] if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : List[Any] =1 elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ) else: raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE )}" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}." ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(SCREAMING_SNAKE_CASE )}." ) # get prompt text embeddings _a : Dict =self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) _a : Union[str, Any] =text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _a : Union[str, Any] =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" f" {self.tokenizer.model_max_length} tokens: {removed_text}" ) _a : str =text_input_ids[:, : self.tokenizer.model_max_length] _a : Dict =self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method _a , _a , _a : Any =text_embeddings.shape _a : str =text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1 ) _a : List[Any] =text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. _a : List[Any] =guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: _a : List[str] if negative_prompt is None: _a : str =[""""""] * batch_size elif type(SCREAMING_SNAKE_CASE ) is not type(SCREAMING_SNAKE_CASE ): raise TypeError( f"`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE )} !=" f" {type(SCREAMING_SNAKE_CASE )}." ) elif isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): _a : List[Any] =[negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE ): raise ValueError( f"`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE )}, but `prompt`:" f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" """ the batch size of `prompt`.""" ) else: _a : int =negative_prompt _a : Tuple =text_input_ids.shape[-1] _a : List[Any] =self.tokenizer( SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE , truncation=SCREAMING_SNAKE_CASE , return_tensors="""pt""" , ) _a : Tuple =self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _a : Dict =uncond_embeddings.shape[1] _a : Tuple =uncond_embeddings.repeat(1 , SCREAMING_SNAKE_CASE , 1 ) _a : Tuple =uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _a : Optional[Any] =torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. _a : List[Any] =(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) _a : Tuple =text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps _a : List[Any] =torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE ).to( self.device ) else: _a : str =torch.randn(SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , device=self.device , dtype=SCREAMING_SNAKE_CASE ) else: if latents.shape != latents_shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) _a : Tuple =latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand _a : int =self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler _a : List[str] =latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] _a : Optional[Any] ="""eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) _a : Optional[int] ={} if accepts_eta: _a : Optional[int] =eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance _a : List[Any] =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _a : Optional[Any] =self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # predict the noise residual _a : Optional[Any] =self.unet(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , encoder_hidden_states=SCREAMING_SNAKE_CASE ).sample # perform guidance if do_classifier_free_guidance: _a , _a : Tuple =noise_pred.chunk(2 ) _a : Optional[Any] =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 _a : Union[str, Any] =self.scheduler.step(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : Tuple =1 / 0.18_215 * latents _a : Union[str, Any] =self.vae.decode(SCREAMING_SNAKE_CASE ).sample _a : int =(image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 _a : List[str] =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _a : Optional[Any] =self.numpy_to_pil(SCREAMING_SNAKE_CASE ) if not return_dict: return image return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE , nsfw_content_detected=SCREAMING_SNAKE_CASE )
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 os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) A__: Union[str, Any] = pytest.mark.integration @pytest.mark.parametrize("""path""" ,["""paws""", """csv"""] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ) -> Optional[int]: inspect_dataset(_UpperCAmelCase ,_UpperCAmelCase ) _a : Any =path + """.py""" assert script_name in os.listdir(_UpperCAmelCase ) assert "__pycache__" not in os.listdir(_UpperCAmelCase ) @pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.parametrize("""path""" ,["""accuracy"""] ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: inspect_metric(_UpperCAmelCase ,_UpperCAmelCase ) _a : List[Any] =path + """.py""" assert script_name in os.listdir(_UpperCAmelCase ) assert "__pycache__" not in os.listdir(_UpperCAmelCase ) @pytest.mark.parametrize( """path, config_name, expected_splits""" ,[ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ) -> str: _a : str =get_dataset_config_info(_UpperCAmelCase ,config_name=_UpperCAmelCase ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" ,[ ("""paws""", None, ValueError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Optional[Any] ) -> Tuple: with pytest.raises(_UpperCAmelCase ): get_dataset_config_info(_UpperCAmelCase ,config_name=_UpperCAmelCase ) @pytest.mark.parametrize( """path, expected""" ,[ ("""squad""", """plain_text"""), ("""acronym_identification""", """default"""), ("""lhoestq/squad""", """plain_text"""), ("""lhoestq/test""", """default"""), ("""lhoestq/demo1""", """lhoestq--demo1"""), ("""dalle-mini/wit""", """dalle-mini--wit"""), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Tuple ) -> str: _a : Optional[Any] =get_dataset_config_names(_UpperCAmelCase ) assert expected in config_names @pytest.mark.parametrize( """path, expected_configs, expected_splits_in_first_config""" ,[ ("""squad""", ["""plain_text"""], ["""train""", """validation"""]), ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]), ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Any ) -> Optional[int]: _a : Union[str, Any] =get_dataset_infos(_UpperCAmelCase ) assert list(infos.keys() ) == expected_configs _a : Tuple =expected_configs[0] assert expected_config in infos _a : str =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( """path, expected_config, expected_splits""" ,[ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Dict ) -> Optional[int]: _a : Dict =get_dataset_infos(_UpperCAmelCase ) assert expected_config in infos _a : Union[str, Any] =infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" ,[ ("""paws""", None, ValueError), ] ,) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ) -> Any: with pytest.raises(_UpperCAmelCase ): get_dataset_split_names(_UpperCAmelCase ,config_name=_UpperCAmelCase )
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__: 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
'''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 import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class A__ : __UpperCamelCase : Tuple = BlenderbotSmallConfig __UpperCamelCase : int = {} __UpperCamelCase : Union[str, Any] = "gelu" def __init__( self :Any , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any=1_3 , SCREAMING_SNAKE_CASE :Optional[int]=7 , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :Any=False , SCREAMING_SNAKE_CASE :str=9_9 , SCREAMING_SNAKE_CASE :Optional[Any]=3_2 , SCREAMING_SNAKE_CASE :Optional[int]=2 , SCREAMING_SNAKE_CASE :List[Any]=4 , SCREAMING_SNAKE_CASE :List[Any]=3_7 , SCREAMING_SNAKE_CASE :List[Any]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=0.1 , SCREAMING_SNAKE_CASE :Optional[int]=2_0 , SCREAMING_SNAKE_CASE :Optional[int]=2 , SCREAMING_SNAKE_CASE :List[str]=1 , SCREAMING_SNAKE_CASE :Tuple=0 , ) -> str: '''simple docstring''' _a : Optional[Any] =parent _a : Dict =batch_size _a : Any =seq_length _a : List[Any] =is_training _a : Any =use_labels _a : str =vocab_size _a : List[Any] =hidden_size _a : Optional[Any] =num_hidden_layers _a : List[str] =num_attention_heads _a : str =intermediate_size _a : List[Any] =hidden_dropout_prob _a : List[str] =attention_probs_dropout_prob _a : Optional[Any] =max_position_embeddings _a : Any =eos_token_id _a : Dict =pad_token_id _a : Optional[int] =bos_token_id def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : Any =ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) _a : Union[str, Any] =tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) _a : Any =tf.concat([input_ids, eos_tensor] , axis=1 ) _a : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Optional[int] =self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) _a : Union[str, Any] =prepare_blenderbot_small_inputs_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return config, inputs_dict def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any ) -> List[Any]: '''simple docstring''' _a : Any =TFBlenderbotSmallModel(config=SCREAMING_SNAKE_CASE ).get_decoder() _a : Optional[int] =inputs_dict["""input_ids"""] _a : Optional[int] =input_ids[:1, :] _a : List[str] =inputs_dict["""attention_mask"""][:1, :] _a : Optional[int] =inputs_dict["""head_mask"""] _a : Optional[Any] =1 # first forward pass _a : Optional[int] =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , head_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE ) _a , _a : List[Any] =outputs.to_tuple() # create hypothetical next token and extent to next_input_ids _a : str =ids_tensor((self.batch_size, 3) , config.vocab_size ) _a : List[Any] =tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and _a : str =tf.concat([input_ids, next_tokens] , axis=-1 ) _a : Dict =tf.concat([attention_mask, next_attn_mask] , axis=-1 ) _a : str =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE )[0] _a : Tuple =model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice _a : List[Any] =int(ids_tensor((1,) , output_from_past.shape[-1] ) ) _a : Union[str, Any] =output_from_no_past[:, -3:, random_slice_idx] _a : str =output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , rtol=1e-3 ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Optional[int]=None ,) -> Tuple: if attention_mask is None: _a : List[str] =tf.cast(tf.math.not_equal(_UpperCAmelCase ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: _a : Any =tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: _a : int =tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _a : Any =tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _a : Any =tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : str = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __UpperCamelCase : Any = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __UpperCamelCase : int = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __UpperCamelCase : List[Any] = True __UpperCamelCase : Optional[int] = False __UpperCamelCase : List[Any] = False def __UpperCAmelCase ( self :int ) -> Optional[Any]: '''simple docstring''' _a : Tuple =TFBlenderbotSmallModelTester(self ) _a : Optional[Any] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[Any] ) -> Tuple: '''simple docstring''' _a : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE ) @require_tokenizers @require_tf class A__ ( unittest.TestCase ): __UpperCamelCase : Union[str, Any] = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] __UpperCamelCase : Union[str, Any] = "facebook/blenderbot_small-90M" @cached_property def __UpperCAmelCase ( self :Union[str, Any] ) -> Any: '''simple docstring''' # use "old" tokenizer here because of bug when downloading new tokenizer return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def __UpperCAmelCase ( self :int ) -> int: '''simple docstring''' _a : Tuple =TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =self.tokenizer(self.src_text , return_tensors="""tf""" ) _a : List[str] =self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=SCREAMING_SNAKE_CASE , ) _a : str =self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=SCREAMING_SNAKE_CASE )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
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''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionAttendAndExcitePipeline, UNetaDConditionModel, ) from diffusers.utils import load_numpy, skip_mps, slow from diffusers.utils.testing_utils import require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin A__: Optional[Any] = False @skip_mps class A__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : str = StableDiffusionAttendAndExcitePipeline __UpperCamelCase : Dict = False __UpperCamelCase : List[Any] = TEXT_TO_IMAGE_PARAMS __UpperCamelCase : Tuple = TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"} ) __UpperCamelCase : List[str] = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def __UpperCAmelCase ( cls :int ) -> Any: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls :Dict ) -> Optional[Any]: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> int: '''simple docstring''' torch.manual_seed(0 ) _a : Any =UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=1 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , attention_head_dim=(2, 4) , use_linear_projection=SCREAMING_SNAKE_CASE , ) _a : Optional[int] =DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=SCREAMING_SNAKE_CASE , set_alpha_to_one=SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) _a : Dict =AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) _a : Any =CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act="""gelu""" , projection_dim=5_1_2 , ) _a : Dict =CLIPTextModel(SCREAMING_SNAKE_CASE ) _a : int =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _a : Any ={ """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :int=0 ) -> str: '''simple docstring''' if str(SCREAMING_SNAKE_CASE ).startswith("""mps""" ): _a : Any =torch.manual_seed(SCREAMING_SNAKE_CASE ) else: _a : Dict =torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) _a : List[Any] ={ """prompt""": """a cat and a frog""", """token_indices""": [2, 5], """generator""": generator, """num_inference_steps""": 1, """guidance_scale""": 6.0, """output_type""": """numpy""", """max_iter_to_alter""": 2, """thresholds""": {0: 0.7}, } return inputs def __UpperCAmelCase ( self :Dict ) -> str: '''simple docstring''' _a : List[str] ="""cpu""" _a : Union[str, Any] =self.get_dummy_components() _a : Tuple =self.pipeline_class(**SCREAMING_SNAKE_CASE ) pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =pipe(**SCREAMING_SNAKE_CASE ).images _a : int =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 6_4, 6_4, 3) ) _a : List[Any] =np.array( [0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496] ) _a : Tuple =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE , 1e-3 ) def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def __UpperCAmelCase ( self :Optional[Any] ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __UpperCAmelCase ( self :List[Any] ) -> int: '''simple docstring''' self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def __UpperCAmelCase ( self :List[str] ) -> str: '''simple docstring''' super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' super().test_save_load_local(expected_max_difference=5e-4 ) def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class A__ ( unittest.TestCase ): @classmethod def __UpperCAmelCase ( cls :List[Any] ) -> List[str]: '''simple docstring''' super().setUpClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE ) @classmethod def __UpperCAmelCase ( cls :List[Any] ) -> List[Any]: '''simple docstring''' super().tearDownClass() torch.use_deterministic_algorithms(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[Any] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCAmelCase ( self :Optional[int] ) -> Tuple: '''simple docstring''' _a : Any =torch.manual_seed(5_1 ) _a : str =StableDiffusionAttendAndExcitePipeline.from_pretrained( """CompVis/stable-diffusion-v1-4""" , safety_checker=SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa ) pipe.to("""cuda""" ) _a : List[str] ="""a painting of an elephant with glasses""" _a : Dict =[5, 7] _a : str =pipe( prompt=SCREAMING_SNAKE_CASE , token_indices=SCREAMING_SNAKE_CASE , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , max_iter_to_alter=5 , output_type="""numpy""" , ).images[0] _a : str =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy""" ) assert np.abs((expected_image - image).max() ) < 5e-1
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 __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
'''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 timeit import timeit def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) _a : List[str] =0 while number: number &= number - 1 result += 1 return result def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> int: if number < 0: raise ValueError("""the value of input must not be negative""" ) _a : Any =0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def SCREAMING_SNAKE_CASE_ ( ) -> None: def do_benchmark(_UpperCAmelCase : int ) -> None: _a : Optional[int] ="""import __main__ as z""" print(F"Benchmark when {number = }:" ) print(F"{get_set_bits_count_using_modulo_operator(_UpperCAmelCase ) = }" ) _a : Union[str, Any] =timeit("""z.get_set_bits_count_using_modulo_operator(25)""" ,setup=_UpperCAmelCase ) print(F"timeit() runs in {timing} seconds" ) print(F"{get_set_bits_count_using_brian_kernighans_algorithm(_UpperCAmelCase ) = }" ) _a : Union[str, Any] =timeit( """z.get_set_bits_count_using_brian_kernighans_algorithm(25)""" ,setup=_UpperCAmelCase ,) print(F"timeit() runs in {timing} seconds" ) for number in (25, 37, 58, 0): do_benchmark(_UpperCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
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''' from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Any = logging.get_logger(__name__) A__: Any = { '''huggingface/time-series-transformer-tourism-monthly''': ( '''https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json''' ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : str = "time_series_transformer" __UpperCamelCase : Tuple = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", "num_hidden_layers": "encoder_layers", } def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :Optional[int] = None , SCREAMING_SNAKE_CASE :str = "student_t" , SCREAMING_SNAKE_CASE :str = "nll" , SCREAMING_SNAKE_CASE :int = 1 , SCREAMING_SNAKE_CASE :List[int] = [1, 2, 3, 4, 5, 6, 7] , SCREAMING_SNAKE_CASE :Optional[Union[str, bool]] = "mean" , SCREAMING_SNAKE_CASE :int = 0 , SCREAMING_SNAKE_CASE :int = 0 , SCREAMING_SNAKE_CASE :int = 0 , SCREAMING_SNAKE_CASE :int = 0 , SCREAMING_SNAKE_CASE :Optional[List[int]] = None , SCREAMING_SNAKE_CASE :Optional[List[int]] = None , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 3_2 , SCREAMING_SNAKE_CASE :int = 2 , SCREAMING_SNAKE_CASE :int = 2 , SCREAMING_SNAKE_CASE :int = 2 , SCREAMING_SNAKE_CASE :int = 2 , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :str = "gelu" , SCREAMING_SNAKE_CASE :int = 6_4 , SCREAMING_SNAKE_CASE :float = 0.1 , SCREAMING_SNAKE_CASE :float = 0.1 , SCREAMING_SNAKE_CASE :float = 0.1 , SCREAMING_SNAKE_CASE :float = 0.1 , SCREAMING_SNAKE_CASE :float = 0.1 , SCREAMING_SNAKE_CASE :int = 1_0_0 , SCREAMING_SNAKE_CASE :float = 0.02 , SCREAMING_SNAKE_CASE :str=True , **SCREAMING_SNAKE_CASE :Tuple , ) -> str: '''simple docstring''' # time series specific configuration _a : Dict =prediction_length _a : Optional[int] =context_length or prediction_length _a : int =distribution_output _a : Any =loss _a : List[Any] =input_size _a : Optional[Any] =num_time_features _a : Optional[Any] =lags_sequence _a : str =scaling _a : Optional[Any] =num_dynamic_real_features _a : int =num_static_real_features _a : Optional[Any] =num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) _a : List[Any] =cardinality else: _a : Union[str, Any] =[0] if embedding_dimension and num_static_categorical_features > 0: if len(SCREAMING_SNAKE_CASE ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) _a : str =embedding_dimension else: _a : Optional[int] =[min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality] _a : Dict =num_parallel_samples # Transformer architecture configuration _a : Optional[Any] =input_size * len(SCREAMING_SNAKE_CASE ) + self._number_of_features _a : int =d_model _a : List[Any] =encoder_attention_heads _a : List[str] =decoder_attention_heads _a : Optional[Any] =encoder_ffn_dim _a : Dict =decoder_ffn_dim _a : Union[str, Any] =encoder_layers _a : Union[str, Any] =decoder_layers _a : int =dropout _a : Union[str, Any] =attention_dropout _a : List[str] =activation_dropout _a : Optional[Any] =encoder_layerdrop _a : str =decoder_layerdrop _a : Any =activation_function _a : Any =init_std _a : Any =use_cache super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def __UpperCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
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 argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def SCREAMING_SNAKE_CASE_ ( ) -> List[str]: _a : Optional[int] ="""https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg""" _a : Union[str, Any] =Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ).convert("""RGB""" ) return image def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: _a : List[str] =[] # fmt: off # vision encoder rename_keys.append(("""visual_encoder.cls_token""", """vision_model.embeddings.class_embedding""") ) rename_keys.append(("""visual_encoder.pos_embed""", """vision_model.embeddings.position_embedding""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.weight""", """vision_model.embeddings.patch_embedding.weight""") ) rename_keys.append(("""visual_encoder.patch_embed.proj.bias""", """vision_model.embeddings.patch_embedding.bias""") ) rename_keys.append(("""ln_vision.weight""", """vision_model.post_layernorm.weight""") ) rename_keys.append(("""ln_vision.bias""", """vision_model.post_layernorm.bias""") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F"visual_encoder.blocks.{i}.norm1.weight", F"vision_model.encoder.layers.{i}.layer_norm1.weight") ) rename_keys.append((F"visual_encoder.blocks.{i}.norm1.bias", F"vision_model.encoder.layers.{i}.layer_norm1.bias") ) rename_keys.append((F"visual_encoder.blocks.{i}.norm2.weight", F"vision_model.encoder.layers.{i}.layer_norm2.weight") ) rename_keys.append((F"visual_encoder.blocks.{i}.norm2.bias", F"vision_model.encoder.layers.{i}.layer_norm2.bias") ) rename_keys.append((F"visual_encoder.blocks.{i}.attn.qkv.weight", F"vision_model.encoder.layers.{i}.self_attn.qkv.weight") ) rename_keys.append((F"visual_encoder.blocks.{i}.attn.proj.weight", F"vision_model.encoder.layers.{i}.self_attn.projection.weight",) ) rename_keys.append((F"visual_encoder.blocks.{i}.attn.proj.bias", F"vision_model.encoder.layers.{i}.self_attn.projection.bias") ) rename_keys.append((F"visual_encoder.blocks.{i}.mlp.fc1.weight", F"vision_model.encoder.layers.{i}.mlp.fc1.weight") ) rename_keys.append((F"visual_encoder.blocks.{i}.mlp.fc1.bias", F"vision_model.encoder.layers.{i}.mlp.fc1.bias") ) rename_keys.append((F"visual_encoder.blocks.{i}.mlp.fc2.weight", F"vision_model.encoder.layers.{i}.mlp.fc2.weight") ) rename_keys.append((F"visual_encoder.blocks.{i}.mlp.fc2.bias", F"vision_model.encoder.layers.{i}.mlp.fc2.bias") ) # QFormer rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.weight""", """qformer.embeddings.layernorm.weight""") ) rename_keys.append(("""Qformer.bert.embeddings.LayerNorm.bias""", """qformer.embeddings.layernorm.bias""") ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ) -> str: _a : Optional[int] =dct.pop(_UpperCAmelCase ) _a : Tuple =val def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Any ) -> Optional[int]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases _a : Optional[int] =state_dict.pop(F"visual_encoder.blocks.{i}.attn.q_bias" ) _a : Any =state_dict.pop(F"visual_encoder.blocks.{i}.attn.v_bias" ) # next, set bias in the state dict _a : List[str] =torch.cat((q_bias, torch.zeros_like(_UpperCAmelCase ,requires_grad=_UpperCAmelCase ), v_bias) ) _a : Union[str, Any] =qkv_bias def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Dict ) -> List[Any]: _a : List[Any] =364 if """coco""" in model_name else 224 _a : Tuple =InstructBlipVisionConfig(image_size=_UpperCAmelCase ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: _a : List[str] =TaConfig.from_pretrained("""google/flan-t5-xl""" ,dense_act_fn="""gelu""" ,bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: _a : Optional[Any] =TaConfig.from_pretrained("""google/flan-t5-xxl""" ,dense_act_fn="""gelu""" ,bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: _a : Union[str, Any] =LlamaConfig.from_pretrained("""decapoda-research/llama-7b-hf""" ,vocab_size=32001 ).to_dict() elif "vicuna-13b" in model_name: _a : Optional[int] =LlamaConfig.from_pretrained("""decapoda-research/llama-13b-hf""" ,vocab_size=32001 ).to_dict() else: raise ValueError("""Model name not supported""" ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 _a : int =InstructBlipQFormerConfig(vocab_size=30523 ).to_dict() _a : Tuple =InstructBlipConfig(vision_config=_UpperCAmelCase ,text_config=_UpperCAmelCase ,qformer_config=_UpperCAmelCase ) return config, image_size @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any=None ,_UpperCAmelCase : List[str]=False ) -> Dict: _a : Optional[Any] =AutoTokenizer.from_pretrained("""bert-base-uncased""" ,truncation_side="""left""" ) qformer_tokenizer.add_special_tokens({"""bos_token""": """[DEC]"""} ) if "t5" in model_name: _a : Union[str, Any] =TaTokenizerFast.from_pretrained("""google/flan-t5-xl""" ,truncation_side="""left""" ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) _a : str =LlamaTokenizerFast.from_pretrained( """huggyllama/llama-7b""" ,truncation_side="""left""" ,bos_token="""</s>""" ,unk_token="""</s>""" ) tokenizer.add_special_tokens({"""pad_token""": """[PAD]"""} ) _a , _a : Tuple =get_blipa_config(_UpperCAmelCase ) _a : Tuple =InstructBlipForConditionalGeneration(_UpperCAmelCase ).eval() _a : List[str] ={ """instructblip-vicuna-7b""": ("""blip2_vicuna_instruct""", """vicuna7b"""), """instructblip-vicuna-13b""": ("""blip2_vicuna_instruct""", """vicuna13b"""), """instructblip-flan-t5-xl""": ("""blip2_t5_instruct""", """flant5xl"""), """instructblip-flan-t5-xxl""": ("""blip2_t5_instruct""", """flant5xxl"""), } _a , _a : Optional[Any] =model_name_to_original[model_name] # load original model print("""Loading original model...""" ) _a : Optional[Any] ="""cuda:1""" if torch.cuda.is_available() else """cpu""" _a : str ="""cuda:2""" if torch.cuda.is_available() else """cpu""" _a , _a , _a : int =load_model_and_preprocess( name=_UpperCAmelCase ,model_type=_UpperCAmelCase ,is_eval=_UpperCAmelCase ,device=_UpperCAmelCase ) original_model.eval() print("""Done!""" ) # update state dict keys _a : Tuple =original_model.state_dict() _a : Dict =create_rename_keys(_UpperCAmelCase ) for src, dest in rename_keys: rename_key(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): _a : List[str] =state_dict.pop(_UpperCAmelCase ) if key.startswith("""Qformer.bert""" ): _a : int =key.replace("""Qformer.bert""" ,"""qformer""" ) if "attention.self" in key: _a : str =key.replace("""self""" ,"""attention""" ) if "llm_proj" in key: _a : List[str] =key.replace("""llm_proj""" ,"""language_projection""" ) if "t5_proj" in key: _a : Union[str, Any] =key.replace("""t5_proj""" ,"""language_projection""" ) if key.startswith("""llm_model""" ): _a : Dict =key.replace("""llm_model""" ,"""language_model""" ) if key.startswith("""t5""" ): _a : Dict =key.replace("""t5""" ,"""language""" ) _a : Union[str, Any] =val # read in qv biases read_in_q_v_bias(_UpperCAmelCase ,_UpperCAmelCase ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) _a : Optional[int] =load_demo_image() _a : Tuple ="""What is unusual about this image?""" # create processor _a : List[Any] =BlipImageProcessor( size={"""height""": image_size, """width""": image_size} ,image_mean=_UpperCAmelCase ,image_std=_UpperCAmelCase ) _a : List[str] =InstructBlipProcessor( image_processor=_UpperCAmelCase ,tokenizer=_UpperCAmelCase ,qformer_tokenizer=_UpperCAmelCase ,) _a : Tuple =processor(images=_UpperCAmelCase ,text=_UpperCAmelCase ,return_tensors="""pt""" ).to(_UpperCAmelCase ) # make sure processor creates exact same pixel values _a : Tuple =vis_processors["""eval"""](_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) _a : str =inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) ,_UpperCAmelCase ) original_model.to(_UpperCAmelCase ) hf_model.to(_UpperCAmelCase ) with torch.no_grad(): if "vicuna" in model_name: _a : List[Any] =original_model({"""image""": original_pixel_values, """text_input""": [prompt]} ).logits _a : str =hf_model(**_UpperCAmelCase ).logits else: _a : str =original_model( {"""image""": original_pixel_values, """text_input""": [prompt], """text_output""": ["""\n"""]} ).logits _a : Optional[int] =tokenizer("""\n""" ,return_tensors="""pt""" ).input_ids.to(_UpperCAmelCase ) _a : List[str] =label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id ,-100 ) _a : List[Any] =hf_model(**_UpperCAmelCase ,labels=_UpperCAmelCase ).logits print("""First values of original logits:""" ,original_logits[0, :3, :3] ) print("""First values of HF logits:""" ,logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape _a : str =1e-4 if """vicuna""" in model_name else 1e-5 assert torch.allclose(original_logits.to(logits.device ) ,_UpperCAmelCase ,atol=_UpperCAmelCase ) print("""Looks ok!""" ) print("""Generating with original model...""" ) _a : Union[str, Any] =original_model.generate({"""image""": original_pixel_values, """prompt""": prompt} ,num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print("""Generating with HF model...""" ) _a : Dict =hf_model.generate( **_UpperCAmelCase ,do_sample=_UpperCAmelCase ,num_beams=5 ,max_length=256 ,min_length=1 ,top_p=0.9 ,repetition_penalty=1.5 ,length_penalty=1.0 ,temperature=1 ,) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? _a : Any =2 print("""Original generation:""" ,_UpperCAmelCase ) _a : Optional[int] =processor.batch_decode(_UpperCAmelCase ,skip_special_tokens=_UpperCAmelCase ) _a : int =[text.strip() for text in output_text] print("""HF generation:""" ,_UpperCAmelCase ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_UpperCAmelCase ) hf_model.save_pretrained(_UpperCAmelCase ) if push_to_hub: processor.push_to_hub(F"Salesforce/{model_name}" ) hf_model.push_to_hub(F"Salesforce/{model_name}" ) if __name__ == "__main__": A__: Optional[Any] = argparse.ArgumentParser() A__: Any = [ '''instructblip-vicuna-7b''', '''instructblip-vicuna-13b''', '''instructblip-flan-t5-xl''', '''instructblip-flan-t5-xxl''', ] parser.add_argument( '''--model_name''', default='''instructblip-flan-t5-xl''', choices=choices, type=str, help='''Path to hf config.json of model to convert''', ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to push the model and processor to the hub after converting''', ) A__: int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
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 inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class A__ ( unittest.TestCase ): __UpperCamelCase : Dict = inspect.getfile(accelerate.test_utils ) __UpperCamelCase : Dict = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_cli.py"] ) __UpperCamelCase : List[str] = ["accelerate", "launch"] __UpperCamelCase : List[str] = Path.home() / ".cache/huggingface/accelerate" __UpperCamelCase : Optional[int] = "default_config.yaml" __UpperCamelCase : Optional[Any] = config_folder / config_file __UpperCamelCase : int = config_folder / "_default_config.yaml" __UpperCamelCase : Union[str, Any] = Path("tests/test_configs" ) @classmethod def __UpperCAmelCase ( cls :List[Any] ) -> List[str]: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def __UpperCAmelCase ( cls :int ) -> Union[str, Any]: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def __UpperCAmelCase ( self :List[Any] ) -> Any: '''simple docstring''' _a : Dict =self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def __UpperCAmelCase ( self :List[Any] ) -> Union[str, Any]: '''simple docstring''' for config in sorted(self.test_config_path.glob("""**/*.yaml""" ) ): with self.subTest(config_file=SCREAMING_SNAKE_CASE ): execute_subprocess_async( self.base_cmd + ["""--config_file""", str(SCREAMING_SNAKE_CASE ), self.test_file_path] , env=os.environ.copy() ) def __UpperCAmelCase ( self :Any ) -> int: '''simple docstring''' execute_subprocess_async(["""accelerate""", """test"""] , env=os.environ.copy() ) class A__ ( unittest.TestCase ): __UpperCamelCase : List[str] = "test-tpu" __UpperCamelCase : Dict = "us-central1-a" __UpperCamelCase : Any = "ls" __UpperCamelCase : int = ["accelerate", "tpu-config"] __UpperCamelCase : str = "cd /usr/share" __UpperCamelCase : str = "tests/test_samples/test_command_file.sh" __UpperCamelCase : List[Any] = "Running gcloud compute tpus tpu-vm ssh" def __UpperCAmelCase ( self :Tuple ) -> int: '''simple docstring''' _a : Optional[int] =run_command( self.cmd + ["""--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' _a : Optional[Any] =run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command""", self.command, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : str =run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :List[Any] ) -> Union[str, Any]: '''simple docstring''' _a : str =run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Union[str, Any] ) -> List[Any]: '''simple docstring''' _a : Optional[Any] =run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--command""", self.command, """--command""", """echo \"Hello World\"""", """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :List[Any] ) -> Union[str, Any]: '''simple docstring''' _a : str =run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--command_file""", self.command_file, """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Optional[Any]: '''simple docstring''' _a : Any =run_command( self.cmd + [ """--config_file""", """tests/test_configs/0_12_0.yaml""", """--command_file""", self.command_file, """--tpu_zone""", self.tpu_zone, """--tpu_name""", self.tpu_name, """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Union[str, Any] ) -> int: '''simple docstring''' _a : Any =run_command( self.cmd + ["""--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--debug"""] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all" , SCREAMING_SNAKE_CASE , ) def __UpperCAmelCase ( self :Tuple ) -> Dict: '''simple docstring''' _a : Any =run_command( self.cmd + [ """--config_file""", """tests/test_configs/latest.yaml""", """--install_accelerate""", """--accelerate_version""", """12.0.0""", """--debug""", ] , return_stdout=SCREAMING_SNAKE_CASE , ) self.assertIn( f"{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all" , SCREAMING_SNAKE_CASE , )
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 import os import tempfile import unittest from transformers import ConvBertConfig, 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 ( TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertModel, ) class A__ : def __init__( self :Optional[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[Any]=1_3 , SCREAMING_SNAKE_CASE :int=7 , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :Dict=True , SCREAMING_SNAKE_CASE :int=True , SCREAMING_SNAKE_CASE :int=9_9 , SCREAMING_SNAKE_CASE :Tuple=3_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Dict=4 , SCREAMING_SNAKE_CASE :int=3_7 , SCREAMING_SNAKE_CASE :List[Any]="gelu" , SCREAMING_SNAKE_CASE :int=0.1 , SCREAMING_SNAKE_CASE :List[str]=0.1 , SCREAMING_SNAKE_CASE :Dict=5_1_2 , SCREAMING_SNAKE_CASE :List[Any]=1_6 , SCREAMING_SNAKE_CASE :Optional[int]=2 , SCREAMING_SNAKE_CASE :Any=0.02 , SCREAMING_SNAKE_CASE :Union[str, Any]=3 , SCREAMING_SNAKE_CASE :Optional[int]=4 , SCREAMING_SNAKE_CASE :List[Any]=None , ) -> str: '''simple docstring''' _a : int =parent _a : List[Any] =1_3 _a : str =7 _a : List[str] =True _a : Optional[Any] =True _a : str =True _a : List[str] =True _a : str =9_9 _a : Optional[Any] =3_8_4 _a : str =2 _a : List[str] =4 _a : Optional[Any] =3_7 _a : Optional[Any] ="""gelu""" _a : List[str] =0.1 _a : Dict =0.1 _a : List[str] =5_1_2 _a : List[str] =1_6 _a : Union[str, Any] =2 _a : Optional[int] =0.02 _a : int =3 _a : Any =4 _a : Optional[int] =1_2_8 _a : Any =2 _a : Optional[int] =9 _a : int =1 _a : List[Any] =None def __UpperCAmelCase ( self :Optional[int] ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : Tuple =None if self.use_input_mask: _a : str =random_attention_mask([self.batch_size, self.seq_length] ) _a : Dict =None if self.use_token_type_ids: _a : int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : int =None _a : List[Any] =None _a : Any =None if self.use_labels: _a : Optional[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : Any =ids_tensor([self.batch_size] , self.num_choices ) _a : Optional[int] =ConvBertConfig( 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 :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Tuple ) -> Dict: '''simple docstring''' _a : Optional[Any] =TFConvBertModel(config=SCREAMING_SNAKE_CASE ) _a : Dict ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : Dict =[input_ids, input_mask] _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) _a : Optional[int] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[Any] ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =TFConvBertForMaskedLM(config=SCREAMING_SNAKE_CASE ) _a : Optional[Any] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : List[str] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCAmelCase ( self :Dict , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :str ) -> str: '''simple docstring''' _a : str =self.num_labels _a : Dict =TFConvBertForSequenceClassification(config=SCREAMING_SNAKE_CASE ) _a : List[Any] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :List[Any] ) -> str: '''simple docstring''' _a : str =self.num_choices _a : int =TFConvBertForMultipleChoice(config=SCREAMING_SNAKE_CASE ) _a : List[Any] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Dict =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Optional[Any] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Dict ={ """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } _a : Tuple =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> Tuple: '''simple docstring''' _a : Optional[int] =self.num_labels _a : List[str] =TFConvBertForTokenClassification(config=SCREAMING_SNAKE_CASE ) _a : Optional[int] ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : List[str] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple ) -> str: '''simple docstring''' _a : Optional[Any] =TFConvBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE ) _a : Dict ={ """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _a : List[Any] =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 :Tuple ) -> List[str]: '''simple docstring''' _a : int =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Dict =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 : str = ( ( TFConvBertModel, TFConvBertForMaskedLM, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase : Union[str, Any] = ( { "feature-extraction": TFConvBertModel, "fill-mask": TFConvBertForMaskedLM, "question-answering": TFConvBertForQuestionAnswering, "text-classification": TFConvBertForSequenceClassification, "token-classification": TFConvBertForTokenClassification, "zero-shot": TFConvBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : Any = False __UpperCamelCase : List[Any] = False __UpperCamelCase : str = False def __UpperCAmelCase ( self :Tuple ) -> Tuple: '''simple docstring''' _a : List[Any] =TFConvBertModelTester(self ) _a : Any =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCAmelCase ( self :Tuple ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' _a : Union[str, 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 : 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] ) -> Union[str, Any]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' _a : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Tuple ) -> List[str]: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> List[Any]: '''simple docstring''' _a : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> Dict: '''simple docstring''' _a , _a : Any =self.model_tester.prepare_config_and_inputs_for_common() _a : Tuple =True _a : List[Any] =True if hasattr(SCREAMING_SNAKE_CASE , """use_cache""" ): _a : Dict =True _a : int =getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) _a : Any =getattr(self.model_tester , """key_length""" , SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _a : List[str] =self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a : List[Any] =model_class(SCREAMING_SNAKE_CASE ) _a : Any =len(model(SCREAMING_SNAKE_CASE ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE , saved_model=SCREAMING_SNAKE_CASE ) _a : int =os.path.join(SCREAMING_SNAKE_CASE , """saved_model""" , """1""" ) _a : Union[str, Any] =tf.keras.models.load_model(SCREAMING_SNAKE_CASE ) _a : Any =model(SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: _a : Optional[Any] =outputs["""encoder_hidden_states"""] _a : Dict =outputs["""encoder_attentions"""] else: _a : Tuple =outputs["""hidden_states"""] _a : Any =outputs["""attentions"""] self.assertEqual(len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) _a : int =getattr( self.model_tester , """expected_num_hidden_layers""" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE ) self.assertListEqual( list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , ) self.assertEqual(len(SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) @slow def __UpperCAmelCase ( self :Union[str, Any] ) -> str: '''simple docstring''' _a : Any =TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Optional[int] ) -> Tuple: '''simple docstring''' _a , _a : int =self.model_tester.prepare_config_and_inputs_for_common() _a : List[Any] =True _a : Union[str, Any] =getattr(self.model_tester , """decoder_seq_length""" , self.model_tester.seq_length ) _a : List[str] =getattr(self.model_tester , """encoder_seq_length""" , self.model_tester.seq_length ) _a : Optional[int] =getattr(self.model_tester , """key_length""" , SCREAMING_SNAKE_CASE ) _a : Dict =getattr(self.model_tester , """key_length""" , SCREAMING_SNAKE_CASE ) def check_decoder_attentions_output(SCREAMING_SNAKE_CASE :str ): _a : List[str] =len(SCREAMING_SNAKE_CASE ) self.assertEqual(out_len % 2 , 0 ) _a : Union[str, Any] =outputs.decoder_attentions self.assertEqual(len(SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , ) def check_encoder_attentions_output(SCREAMING_SNAKE_CASE :str ): _a : Tuple =[ t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions) ] self.assertEqual(len(SCREAMING_SNAKE_CASE ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , ) for model_class in self.all_model_classes: _a : str =True _a : Tuple =False _a : List[Any] =model_class(SCREAMING_SNAKE_CASE ) _a : Dict =model(self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) _a : Union[str, Any] =len(SCREAMING_SNAKE_CASE ) self.assertEqual(config.output_hidden_states , SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(SCREAMING_SNAKE_CASE ) if self.is_encoder_decoder: _a : Optional[Any] =model_class(SCREAMING_SNAKE_CASE ) _a : str =model(self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , SCREAMING_SNAKE_CASE ) check_decoder_attentions_output(SCREAMING_SNAKE_CASE ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] _a : Union[str, Any] =True _a : Optional[int] =model_class(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(config.output_hidden_states , SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(SCREAMING_SNAKE_CASE ) # Check attention is always last and order is fine _a : Dict =True _a : Optional[Any] =True _a : List[Any] =model_class(SCREAMING_SNAKE_CASE ) _a : Optional[Any] =model(self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(SCREAMING_SNAKE_CASE ) ) self.assertEqual(model.config.output_hidden_states , SCREAMING_SNAKE_CASE ) check_encoder_attentions_output(SCREAMING_SNAKE_CASE ) @require_tf class A__ ( unittest.TestCase ): @slow def __UpperCAmelCase ( self :Tuple ) -> List[Any]: '''simple docstring''' _a : int =TFConvBertModel.from_pretrained("""YituTech/conv-bert-base""" ) _a : Tuple =tf.constant([[0, 1, 2, 3, 4, 5]] ) _a : Dict =model(SCREAMING_SNAKE_CASE )[0] _a : List[str] =[1, 6, 7_6_8] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE ) _a : Tuple =tf.constant( [ [ [-0.03_475_493, -0.4_686_034, -0.30_638_832], [0.22_637_248, -0.26_988_646, -0.7_423_424], [0.10_324_868, -0.45_013_508, -0.58_280_784], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE , atol=1e-4 )
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 from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) A__: List[str] = { '''configuration_layoutlmv3''': [ '''LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LayoutLMv3Config''', '''LayoutLMv3OnnxConfig''', ], '''processing_layoutlmv3''': ['''LayoutLMv3Processor'''], '''tokenization_layoutlmv3''': ['''LayoutLMv3Tokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Dict = ['''LayoutLMv3TokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Union[str, Any] = [ '''LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LayoutLMv3ForQuestionAnswering''', '''LayoutLMv3ForSequenceClassification''', '''LayoutLMv3ForTokenClassification''', '''LayoutLMv3Model''', '''LayoutLMv3PreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: Optional[int] = [ '''TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLayoutLMv3ForQuestionAnswering''', '''TFLayoutLMv3ForSequenceClassification''', '''TFLayoutLMv3ForTokenClassification''', '''TFLayoutLMv3Model''', '''TFLayoutLMv3PreTrainedModel''', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__: str = ['''LayoutLMv3FeatureExtractor'''] A__: Optional[Any] = ['''LayoutLMv3ImageProcessor'''] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys A__: Union[str, 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''' 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
'''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''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__: Union[str, Any] = logging.get_logger(__name__) A__: Optional[int] = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[Any] = "pegasus" __UpperCamelCase : List[str] = ["past_key_values"] __UpperCamelCase : List[Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self :List[Any] , SCREAMING_SNAKE_CASE :str=5_0_2_6_5 , SCREAMING_SNAKE_CASE :List[str]=1_0_2_4 , SCREAMING_SNAKE_CASE :Tuple=1_2 , SCREAMING_SNAKE_CASE :Optional[int]=4_0_9_6 , SCREAMING_SNAKE_CASE :Union[str, Any]=1_6 , SCREAMING_SNAKE_CASE :Tuple=1_2 , SCREAMING_SNAKE_CASE :Any=4_0_9_6 , SCREAMING_SNAKE_CASE :int=1_6 , SCREAMING_SNAKE_CASE :List[str]=0.0 , SCREAMING_SNAKE_CASE :Dict=0.0 , SCREAMING_SNAKE_CASE :Optional[int]=True , SCREAMING_SNAKE_CASE :Any=True , SCREAMING_SNAKE_CASE :Union[str, Any]="gelu" , SCREAMING_SNAKE_CASE :Dict=1_0_2_4 , SCREAMING_SNAKE_CASE :str=0.1 , SCREAMING_SNAKE_CASE :str=0.0 , SCREAMING_SNAKE_CASE :Any=0.0 , SCREAMING_SNAKE_CASE :Dict=0.02 , SCREAMING_SNAKE_CASE :Optional[Any]=0 , SCREAMING_SNAKE_CASE :Tuple=False , SCREAMING_SNAKE_CASE :Optional[Any]=0 , SCREAMING_SNAKE_CASE :Optional[int]=1 , SCREAMING_SNAKE_CASE :List[Any]=1 , **SCREAMING_SNAKE_CASE :str , ) -> List[str]: '''simple docstring''' _a : List[Any] =vocab_size _a : List[Any] =max_position_embeddings _a : int =d_model _a : Any =encoder_ffn_dim _a : int =encoder_layers _a : Dict =encoder_attention_heads _a : int =decoder_ffn_dim _a : Union[str, Any] =decoder_layers _a : List[str] =decoder_attention_heads _a : Any =dropout _a : Optional[int] =attention_dropout _a : Optional[Any] =activation_dropout _a : List[str] =activation_function _a : List[Any] =init_std _a : Dict =encoder_layerdrop _a : Any =decoder_layerdrop _a : Optional[int] =use_cache _a : List[Any] =encoder_layers _a : List[Any] =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , is_encoder_decoder=SCREAMING_SNAKE_CASE , decoder_start_token_id=SCREAMING_SNAKE_CASE , forced_eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @property def __UpperCAmelCase ( self :List[str] ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def __UpperCAmelCase ( self :Dict ) -> int: '''simple docstring''' return self.d_model
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''' import logging from transformers.configuration_utils import PretrainedConfig A__: Dict = logging.getLogger(__name__) class A__ ( UpperCAmelCase__ ): __UpperCamelCase : List[str] = "masked_bert" def __init__( self :Dict , SCREAMING_SNAKE_CASE :Optional[int]=3_0_5_2_2 , SCREAMING_SNAKE_CASE :Tuple=7_6_8 , SCREAMING_SNAKE_CASE :Dict=1_2 , SCREAMING_SNAKE_CASE :Any=1_2 , SCREAMING_SNAKE_CASE :List[str]=3_0_7_2 , SCREAMING_SNAKE_CASE :Optional[int]="gelu" , SCREAMING_SNAKE_CASE :int=0.1 , SCREAMING_SNAKE_CASE :Union[str, Any]=0.1 , SCREAMING_SNAKE_CASE :int=5_1_2 , SCREAMING_SNAKE_CASE :Optional[Any]=2 , SCREAMING_SNAKE_CASE :Tuple=0.02 , SCREAMING_SNAKE_CASE :str=1e-12 , SCREAMING_SNAKE_CASE :Dict=0 , SCREAMING_SNAKE_CASE :str="topK" , SCREAMING_SNAKE_CASE :List[str]="constant" , SCREAMING_SNAKE_CASE :Union[str, Any]=0.0 , **SCREAMING_SNAKE_CASE :List[Any] , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) _a : str =vocab_size _a : Tuple =hidden_size _a : Tuple =num_hidden_layers _a : int =num_attention_heads _a : Tuple =hidden_act _a : Optional[Any] =intermediate_size _a : List[str] =hidden_dropout_prob _a : List[str] =attention_probs_dropout_prob _a : Dict =max_position_embeddings _a : Optional[Any] =type_vocab_size _a : List[Any] =initializer_range _a : str =layer_norm_eps _a : List[Any] =pruning_method _a : Dict =mask_init _a : Union[str, Any] =mask_scale
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 import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf 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 ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A__ : def __init__( self :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :int=1_3 , SCREAMING_SNAKE_CASE :Union[str, Any]=7 , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :List[str]=True , SCREAMING_SNAKE_CASE :Tuple=True , SCREAMING_SNAKE_CASE :Optional[Any]=9_9 , SCREAMING_SNAKE_CASE :str=[1, 1, 2] , SCREAMING_SNAKE_CASE :List[Any]=1 , SCREAMING_SNAKE_CASE :Optional[int]=3_2 , SCREAMING_SNAKE_CASE :int=4 , SCREAMING_SNAKE_CASE :str=8 , SCREAMING_SNAKE_CASE :str=3_7 , SCREAMING_SNAKE_CASE :Any="gelu_new" , SCREAMING_SNAKE_CASE :Optional[Any]=0.1 , SCREAMING_SNAKE_CASE :Any=0.1 , SCREAMING_SNAKE_CASE :Dict=0.0 , SCREAMING_SNAKE_CASE :Optional[Any]=5_1_2 , SCREAMING_SNAKE_CASE :Union[str, Any]=3 , SCREAMING_SNAKE_CASE :List[str]=0.02 , SCREAMING_SNAKE_CASE :Tuple=3 , SCREAMING_SNAKE_CASE :List[Any]=4 , SCREAMING_SNAKE_CASE :str=None , SCREAMING_SNAKE_CASE :Optional[Any]=False , ) -> str: '''simple docstring''' _a : int =parent _a : List[Any] =batch_size _a : str =seq_length _a : Union[str, Any] =is_training _a : Union[str, Any] =use_input_mask _a : Tuple =use_token_type_ids _a : Union[str, Any] =use_labels _a : str =vocab_size _a : int =block_sizes _a : Dict =num_decoder_layers _a : List[str] =d_model _a : str =n_head _a : List[str] =d_head _a : Tuple =d_inner _a : Tuple =hidden_act _a : Optional[Any] =hidden_dropout _a : int =attention_dropout _a : Any =activation_dropout _a : Any =max_position_embeddings _a : Union[str, Any] =type_vocab_size _a : Tuple =2 _a : Optional[Any] =num_labels _a : List[str] =num_choices _a : List[str] =scope _a : Tuple =initializer_std # Used in the tests to check the size of the first attention layer _a : str =n_head # Used in the tests to check the size of the first hidden state _a : List[str] =self.d_model # Used in the tests to check the number of output hidden states/attentions _a : Dict =sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: _a : Tuple =self.num_hidden_layers + 2 def __UpperCAmelCase ( self :Tuple ) -> Any: '''simple docstring''' _a : str =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : List[Any] =None if self.use_input_mask: _a : Optional[int] =random_attention_mask([self.batch_size, self.seq_length] ) _a : Union[str, Any] =None if self.use_token_type_ids: _a : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : str =None _a : Dict =None _a : List[str] =None if self.use_labels: _a : List[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[Any] =ids_tensor([self.batch_size] , self.num_choices ) _a : Dict =FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[Any] , SCREAMING_SNAKE_CASE :int , ) -> Any: '''simple docstring''' _a : str =TFFunnelModel(config=SCREAMING_SNAKE_CASE ) _a : Any ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : List[Any] =model(SCREAMING_SNAKE_CASE ) _a : Optional[int] =[input_ids, input_mask] _a : Dict =model(SCREAMING_SNAKE_CASE ) _a : List[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _a : Dict =False _a : Any =TFFunnelModel(config=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) _a : List[Any] =False _a : Any =TFFunnelModel(config=SCREAMING_SNAKE_CASE ) _a : Optional[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Any , ) -> Any: '''simple docstring''' _a : int =TFFunnelBaseModel(config=SCREAMING_SNAKE_CASE ) _a : Tuple ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : Dict =model(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =[input_ids, input_mask] _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) _a : Optional[int] =False _a : Any =TFFunnelBaseModel(config=SCREAMING_SNAKE_CASE ) _a : List[Any] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) _a : int =False _a : List[str] =TFFunnelBaseModel(config=SCREAMING_SNAKE_CASE ) _a : Dict =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :List[Any] , ) -> str: '''simple docstring''' _a : Any =TFFunnelForPreTraining(config=SCREAMING_SNAKE_CASE ) _a : Optional[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : List[str] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Optional[int] , ) -> Optional[int]: '''simple docstring''' _a : Optional[Any] =TFFunnelForMaskedLM(config=SCREAMING_SNAKE_CASE ) _a : 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 :Dict , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[Any] , ) -> List[Any]: '''simple docstring''' _a : Any =self.num_labels _a : int =TFFunnelForSequenceClassification(config=SCREAMING_SNAKE_CASE ) _a : Optional[int] ={"""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.num_labels) ) def __UpperCAmelCase ( self :List[Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :Optional[Any] , ) -> Union[str, Any]: '''simple docstring''' _a : Optional[Any] =self.num_choices _a : Optional[Any] =TFFunnelForMultipleChoice(config=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : str =tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE , 1 ) , (1, self.num_choices, 1) ) _a : Optional[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 : Any =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCAmelCase ( self :Tuple , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :List[Any] , SCREAMING_SNAKE_CASE :str , SCREAMING_SNAKE_CASE :Union[str, Any] , SCREAMING_SNAKE_CASE :Tuple , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[Any] , ) -> Dict: '''simple docstring''' _a : Any =self.num_labels _a : str =TFFunnelForTokenClassification(config=SCREAMING_SNAKE_CASE ) _a : List[Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : List[str] =model(SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Any , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :Dict , SCREAMING_SNAKE_CASE :str , ) -> Optional[Any]: '''simple docstring''' _a : Union[str, Any] =TFFunnelForQuestionAnswering(config=SCREAMING_SNAKE_CASE ) _a : Union[str, Any] ={"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _a : str =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 :Any ) -> Any: '''simple docstring''' _a : int =self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Dict =config_and_inputs _a : int ={"""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 : Dict = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) __UpperCamelCase : Dict = ( { "feature-extraction": (TFFunnelBaseModel, TFFunnelModel), "fill-mask": TFFunnelForMaskedLM, "question-answering": TFFunnelForQuestionAnswering, "text-classification": TFFunnelForSequenceClassification, "token-classification": TFFunnelForTokenClassification, "zero-shot": TFFunnelForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : Union[str, Any] = False __UpperCamelCase : str = False def __UpperCAmelCase ( self :Union[str, Any] ) -> Tuple: '''simple docstring''' _a : Tuple =TFFunnelModelTester(self ) _a : List[str] =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :List[str] ) -> Dict: '''simple docstring''' _a : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[str] ) -> Optional[int]: '''simple docstring''' _a : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[Any]: '''simple docstring''' _a : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Dict ) -> int: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> Union[str, Any]: '''simple docstring''' _a : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE ) @require_tf class A__ ( UpperCAmelCase__ , unittest.TestCase ): __UpperCamelCase : Optional[int] = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) __UpperCamelCase : str = False __UpperCamelCase : List[str] = False def __UpperCAmelCase ( self :Optional[int] ) -> Any: '''simple docstring''' _a : Any =TFFunnelModelTester(self , base=SCREAMING_SNAKE_CASE ) _a : int =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :List[Any] ) -> str: '''simple docstring''' self.config_tester.run_common_tests() def __UpperCAmelCase ( self :Optional[Any] ) -> List[Any]: '''simple docstring''' _a : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[int]: '''simple docstring''' _a : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> Optional[Any]: '''simple docstring''' _a : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*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 os import re import shutil import sys import tempfile import unittest import black A__: Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. A__: Union[str, Any] = ''' def __init__(self, config): super().__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config.vocab_size)) # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` self.decoder.bias = self.bias def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = self.decoder(hidden_states) return hidden_states ''' class A__ ( unittest.TestCase ): def __UpperCAmelCase ( self :Optional[Any] ) -> Optional[Any]: '''simple docstring''' _a : str =tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , """models/bert/""" ) ) _a : Optional[Any] =self.transformer_dir shutil.copy( os.path.join(SCREAMING_SNAKE_CASE , """src/transformers/models/bert/modeling_bert.py""" ) , os.path.join(self.transformer_dir , """models/bert/modeling_bert.py""" ) , ) def __UpperCAmelCase ( self :List[str] ) -> List[Any]: '''simple docstring''' _a : Optional[Any] ="""src/transformers""" shutil.rmtree(self.transformer_dir ) def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :Optional[int] , SCREAMING_SNAKE_CASE :List[str] , SCREAMING_SNAKE_CASE :Optional[Any]=None ) -> Tuple: '''simple docstring''' _a : List[Any] =comment + f"\nclass {class_name}(nn.Module):\n" + class_code if overwrite_result is not None: _a : Any =comment + f"\nclass {class_name}(nn.Module):\n" + overwrite_result _a : Optional[Any] =black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) _a : List[Any] =black.format_str(SCREAMING_SNAKE_CASE , mode=SCREAMING_SNAKE_CASE ) _a : Optional[int] =os.path.join(self.transformer_dir , """new_code.py""" ) with open(SCREAMING_SNAKE_CASE , """w""" , newline="""\n""" ) as f: f.write(SCREAMING_SNAKE_CASE ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=SCREAMING_SNAKE_CASE ) with open(SCREAMING_SNAKE_CASE , """r""" ) as f: self.assertTrue(f.read() , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> Optional[Any]: '''simple docstring''' _a : Dict =check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead""" ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :str ) -> str: '''simple docstring''' # Base copy consistency self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead""" , """BertLMPredictionHead""" , SCREAMING_SNAKE_CASE , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , re.sub("""Bert""" , """TestModel""" , SCREAMING_SNAKE_CASE ) , ) # Copy consistency with a really long name _a : int ="""TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f"# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}" , f"{long_class_name}LMPredictionHead" , re.sub("""Bert""" , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel""" , """TestModelLMPredictionHead""" , SCREAMING_SNAKE_CASE , overwrite_result=re.sub("""Bert""" , """TestModel""" , SCREAMING_SNAKE_CASE ) , ) def __UpperCAmelCase ( self :str ) -> List[str]: '''simple docstring''' _a : List[Any] =check_copies.LOCALIZED_READMES["""README_zh-hans.md"""] _a : Tuple =( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),""" """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**""" """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders""" """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang""" """ Luong, Quoc V. Le, Christopher D. Manning.""" ) _a : Union[str, Any] =( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) _a : Optional[int] =( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.""" """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文""" """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and""" """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same""" """ method has been applied to compress GPT2 into""" """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into""" """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),""" """ Multilingual BERT into""" """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German""" """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自""" """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather""" """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,""" """ Christopher D. Manning 发布。\n""" ) _a , _a : Union[str, Any] =check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) self.assertFalse(SCREAMING_SNAKE_CASE ) self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _a , _a : List[str] =check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(SCREAMING_SNAKE_CASE ) _a : Dict =( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the""" """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for""" """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong""" """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.""" ) _a : Tuple =( """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and""" """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) _a : Optional[Any] =( """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the""" """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of""" """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian""" """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n""" ) _a , _a : Union[str, Any] =check_copies.convert_to_localized_md( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , localized_readme["""format_model_list"""] ) # Check if the model link is synchronized. self.assertEqual(SCREAMING_SNAKE_CASE , 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''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> Dict: _a : Dict =tmp_path / """file.csv""" _a : Union[str, Any] =textwrap.dedent( """\ header1,header2 1,2 10,20 """ ) with open(_UpperCAmelCase ,"""w""" ) as f: f.write(_UpperCAmelCase ) return str(_UpperCAmelCase ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Optional[Any] ) -> Tuple: _a : List[Any] =tmp_path / """malformed_file.csv""" _a : Union[str, Any] =textwrap.dedent( """\ header1,header2 1,2 10,20, """ ) with open(_UpperCAmelCase ,"""w""" ) as f: f.write(_UpperCAmelCase ) return str(_UpperCAmelCase ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ) -> Any: _a : int =tmp_path / """csv_with_image.csv""" _a : Tuple =textwrap.dedent( F"\\n image\n {image_file}\n " ) with open(_UpperCAmelCase ,"""w""" ) as f: f.write(_UpperCAmelCase ) return str(_UpperCAmelCase ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> str: _a : int =tmp_path / """csv_with_label.csv""" _a : Union[str, Any] =textwrap.dedent( """\ label good bad good """ ) with open(_UpperCAmelCase ,"""w""" ) as f: f.write(_UpperCAmelCase ) return str(_UpperCAmelCase ) @pytest.fixture def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : str ) -> Tuple: _a : Optional[int] =tmp_path / """csv_with_int_list.csv""" _a : Any =textwrap.dedent( """\ int_list 1 2 3 4 5 6 7 8 9 """ ) with open(_UpperCAmelCase ,"""w""" ) as f: f.write(_UpperCAmelCase ) return str(_UpperCAmelCase ) def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[Any] ) -> Union[str, Any]: _a : Union[str, Any] =Csv() _a : List[str] =csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_UpperCAmelCase ,match="""Error tokenizing data""" ): for _ in generator: pass assert any( record.levelname == """ERROR""" and """Failed to read file""" in record.message and os.path.basename(_UpperCAmelCase ) in record.message for record in caplog.records ) @require_pil def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> Any: with open(_UpperCAmelCase ,encoding="""utf-8""" ) as f: _a : Optional[int] =f.read().splitlines()[1] _a : Dict =Csv(encoding="""utf-8""" ,features=Features({"""image""": Image()} ) ) _a : Any =csv._generate_tables([[csv_file_with_image]] ) _a : List[str] =pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""image""" ).type == Image()() _a : Tuple =pa_table.to_pydict()["""image"""] assert generated_content == [{"path": image_file, "bytes": None}] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : int ) -> str: with open(_UpperCAmelCase ,encoding="""utf-8""" ) as f: _a : str =f.read().splitlines()[1:] _a : Any =Csv(encoding="""utf-8""" ,features=Features({"""label""": ClassLabel(names=["""good""", """bad"""] )} ) ) _a : Dict =csv._generate_tables([[csv_file_with_label]] ) _a : Union[str, Any] =pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field("""label""" ).type == ClassLabel(names=["""good""", """bad"""] )() _a : Any =pa_table.to_pydict()["""label"""] assert generated_content == [ClassLabel(names=["""good""", """bad"""] ).straint(_UpperCAmelCase ) for label in labels] def SCREAMING_SNAKE_CASE_ ( _UpperCAmelCase : List[str] ) -> Tuple: _a : List[str] =Csv(encoding="""utf-8""" ,sep=""",""" ,converters={"""int_list""": lambda _UpperCAmelCase : [int(_UpperCAmelCase ) for i in x.split()]} ) _a : int =csv._generate_tables([[csv_file_with_int_list]] ) _a : int =pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field("""int_list""" ).type ) _a : str =pa_table.to_pydict()["""int_list"""] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
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 Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker A__: Optional[int] = '''CompVis/stable-diffusion-v1-1''' A__: Union[str, Any] = '''CompVis/stable-diffusion-v1-2''' A__: List[Any] = '''CompVis/stable-diffusion-v1-3''' A__: Dict = '''CompVis/stable-diffusion-v1-4''' class A__ ( UpperCAmelCase__ ): def __init__( self :List[str] , SCREAMING_SNAKE_CASE :AutoencoderKL , SCREAMING_SNAKE_CASE :CLIPTextModel , SCREAMING_SNAKE_CASE :CLIPTokenizer , SCREAMING_SNAKE_CASE :UNetaDConditionModel , SCREAMING_SNAKE_CASE :Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , SCREAMING_SNAKE_CASE :StableDiffusionSafetyChecker , SCREAMING_SNAKE_CASE :CLIPImageProcessor , SCREAMING_SNAKE_CASE :bool = True , ) -> int: '''simple docstring''' super()._init_() _a : Union[str, Any] =StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE ) _a : Any =StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE ) _a : List[Any] =StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE ) _a : List[Any] =StableDiffusionPipeline( vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=SCREAMING_SNAKE_CASE , requires_safety_checker=SCREAMING_SNAKE_CASE , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def __UpperCAmelCase ( self :List[Any] ) -> Dict[str, Any]: '''simple docstring''' return {k: getattr(self , SCREAMING_SNAKE_CASE ) for k in self.config.keys() if not k.startswith("""_""" )} def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Optional[Union[str, int]] = "auto" ) -> List[str]: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory _a : Dict =self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE ) def __UpperCAmelCase ( self :Any ) -> List[str]: '''simple docstring''' self.enable_attention_slicing(SCREAMING_SNAKE_CASE ) @torch.no_grad() def __UpperCAmelCase ( self :List[str] , SCREAMING_SNAKE_CASE :Union[str, List[str]] , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :int , ) -> int: '''simple docstring''' return self.pipea( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @torch.no_grad() def __UpperCAmelCase ( self :Union[str, Any] , SCREAMING_SNAKE_CASE :Union[str, List[str]] , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :List[str] , ) -> int: '''simple docstring''' return self.pipea( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @torch.no_grad() def __UpperCAmelCase ( self :str , SCREAMING_SNAKE_CASE :Union[str, List[str]] , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :str , ) -> Union[str, Any]: '''simple docstring''' return self.pipea( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @torch.no_grad() def __UpperCAmelCase ( self :Any , SCREAMING_SNAKE_CASE :Union[str, List[str]] , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :Dict , ) -> Optional[Any]: '''simple docstring''' return self.pipea( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) @torch.no_grad() def __UpperCAmelCase ( self :Optional[Any] , SCREAMING_SNAKE_CASE :Union[str, List[str]] , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_1_2 , SCREAMING_SNAKE_CASE :int = 5_0 , SCREAMING_SNAKE_CASE :float = 7.5 , SCREAMING_SNAKE_CASE :Optional[Union[str, List[str]]] = None , SCREAMING_SNAKE_CASE :Optional[int] = 1 , SCREAMING_SNAKE_CASE :float = 0.0 , SCREAMING_SNAKE_CASE :Optional[torch.Generator] = None , SCREAMING_SNAKE_CASE :Optional[torch.FloatTensor] = None , SCREAMING_SNAKE_CASE :Optional[str] = "pil" , SCREAMING_SNAKE_CASE :bool = True , SCREAMING_SNAKE_CASE :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , SCREAMING_SNAKE_CASE :int = 1 , **SCREAMING_SNAKE_CASE :Optional[int] , ) -> Union[str, Any]: '''simple docstring''' _a : List[Any] ="""cuda""" if torch.cuda.is_available() else """cpu""" self.to(SCREAMING_SNAKE_CASE ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 _a : Optional[Any] =self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.2 _a : Dict =self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.3 _a : Dict =self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) # Get first result from Stable Diffusion Checkpoint v1.4 _a : Dict =self.textaimg_sda_a( prompt=SCREAMING_SNAKE_CASE , height=SCREAMING_SNAKE_CASE , width=SCREAMING_SNAKE_CASE , num_inference_steps=SCREAMING_SNAKE_CASE , guidance_scale=SCREAMING_SNAKE_CASE , negative_prompt=SCREAMING_SNAKE_CASE , num_images_per_prompt=SCREAMING_SNAKE_CASE , eta=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , latents=SCREAMING_SNAKE_CASE , output_type=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , callback=SCREAMING_SNAKE_CASE , callback_steps=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
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
from datetime import datetime as dt import os from github import Github UpperCAmelCase__ = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def _a ( ) -> Tuple: a = Github(os.environ['''GITHUB_TOKEN'''] ) a = g.get_repo('''huggingface/transformers''' ) a = repo.get_issues(state='''open''' ) for issue in open_issues: a = sorted([comment for comment in issue.get_comments()] , key=lambda a : i.created_at , reverse=a ) a = comments[0] if len(a ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='''closed''' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
0
'''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
0
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class __A : def __init__(self : Any , __a : str , __a : List[str]=13 , __a : Optional[int]=30 , __a : Tuple=2 , __a : str=3 , __a : Tuple=True , __a : List[Any]=True , __a : Optional[int]=32 , __a : Optional[int]=2 , __a : int=4 , __a : Optional[Any]=37 , __a : Optional[Any]="gelu" , __a : Optional[Any]=0.1 , __a : int=0.1 , __a : int=10 , __a : Optional[int]=0.02 , __a : Dict=3 , __a : Optional[int]=None , __a : List[str]=2 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = image_size UpperCAmelCase_ = patch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = is_training UpperCAmelCase_ = use_labels UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = type_sequence_label_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = scope UpperCAmelCase_ = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) UpperCAmelCase_ = (image_size // patch_size) ** 2 UpperCAmelCase_ = num_patches + 2 def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase_ = None if self.use_labels: UpperCAmelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ = self.get_config() return config, pixel_values, labels def _lowercase (self : List[str] ): return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def _lowercase (self : Union[str, Any] , __a : str , __a : Any , __a : Dict ): UpperCAmelCase_ = TFDeiTModel(config=__a ) UpperCAmelCase_ = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase (self : str , __a : Optional[int] , __a : List[str] , __a : Tuple ): UpperCAmelCase_ = TFDeiTForMaskedImageModeling(config=__a ) UpperCAmelCase_ = model(__a ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images UpperCAmelCase_ = 1 UpperCAmelCase_ = TFDeiTForMaskedImageModeling(__a ) UpperCAmelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase_ = model(__a ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def _lowercase (self : List[Any] , __a : List[str] , __a : int , __a : int ): UpperCAmelCase_ = self.type_sequence_label_size UpperCAmelCase_ = TFDeiTForImageClassification(__a ) UpperCAmelCase_ = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images UpperCAmelCase_ = 1 UpperCAmelCase_ = TFDeiTForImageClassification(__a ) UpperCAmelCase_ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) UpperCAmelCase_ = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowercase (self : Dict ): UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = config_and_inputs UpperCAmelCase_ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : Tuple = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) a__ : Union[str, Any] = ( { """feature-extraction""": TFDeiTModel, """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) a__ : Tuple = False a__ : List[Any] = False a__ : Any = False a__ : Dict = False def _lowercase (self : List[Any] ): UpperCAmelCase_ = TFDeiTModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def _lowercase (self : Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="DeiT does not use inputs_embeds" ) def _lowercase (self : List[str] ): pass def _lowercase (self : List[Any] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) UpperCAmelCase_ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__a , tf.keras.layers.Dense ) ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) UpperCAmelCase_ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def _lowercase (self : Dict ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def _lowercase (self : Any ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__a ) def _lowercase (self : Any ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) def _lowercase (self : Optional[Any] , __a : Tuple , __a : Tuple , __a : Union[str, Any]=False ): UpperCAmelCase_ = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def _lowercase (self : int ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ = TFDeiTModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class __A ( unittest.TestCase ): @cached_property def _lowercase (self : Union[str, Any] ): return ( DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" ) if is_vision_available() else None ) @slow def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(images=__a , return_tensors="tf" ) # forward pass UpperCAmelCase_ = model(**__a ) # verify the logits UpperCAmelCase_ = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) UpperCAmelCase_ = tf.constant([-1.02_66, 0.19_12, -1.28_61] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) )
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
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase : int = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''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
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, 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 ( __snake_case , unittest.TestCase ): __magic_name__ = KandinskyVaaControlnetImgaImgPipeline __magic_name__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] __magic_name__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''hint'''] __magic_name__ = [ '''generator''', '''height''', '''width''', '''strength''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] __magic_name__ = False @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self ) -> int: """simple docstring""" return 32 @property def __lowerCAmelCase ( self ) -> str: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self ) -> Any: """simple docstring""" return 100 @property def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) A : List[Any] = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } A : List[str] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE ) return model @property def __lowerCAmelCase ( self ) -> Any: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) A : int = VQModel(**self.dummy_movq_kwargs ) return model def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : List[str] = self.dummy_unet A : Tuple = self.dummy_movq A : List[str] = { '''num_train_timesteps''': 1000, '''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 : str = DDIMScheduler(**SCREAMING_SNAKE_CASE ) A : Tuple = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=0 ) -> List[Any]: """simple docstring""" A : int = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) A : 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, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) A : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0] A : Tuple = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE ) ).convert('''RGB''' ).resize((256, 256) ) # create hint A : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE ) ).to(SCREAMING_SNAKE_CASE ) if str(SCREAMING_SNAKE_CASE ).startswith('''mps''' ): A : str = torch.manual_seed(SCREAMING_SNAKE_CASE ) else: A : List[str] = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(SCREAMING_SNAKE_CASE ) A : Optional[int] = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 10, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Optional[Any] = '''cpu''' A : Dict = self.get_dummy_components() A : Optional[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE ) A : Dict = pipe.to(SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) A : Optional[int] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) ) A : Union[str, Any] = output.images A : str = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE ) , return_dict=SCREAMING_SNAKE_CASE , )[0] A : Optional[Any] = image[0, -3:, -3:, -1] A : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A : List[Any] = np.array( [0.54_985_034, 0.55_509_365, 0.52_561_504, 0.5_570_494, 0.5_593_818, 0.5_263_979, 0.50_285_643, 0.5_069_846, 0.51_196_736] ) 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 __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self ) -> str: """simple docstring""" A : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) A : int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) A : List[Any] = init_image.resize((512, 512) ) A : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) A : List[Any] = torch.from_numpy(np.array(SCREAMING_SNAKE_CASE ) ).float() / 255.0 A : Optional[int] = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) A : int = '''A robot, 4k photo''' A : str = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE ) A : Optional[int] = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) A : List[Any] = 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 : Optional[Any] = pipe_prior( SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , strength=0.85 , generator=SCREAMING_SNAKE_CASE , negative_prompt='''''' , ).to_tuple() A : str = pipeline( image=SCREAMING_SNAKE_CASE , image_embeds=SCREAMING_SNAKE_CASE , negative_image_embeds=SCREAMING_SNAKE_CASE , hint=SCREAMING_SNAKE_CASE , generator=SCREAMING_SNAKE_CASE , num_inference_steps=100 , height=512 , width=512 , strength=0.5 , output_type='''np''' , ) A : str = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
3
'''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
0
'''simple docstring''' import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( """The `inpainting.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionInpaintPipeline` instead.""" )
4
'''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
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase__ = ''' Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)["depth"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline("depth-estimation") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to("cuda") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to("cuda") >>> img = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/cat.png" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda") >>> prompt = "A robot, 4k photo" >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature" >>> generator = torch.Generator(device="cuda").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save("robot_cat.png") ``` ''' def UpperCAmelCase_ ( __snake_case , __snake_case , __snake_case=8 ) -> Union[str, Any]: """simple docstring""" _lowercase =height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _lowercase =width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCamelCase__ ( lowerCAmelCase): def __init__(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , ) -> Tuple: super().__init__() self.register_modules( unet=UpperCAmelCase , scheduler=UpperCAmelCase , movq=UpperCAmelCase , ) _lowercase =2 ** (len(self.movq.config.block_out_channels ) - 1) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: if latents is None: _lowercase =randn_tensor(UpperCAmelCase , generator=UpperCAmelCase , device=UpperCAmelCase , dtype=UpperCAmelCase ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) _lowercase =latents.to(UpperCAmelCase ) _lowercase =latents * scheduler.init_noise_sigma return latents def __A (self , UpperCAmelCase=0 ) -> Tuple: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) _lowercase =torch.device(f"cuda:{gpu_id}" ) _lowercase =[ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase , UpperCAmelCase ) def __A (self , UpperCAmelCase=0 ) -> str: if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) _lowercase =torch.device(f"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=UpperCAmelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _lowercase =None for cpu_offloaded_model in [self.unet, self.movq]: _lowercase , _lowercase =cpu_offload_with_hook(UpperCAmelCase , UpperCAmelCase , prev_module_hook=UpperCAmelCase ) # We'll offload the last model manually. _lowercase =hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __A (self ) -> Union[str, Any]: if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase ) def __call__(self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 5_1_2 , UpperCAmelCase = 5_1_2 , UpperCAmelCase = 1_0_0 , UpperCAmelCase = 4.0 , UpperCAmelCase = 1 , UpperCAmelCase = None , UpperCAmelCase = None , UpperCAmelCase = "pil" , UpperCAmelCase = True , ) -> Any: _lowercase =self._execution_device _lowercase =guidance_scale > 1.0 if isinstance(UpperCAmelCase , UpperCAmelCase ): _lowercase =torch.cat(UpperCAmelCase , dim=0 ) if isinstance(UpperCAmelCase , UpperCAmelCase ): _lowercase =torch.cat(UpperCAmelCase , dim=0 ) if isinstance(UpperCAmelCase , UpperCAmelCase ): _lowercase =torch.cat(UpperCAmelCase , dim=0 ) _lowercase =image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: _lowercase =image_embeds.repeat_interleave(UpperCAmelCase , dim=0 ) _lowercase =negative_image_embeds.repeat_interleave(UpperCAmelCase , dim=0 ) _lowercase =hint.repeat_interleave(UpperCAmelCase , dim=0 ) _lowercase =torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase ) _lowercase =torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase ) self.scheduler.set_timesteps(UpperCAmelCase , device=UpperCAmelCase ) _lowercase =self.scheduler.timesteps _lowercase =self.movq.config.latent_channels _lowercase , _lowercase =downscale_height_and_width(UpperCAmelCase , UpperCAmelCase , self.movq_scale_factor ) # create initial latent _lowercase =self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase ) ): # expand the latents if we are doing classifier free guidance _lowercase =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _lowercase ={'''image_embeds''': image_embeds, '''hint''': hint} _lowercase =self.unet( sample=UpperCAmelCase , timestep=UpperCAmelCase , encoder_hidden_states=UpperCAmelCase , added_cond_kwargs=UpperCAmelCase , return_dict=UpperCAmelCase , )[0] if do_classifier_free_guidance: _lowercase , _lowercase =noise_pred.split(latents.shape[1] , dim=1 ) _lowercase , _lowercase =noise_pred.chunk(2 ) _lowercase , _lowercase =variance_pred.chunk(2 ) _lowercase =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _lowercase =torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _lowercase , _lowercase =noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _lowercase =self.scheduler.step( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , generator=UpperCAmelCase , )[0] # post-processing _lowercase =self.movq.decode(UpperCAmelCase , force_not_quantize=UpperCAmelCase )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: _lowercase =image * 0.5 + 0.5 _lowercase =image.clamp(0 , 1 ) _lowercase =image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _lowercase =self.numpy_to_pil(UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase )
5
'''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
0
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers A : int = '3' print('Python version:', sys.version) print('transformers version:', transformers.__version__) try: import torch print('Torch version:', torch.__version__) print('Cuda available:', torch.cuda.is_available()) print('Cuda version:', torch.version.cuda) print('CuDNN version:', torch.backends.cudnn.version()) print('Number of GPUs available:', torch.cuda.device_count()) print('NCCL version:', torch.cuda.nccl.version()) except ImportError: print('Torch version:', None) try: import deepspeed print('DeepSpeed version:', deepspeed.__version__) except ImportError: print('DeepSpeed version:', None) try: import tensorflow as tf print('TensorFlow version:', tf.__version__) print('TF GPUs available:', bool(tf.config.list_physical_devices('GPU'))) print('Number of TF GPUs available:', len(tf.config.list_physical_devices('GPU'))) except ImportError: print('TensorFlow version:', None)
6
'''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
0
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def _snake_case( SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return EnvironmentCommand() class A ( _UpperCAmelCase ): """simple docstring""" @staticmethod def snake_case__ ( lowercase_ : ArgumentParser )-> Dict: '''simple docstring''' A__ = parser.add_parser('env' ) download_parser.set_defaults(func=lowercase_ ) def snake_case__ ( self : List[Any] )-> List[str]: '''simple docstring''' A__ = huggingface_hub.__version__ A__ = 'not installed' A__ = 'NA' if is_torch_available(): import torch A__ = torch.__version__ A__ = torch.cuda.is_available() A__ = 'not installed' if is_transformers_available(): import transformers A__ = transformers.__version__ A__ = 'not installed' if is_accelerate_available(): import accelerate A__ = accelerate.__version__ A__ = 'not installed' if is_xformers_available(): import xformers A__ = xformers.__version__ A__ = { '`diffusers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'PyTorch version (GPU?)': F'{pt_version} ({pt_cuda_available})', 'Huggingface_hub version': hub_version, 'Transformers version': transformers_version, 'Accelerate version': accelerate_version, 'xFormers version': xformers_version, 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' ) print(self.format_dict(lowercase_ ) ) return info @staticmethod def snake_case__ ( lowercase_ : int )-> Optional[Any]: '''simple docstring''' return "\n".join([F'- {prop}: {val}' for prop, val in d.items()] ) + "\n"
7
'''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
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = "biogpt" def __init__( self : Any , _UpperCamelCase : Dict=4_2_3_8_4 , _UpperCamelCase : Dict=1_0_2_4 , _UpperCamelCase : Optional[Any]=2_4 , _UpperCamelCase : Union[str, Any]=1_6 , _UpperCamelCase : Union[str, Any]=4_0_9_6 , _UpperCamelCase : Union[str, Any]="gelu" , _UpperCamelCase : Tuple=0.1 , _UpperCamelCase : int=0.1 , _UpperCamelCase : Union[str, Any]=1_0_2_4 , _UpperCamelCase : Optional[int]=0.02 , _UpperCamelCase : str=1e-12 , _UpperCamelCase : List[str]=True , _UpperCamelCase : str=True , _UpperCamelCase : List[str]=0.0 , _UpperCamelCase : Optional[Any]=0.0 , _UpperCamelCase : int=1 , _UpperCamelCase : List[Any]=0 , _UpperCamelCase : Any=2 , **_UpperCamelCase : List[str] , ) ->List[Any]: snake_case_ = vocab_size snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = scale_embedding snake_case_ = use_cache snake_case_ = layerdrop snake_case_ = activation_dropout super().__init__(pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase )
8
'''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
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : Optional[Any] ='▁' __lowerCAmelCase : Union[str, Any] ={'vocab_file': 'spiece.model'} __lowerCAmelCase : Optional[int] ={ 'vocab_file': {'google/pegasus-xsum': 'https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'} } __lowerCAmelCase : Optional[int] ={ 'google/pegasus-xsum': 5_1_2, } __lowerCAmelCase : Union[str, Any] =logging.get_logger(__name__) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : List[str] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : Any = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Tuple = ['''input_ids''', '''attention_mask'''] def __init__( self :str , lowerCAmelCase__ :Tuple , lowerCAmelCase__ :Dict="<pad>" , lowerCAmelCase__ :List[Any]="</s>" , lowerCAmelCase__ :Tuple="<unk>" , lowerCAmelCase__ :str="<mask_2>" , lowerCAmelCase__ :Dict="<mask_1>" , lowerCAmelCase__ :Union[str, Any]=None , lowerCAmelCase__ :Union[str, Any]=103 , lowerCAmelCase__ :Optional[Dict[str, Any]] = None , **lowerCAmelCase__ :str , ) -> None: __SCREAMING_SNAKE_CASE : int = offset if additional_special_tokens is not None: if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise TypeError( f'''additional_special_tokens should be of type {type(lowerCAmelCase__ )}, but is''' f''' {type(lowerCAmelCase__ )}''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(lowerCAmelCase__ ) , self.offset - 1 ) ] if len(set(lowerCAmelCase__ ) ) != len(lowerCAmelCase__ ): raise ValueError( '''Please make sure that the provided additional_special_tokens do not contain an incorrectly''' f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) __SCREAMING_SNAKE_CASE : List[str] = additional_special_tokens_extended else: __SCREAMING_SNAKE_CASE : List[Any] = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] __SCREAMING_SNAKE_CASE : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , mask_token_sent=lowerCAmelCase__ , offset=lowerCAmelCase__ , additional_special_tokens=lowerCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , **lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE : Dict = mask_token_sent __SCREAMING_SNAKE_CASE : Any = vocab_file __SCREAMING_SNAKE_CASE : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase__ ) # add special tokens to encoder dict __SCREAMING_SNAKE_CASE : Dict[int, str] = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) __SCREAMING_SNAKE_CASE : Dict[str, int] = {v: k for k, v in self.encoder.items()} @property def __magic_name__( self :Dict ) -> int: return len(self.sp_model ) + self.offset def __magic_name__( self :Dict ) -> Dict[str, int]: __SCREAMING_SNAKE_CASE : List[str] = {self.convert_ids_to_tokens(lowerCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self :List[str] ) -> Dict: __SCREAMING_SNAKE_CASE : str = self.__dict__.copy() __SCREAMING_SNAKE_CASE : Optional[Any] = None return state def __setstate__( self :Any , lowerCAmelCase__ :Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE : Union[str, Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Any = {} __SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :str ) -> List[str]: return self.sp_model.encode(lowerCAmelCase__ , out_type=lowerCAmelCase__ ) def __magic_name__( self :List[Any] , lowerCAmelCase__ :str ) -> int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] __SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.piece_to_id(lowerCAmelCase__ ) return sp_id + self.offset def __magic_name__( self :List[Any] , lowerCAmelCase__ :int ) -> str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: __SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.IdToPiece(index - self.offset ) return token def __magic_name__( self :Tuple , lowerCAmelCase__ :Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE : Dict = [] __SCREAMING_SNAKE_CASE : Tuple = '''''' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase__ ) + token __SCREAMING_SNAKE_CASE : int = [] else: current_sub_tokens.append(lowerCAmelCase__ ) out_string += self.sp_model.decode(lowerCAmelCase__ ) return out_string.strip() def __magic_name__( self :Any , lowerCAmelCase__ :Optional[Any]=False ) -> Dict: return 1 def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :int ) -> str: __SCREAMING_SNAKE_CASE : List[Any] = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def __magic_name__( self :int , lowerCAmelCase__ :List , lowerCAmelCase__ :Optional[List] = None , lowerCAmelCase__ :bool = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(lowerCAmelCase__ ) elif token_ids_a is None: return self._special_token_mask(lowerCAmelCase__ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def __magic_name__( self :List[str] , lowerCAmelCase__ :List[Any] , lowerCAmelCase__ :List[Any]=None ) -> List[int]: if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __magic_name__( self :int , lowerCAmelCase__ :str , lowerCAmelCase__ :Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : Optional[int] = os.path.join( lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowerCAmelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase__ , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase__ ) return (out_vocab_file,)
9
'''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
0
def lowerCAmelCase_ ( __a , __a ) -> Dict: """simple docstring""" lowerCamelCase__: Any =[0 for i in range(r + 1 )] # nc0 = 1 lowerCamelCase__: List[str] =1 for i in range(1 , n + 1 ): # to compute current row from previous row. lowerCamelCase__: List[str] =min(__a , __a ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
10
'''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
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'microsoft/beit-base-patch16-224-pt22k': ( 'https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json' ), # See all BEiT models at https://huggingface.co/models?filter=beit } class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = "beit" def __init__( self , __lowerCamelCase=8_1_9_2 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.0_2 , __lowerCamelCase=1e-12 , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=0.1 , __lowerCamelCase=0.1 , __lowerCamelCase=True , __lowerCamelCase=[3, 5, 7, 1_1] , __lowerCamelCase=[1, 2, 3, 6] , __lowerCamelCase=True , __lowerCamelCase=0.4 , __lowerCamelCase=2_5_6 , __lowerCamelCase=1 , __lowerCamelCase=False , __lowerCamelCase=2_5_5 , **__lowerCamelCase , ) -> str: super().__init__(**__lowerCamelCase) _A : Union[str, Any] = vocab_size _A : Union[str, Any] = hidden_size _A : Optional[Any] = num_hidden_layers _A : str = num_attention_heads _A : List[str] = intermediate_size _A : Any = hidden_act _A : Tuple = hidden_dropout_prob _A : Dict = attention_probs_dropout_prob _A : int = initializer_range _A : Any = layer_norm_eps _A : Optional[int] = image_size _A : Optional[int] = patch_size _A : Optional[Any] = num_channels _A : str = use_mask_token _A : int = use_absolute_position_embeddings _A : List[Any] = use_relative_position_bias _A : List[Any] = use_shared_relative_position_bias _A : Optional[Any] = layer_scale_init_value _A : Dict = drop_path_rate _A : Union[str, Any] = use_mean_pooling # decode head attributes (semantic segmentation) _A : Dict = out_indices _A : Dict = pool_scales # auxiliary head attributes (semantic segmentation) _A : List[Any] = use_auxiliary_head _A : Dict = auxiliary_loss_weight _A : str = auxiliary_channels _A : str = auxiliary_num_convs _A : Optional[Any] = auxiliary_concat_input _A : int = semantic_loss_ignore_index class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = version.parse("1.11") @property def _lowerCamelCase ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def _lowerCamelCase ( self) -> float: return 1e-4
11
'''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
0
import argparse import torch from transformers import RemBertConfig, RemBertModel, load_tf_weights_in_rembert from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase__ ( A__ : str , A__ : List[str] , A__ : Tuple ): '''simple docstring''' __lowerCamelCase = RemBertConfig.from_json_file(A__ ) print("""Building PyTorch model from configuration: {}""".format(str(A__ ) ) ) __lowerCamelCase = RemBertModel(A__ ) # Load weights from tf checkpoint load_tf_weights_in_rembert(A__ , A__ , A__ ) # Save pytorch-model print("""Save PyTorch model to {}""".format(A__ ) ) torch.save(model.state_dict() , A__ ) if __name__ == "__main__": UpperCAmelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--rembert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained RemBERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) UpperCAmelCase_ = parser.parse_args() convert_rembert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.rembert_config_file, args.pytorch_dump_path)
12
'''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
0
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 lowerCAmelCase : Any = random.Random() def A_ ( _UpperCAmelCase , _UpperCAmelCase=1.0 , _UpperCAmelCase=None , _UpperCAmelCase=None ): if rng is None: SCREAMING_SNAKE_CASE_: Tuple = global_rng SCREAMING_SNAKE_CASE_: Dict = [] 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 __lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[Any]=7 , lowerCAmelCase__ : Tuple=400 , lowerCAmelCase__ : int=2000 , lowerCAmelCase__ : int=10 , lowerCAmelCase__ : Any=160 , lowerCAmelCase__ : Optional[Any]=8 , lowerCAmelCase__ : Any=0.0 , lowerCAmelCase__ : int=4000 , lowerCAmelCase__ : str=False , lowerCAmelCase__ : Union[str, Any]=True , ): SCREAMING_SNAKE_CASE_: str = parent SCREAMING_SNAKE_CASE_: Union[str, Any] = batch_size SCREAMING_SNAKE_CASE_: Optional[Any] = min_seq_length SCREAMING_SNAKE_CASE_: str = max_seq_length SCREAMING_SNAKE_CASE_: int = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE_: Union[str, Any] = padding_value SCREAMING_SNAKE_CASE_: Union[str, Any] = sampling_rate SCREAMING_SNAKE_CASE_: List[str] = return_attention_mask SCREAMING_SNAKE_CASE_: Optional[int] = do_normalize SCREAMING_SNAKE_CASE_: int = feature_size SCREAMING_SNAKE_CASE_: Union[str, Any] = chunk_length SCREAMING_SNAKE_CASE_: Optional[Any] = hop_length def _SCREAMING_SNAKE_CASE ( self : List[str]): 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 _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase__ : Optional[int]=False , lowerCAmelCase__ : Dict=False): def _flatten(lowerCAmelCase__ : int): return list(itertools.chain(*lowerCAmelCase__)) if equal_length: SCREAMING_SNAKE_CASE_: List[Any] = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE_: List[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: SCREAMING_SNAKE_CASE_: Tuple = [np.asarray(lowerCAmelCase__) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __lowercase ( UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" _UpperCAmelCase : int = WhisperFeatureExtractor if is_speech_available() else None def _SCREAMING_SNAKE_CASE ( self : Any): SCREAMING_SNAKE_CASE_: Optional[int] = WhisperFeatureExtractionTester(self) def _SCREAMING_SNAKE_CASE ( self : List[Any]): SCREAMING_SNAKE_CASE_: Optional[int] = self.feature_extraction_class(**self.feat_extract_dict) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_: str = feat_extract_first.save_pretrained(lowerCAmelCase__)[0] check_json_file_has_correct_format(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Tuple = self.feature_extraction_class.from_pretrained(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE_: List[Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE_: Dict = feat_extract_first.mel_filters SCREAMING_SNAKE_CASE_: Any = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__)) self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): SCREAMING_SNAKE_CASE_: Any = self.feature_extraction_class(**self.feat_extract_dict) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE_: Optional[Any] = os.path.join(lowerCAmelCase__ , "feat_extract.json") feat_extract_first.to_json_file(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Optional[int] = self.feature_extraction_class.from_json_file(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: Dict = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE_: Dict = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE_: Any = feat_extract_first.mel_filters SCREAMING_SNAKE_CASE_: Union[str, Any] = feat_extract_second.mel_filters self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__)) self.assertEqual(lowerCAmelCase__ , lowerCAmelCase__) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE_: List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE_: Union[str, Any] = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] SCREAMING_SNAKE_CASE_: Dict = [np.asarray(lowerCAmelCase__) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE_: List[str] = feature_extractor(lowerCAmelCase__ , 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 SCREAMING_SNAKE_CASE_: Optional[Any] = feature_extractor(speech_inputs[0] , return_tensors="np").input_features SCREAMING_SNAKE_CASE_: Dict = feature_extractor(np_speech_inputs[0] , return_tensors="np").input_features self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3)) # Test batched SCREAMING_SNAKE_CASE_: int = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features SCREAMING_SNAKE_CASE_: Optional[int] = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__ , lowerCAmelCase__): self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3)) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE_: int = [floats_list((1, x))[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE_: Union[str, Any] = np.asarray(lowerCAmelCase__) SCREAMING_SNAKE_CASE_: str = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features SCREAMING_SNAKE_CASE_: Union[str, Any] = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__ , lowerCAmelCase__): self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3)) # Test truncation required SCREAMING_SNAKE_CASE_: Optional[Any] = [floats_list((1, x))[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200)] SCREAMING_SNAKE_CASE_: List[Any] = [np.asarray(lowerCAmelCase__) for speech_input in speech_inputs] SCREAMING_SNAKE_CASE_: Union[str, Any] = [x[: feature_extractor.n_samples] for x in speech_inputs] SCREAMING_SNAKE_CASE_: Tuple = [np.asarray(lowerCAmelCase__) for speech_input in speech_inputs_truncated] SCREAMING_SNAKE_CASE_: Any = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features SCREAMING_SNAKE_CASE_: Any = feature_extractor(lowerCAmelCase__ , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__ , lowerCAmelCase__): self.assertTrue(np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3)) def _SCREAMING_SNAKE_CASE ( self : str): import torch SCREAMING_SNAKE_CASE_: Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) SCREAMING_SNAKE_CASE_: Union[str, Any] = np.random.rand(100 , 32).astype(np.floataa) SCREAMING_SNAKE_CASE_: Any = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE_: str = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np") self.assertTrue(np_processed.input_features.dtype == np.floataa) SCREAMING_SNAKE_CASE_: List[Any] = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt") self.assertTrue(pt_processed.input_features.dtype == torch.floataa) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase__ : Union[str, Any]): SCREAMING_SNAKE_CASE_: Tuple = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation") # automatic decoding with librispeech SCREAMING_SNAKE_CASE_: Union[str, Any] = ds.sort("id").select(range(lowerCAmelCase__))[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _SCREAMING_SNAKE_CASE ( self : str): # fmt: off SCREAMING_SNAKE_CASE_: str = torch.tensor( [ 0.1193, -0.0946, -0.1098, -0.0196, 0.0225, -0.0690, -0.1736, 0.0951, 0.0971, -0.0817, -0.0702, 0.0162, 0.0260, 0.0017, -0.0192, -0.1678, 0.0709, -0.1867, -0.0655, -0.0274, -0.0234, -0.1884, -0.0516, -0.0554, -0.0274, -0.1425, -0.1423, 0.0837, 0.0377, -0.0854 ]) # fmt: on SCREAMING_SNAKE_CASE_: Union[str, Any] = self._load_datasamples(1) SCREAMING_SNAKE_CASE_: Optional[int] = WhisperFeatureExtractor() SCREAMING_SNAKE_CASE_: str = feature_extractor(lowerCAmelCase__ , return_tensors="pt").input_features self.assertEqual(input_features.shape , (1, 80, 3000)) self.assertTrue(torch.allclose(input_features[0, 0, :30] , lowerCAmelCase__ , atol=1E-4)) def _SCREAMING_SNAKE_CASE ( self : Optional[int]): SCREAMING_SNAKE_CASE_: Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) SCREAMING_SNAKE_CASE_: Dict = self._load_datasamples(1)[0] SCREAMING_SNAKE_CASE_: Union[str, Any] = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue SCREAMING_SNAKE_CASE_: int = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=lowerCAmelCase__)[0] self.assertTrue(np.all(np.mean(lowerCAmelCase__) < 1E-3)) self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase__) - 1) < 1E-3))
13
'''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
0
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : Tuple = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_=False ) -> Union[str, Any]: """simple docstring""" A__ = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('''head''' ): A__ = '''segformer.encoder.''' + key if key.startswith('''backbone''' ): A__ = key.replace('''backbone''' , '''segformer.encoder''' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 A__ = key[key.find('''patch_embed''' ) + len('''patch_embed''' )] A__ = key.replace(f"""patch_embed{idx}""" , f"""patch_embeddings.{int(lowercase_ )-1}""" ) if "norm" in key: A__ = key.replace('''norm''' , '''layer_norm''' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 A__ = key[key.find('''segformer.encoder.layer_norm''' ) + len('''segformer.encoder.layer_norm''' )] A__ = key.replace(f"""layer_norm{idx}""" , f"""layer_norm.{int(lowercase_ )-1}""" ) if "layer_norm1" in key: A__ = key.replace('''layer_norm1''' , '''layer_norm_1''' ) if "layer_norm2" in key: A__ = key.replace('''layer_norm2''' , '''layer_norm_2''' ) if "block" in key: # replace for example block1 by block.0 A__ = key[key.find('''block''' ) + len('''block''' )] A__ = key.replace(f"""block{idx}""" , f"""block.{int(lowercase_ )-1}""" ) if "attn.q" in key: A__ = key.replace('''attn.q''' , '''attention.self.query''' ) if "attn.proj" in key: A__ = key.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in key: A__ = key.replace('''attn''' , '''attention.self''' ) if "fc1" in key: A__ = key.replace('''fc1''' , '''dense1''' ) if "fc2" in key: A__ = key.replace('''fc2''' , '''dense2''' ) if "linear_pred" in key: A__ = key.replace('''linear_pred''' , '''classifier''' ) if "linear_fuse" in key: A__ = key.replace('''linear_fuse.conv''' , '''linear_fuse''' ) A__ = key.replace('''linear_fuse.bn''' , '''batch_norm''' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 A__ = key[key.find('''linear_c''' ) + len('''linear_c''' )] A__ = key.replace(f"""linear_c{idx}""" , f"""linear_c.{int(lowercase_ )-1}""" ) if key.startswith('''head''' ): A__ = key.replace('''head''' , '''classifier''' ) A__ = value return new_state_dict def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> str: """simple docstring""" for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) A__ = state_dict.pop(f"""segformer.encoder.block.{i}.{j}.attention.self.kv.weight""" ) A__ = state_dict.pop(f"""segformer.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict A__ = kv_weight[ : config.hidden_sizes[i], : ] A__ = kv_bias[: config.hidden_sizes[i]] A__ = kv_weight[ config.hidden_sizes[i] :, : ] A__ = kv_bias[ config.hidden_sizes[i] : ] def SCREAMING_SNAKE_CASE ( ) -> Optional[Any]: """simple docstring""" A__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' A__ = Image.open(requests.get(lowercase_ , stream=lowercase_ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> List[str]: """simple docstring""" A__ = SegformerConfig() A__ = False # set attributes based on model_name A__ = '''huggingface/label-files''' if "segformer" in model_name: A__ = model_name[len('''segformer.''' ) : len('''segformer.''' ) + 2] if "ade" in model_name: A__ = 150 A__ = '''ade20k-id2label.json''' A__ = (1, 150, 128, 128) elif "city" in model_name: A__ = 19 A__ = '''cityscapes-id2label.json''' A__ = (1, 19, 128, 128) else: raise ValueError(f"""Model {model_name} not supported""" ) elif "mit" in model_name: A__ = True A__ = model_name[4:6] A__ = 1_000 A__ = '''imagenet-1k-id2label.json''' A__ = (1, 1_000) else: raise ValueError(f"""Model {model_name} not supported""" ) # set config attributes A__ = json.load(open(hf_hub_download(lowercase_ , lowercase_ , repo_type='''dataset''' ) , '''r''' ) ) A__ = {int(lowercase_ ): v for k, v in idalabel.items()} A__ = idalabel A__ = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": A__ = [64, 128, 320, 512] A__ = 256 elif size == "b2": A__ = [64, 128, 320, 512] A__ = 768 A__ = [3, 4, 6, 3] elif size == "b3": A__ = [64, 128, 320, 512] A__ = 768 A__ = [3, 4, 18, 3] elif size == "b4": A__ = [64, 128, 320, 512] A__ = 768 A__ = [3, 8, 27, 3] elif size == "b5": A__ = [64, 128, 320, 512] A__ = 768 A__ = [3, 6, 40, 3] else: raise ValueError(f"""Size {size} not supported""" ) # load image processor (only resize + normalize) A__ = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=lowercase_ , align=lowercase_ , do_random_crop=lowercase_ ) # prepare image A__ = prepare_img() A__ = image_processor(images=lowercase_ , return_tensors='''pt''' ).pixel_values logger.info(f"""Converting model {model_name}...""" ) # load original state dict if encoder_only: A__ = torch.load(lowercase_ , map_location=torch.device('''cpu''' ) ) else: A__ = torch.load(lowercase_ , map_location=torch.device('''cpu''' ) )['''state_dict'''] # rename keys A__ = rename_keys(lowercase_ , encoder_only=lowercase_ ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(lowercase_ , lowercase_ ) # create HuggingFace model and load state dict if encoder_only: A__ = False A__ = SegformerForImageClassification(lowercase_ ) else: A__ = SegformerForSemanticSegmentation(lowercase_ ) model.load_state_dict(lowercase_ ) model.eval() # forward pass A__ = model(lowercase_ ) A__ = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": A__ = torch.tensor( [ [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": A__ = torch.tensor( [ [[-7.58_20, -8.72_31, -8.32_15], [-8.06_00, -10.35_29, -10.03_04], [-7.52_08, -9.41_03, -9.62_39]], [[-12.69_18, -13.89_94, -13.71_37], [-13.31_96, -15.75_23, -15.47_89], [-12.93_43, -14.87_57, -14.96_89]], [[-11.19_11, -11.94_21, -11.32_43], [-11.33_42, -13.68_39, -13.35_81], [-10.39_09, -12.18_32, -12.48_58]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": A__ = torch.tensor( [ [[-11.81_73, -14.38_50, -16.31_28], [-14.56_48, -16.58_04, -18.65_68], [-14.72_23, -15.73_87, -18.42_18]], [[-15.72_90, -17.91_71, -19.44_23], [-18.31_05, -19.94_48, -21.46_61], [-17.92_96, -18.64_97, -20.79_10]], [[-15.07_83, -17.03_36, -18.27_89], [-16.87_71, -18.68_70, -20.16_12], [-16.24_54, -17.14_26, -19.50_55]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": A__ = torch.tensor( [ [[-9.08_78, -10.20_81, -10.18_91], [-9.31_44, -10.79_41, -10.98_43], [-9.22_94, -10.38_55, -10.57_04]], [[-12.23_16, -13.90_68, -13.61_02], [-12.91_61, -14.37_02, -14.32_35], [-12.52_33, -13.71_74, -13.79_32]], [[-14.62_75, -15.24_90, -14.97_27], [-14.34_00, -15.96_87, -16.28_27], [-14.14_84, -15.40_33, -15.89_37]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": A__ = torch.tensor( [ [[-12.31_44, -13.24_47, -14.08_02], [-13.36_14, -14.58_16, -15.61_17], [-13.33_40, -14.44_33, -16.22_19]], [[-19.27_81, -20.41_28, -20.75_06], [-20.61_53, -21.65_66, -22.09_98], [-19.98_00, -21.04_30, -22.14_94]], [[-18.87_39, -19.78_04, -21.18_34], [-20.12_33, -21.67_65, -23.29_44], [-20.03_15, -21.26_41, -23.69_44]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": A__ = torch.tensor( [ [[-9.55_24, -12.08_35, -11.73_48], [-10.52_29, -13.64_46, -14.56_62], [-9.58_42, -12.88_51, -13.94_14]], [[-15.34_32, -17.53_23, -17.08_18], [-16.33_30, -18.92_55, -19.21_01], [-15.13_40, -17.78_48, -18.39_71]], [[-12.60_72, -14.94_86, -14.66_31], [-13.76_29, -17.09_07, -17.77_45], [-12.78_99, -16.16_95, -17.16_71]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": A__ = torch.tensor( [ [[-11.92_95, -13.40_57, -14.81_06], [-13.34_31, -14.81_79, -15.37_81], [-14.28_36, -15.59_42, -16.15_88]], [[-11.49_06, -12.80_67, -13.65_64], [-13.11_89, -14.05_00, -14.15_43], [-13.87_48, -14.51_36, -14.87_89]], [[0.53_74, 0.10_67, -0.47_42], [0.11_41, -0.22_55, -0.70_99], [-0.30_00, -0.59_24, -1.31_05]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": A__ = torch.tensor( [ [[-7.82_17, -9.87_67, -10.17_17], [-9.44_38, -10.90_58, -11.40_47], [-9.79_39, -12.34_95, -12.10_79]], [[-7.15_14, -9.53_36, -10.08_60], [-9.77_76, -11.68_22, -11.84_39], [-10.14_11, -12.76_55, -12.89_72]], [[0.30_21, 0.08_05, -0.23_10], [-0.03_28, -0.16_05, -0.27_14], [-0.14_08, -0.54_77, -0.69_76]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": A__ = torch.tensor( [ [ [-1.1_3_7_2E0_1, -1.2_7_8_7E0_1, -1.3_4_7_7E0_1], [-1.2_5_3_6E0_1, -1.4_1_9_4E0_1, -1.4_4_0_9E0_1], [-1.3_2_1_7E0_1, -1.4_8_8_8E0_1, -1.5_3_2_7E0_1], ], [ [-1.4_7_9_1E0_1, -1.7_1_2_2E0_1, -1.8_2_7_7E0_1], [-1.7_1_6_3E0_1, -1.9_1_9_2E0_1, -1.9_5_3_3E0_1], [-1.7_8_9_7E0_1, -1.9_9_9_1E0_1, -2.0_3_1_5E0_1], ], [ [7.6_7_2_3E-0_1, 4.1_9_2_1E-0_1, -7.7_8_7_8E-0_2], [4.7_7_7_2E-0_1, 9.5_5_5_7E-0_3, -2.8_0_8_2E-0_1], [3.6_0_3_2E-0_1, -2.4_8_2_6E-0_1, -5.1_1_6_8E-0_1], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": A__ = torch.tensor( [ [[-9.49_59, -11.30_87, -11.74_79], [-11.00_25, -12.65_40, -12.33_19], [-11.40_64, -13.04_87, -12.99_05]], [[-9.89_05, -11.30_84, -12.08_54], [-11.17_26, -12.76_98, -12.95_83], [-11.59_85, -13.32_78, -14.17_74]], [[0.22_13, 0.01_92, -0.24_66], [-0.17_31, -0.42_13, -0.48_74], [-0.31_26, -0.65_41, -1.13_89]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": A__ = torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": A__ = torch.tensor( [ [[-16.09_76, -16.48_56, -17.39_62], [-16.62_34, -19.03_42, -19.76_85], [-16.09_00, -18.06_61, -19.11_80]], [[-18.47_50, -18.84_88, -19.50_74], [-19.40_30, -22.15_70, -22.59_77], [-19.11_91, -20.84_86, -22.37_83]], [[-4.51_78, -5.50_37, -6.51_09], [-5.08_84, -7.21_74, -8.03_34], [-4.41_56, -5.81_17, -7.29_70]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": A__ = torch.tensor( [ [[-14.20_81, -14.47_32, -14.19_77], [-14.58_67, -16.44_23, -16.63_56], [-13.44_41, -14.96_85, -16.86_96]], [[-14.45_76, -14.70_73, -15.04_51], [-15.08_16, -17.62_37, -17.98_73], [-14.42_13, -16.01_99, -18.59_92]], [[-4.73_49, -4.95_88, -5.09_66], [-4.32_10, -6.93_25, -7.25_91], [-3.43_12, -4.74_84, -7.19_17]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": A__ = torch.tensor( [ [[-11.77_37, -11.95_26, -11.32_73], [-13.66_92, -14.45_74, -13.88_78], [-13.89_37, -14.69_24, -15.93_45]], [[-14.67_06, -14.53_30, -14.13_06], [-16.15_02, -16.81_80, -16.42_69], [-16.83_38, -17.89_39, -20.17_46]], [[1.04_91, 0.82_89, 1.03_10], [1.10_44, 0.52_19, 0.80_55], [1.08_99, 0.69_26, 0.55_90]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": A__ = torch.tensor( [ [[-12.56_41, -13.47_77, -13.06_84], [-13.95_87, -15.89_83, -16.65_57], [-13.31_09, -15.73_50, -16.31_41]], [[-14.70_74, -15.43_52, -14.59_44], [-16.63_53, -18.16_63, -18.61_20], [-15.17_02, -18.03_29, -18.15_47]], [[-1.79_90, -2.09_51, -1.77_84], [-2.63_97, -3.82_45, -3.96_86], [-1.52_64, -2.81_26, -2.93_16]], ] ) else: A__ = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , lowercase_ , atol=1E-2 ) # finally, save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) model.save_pretrained(lowercase_ ) image_processor.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument( """--model_name""", default="""segformer.b0.512x512.ade.160k""", type=str, help="""Name of the model you'd like to convert.""", ) parser.add_argument( """--checkpoint_path""", default=None, 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 folder to output PyTorch model.""" ) _lowerCamelCase : Union[str, Any] = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
14
'''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
0
def UpperCAmelCase ( a_ , a_ ) -> float: """simple docstring""" if mass < 0: raise ValueError("The mass of a body cannot be negative" ) return 0.5 * mass * abs(a_ ) * abs(a_ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
15
'''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
0
"""simple docstring""" import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowerCAmelCase_ = logging.getLogger(__name__) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , ) -> int: lowercase__ : Dict = bnb_quantization_config.load_in_abit lowercase__ : int = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,''' ''' make sure you have the latest version of `bitsandbytes` installed.''' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,''' '''make sure you have the latest version of `bitsandbytes` installed.''' ) lowercase__ : List[str] = [] # custom device map if isinstance(__lowerCamelCase , __lowerCamelCase ) and len(device_map.keys() ) > 1: lowercase__ : str = [key for key, value in device_map.items() if value in ['''disk''', '''cpu''']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowercase__ : Any = get_keys_to_not_convert(__lowerCamelCase ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__lowerCamelCase ) lowercase__ : Union[str, Any] = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowercase__ : Union[str, Any] = [] lowercase__ : Optional[Any] = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__lowerCamelCase ) # compatibility with peft lowercase__ : Optional[Any] = load_in_abit lowercase__ : Optional[Any] = load_in_abit lowercase__ : str = get_parameter_device(__lowerCamelCase ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( '''It is not recommended to quantize a loaded model. ''' '''The model should be instantiated under the `init_empty_weights` context manager.''' ) lowercase__ : Dict = replace_with_bnb_layers(__lowerCamelCase , __lowerCamelCase , modules_to_not_convert=__lowerCamelCase ) # convert param to the right dtype lowercase__ : Dict = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowercase__ : Any = name.replace('''.weight''' , '''''' ).replace('''.bias''' , '''''' ) lowercase__ : Dict = getattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__lowerCamelCase ): param.to(__lowerCamelCase ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" '''We move the model to cuda.''' ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowercase__ : int = replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , modules_to_not_convert=__lowerCamelCase ) lowercase__ : List[str] = get_quantized_model_device_map( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , max_memory=__lowerCamelCase , no_split_module_classes=__lowerCamelCase , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowercase__ : List[str] = True lowercase__ : int = any(x in list(device_map.values() ) for x in ['''cpu''', '''disk'''] ) load_checkpoint_in_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , dtype=bnb_quantization_config.torch_dtype , offload_folder=__lowerCamelCase , offload_state_dict=__lowerCamelCase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__lowerCamelCase , device_map=__lowerCamelCase , offload_dir=__lowerCamelCase ) def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None ) -> int: if device_map is None: if torch.cuda.is_available(): lowercase__ : Optional[int] = {'''''': torch.cuda.current_device()} else: raise RuntimeError('''No GPU found. A GPU is needed for quantization.''' ) logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.''' ) if isinstance(__lowerCamelCase , __lowerCamelCase ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ''' '''\'sequential\'.''' ) lowercase__ : List[str] = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowercase__ : List[str] = {} lowercase__ : Tuple = special_dtypes lowercase__ : Optional[int] = no_split_module_classes lowercase__ : int = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowercase__ : Optional[Any] = get_balanced_memory( __lowerCamelCase , low_zero=(device_map == '''balanced_low_0''') , max_memory=__lowerCamelCase , **__lowerCamelCase , ) lowercase__ : int = max_memory lowercase__ : List[Any] = infer_auto_device_map(__lowerCamelCase , **__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): # check if don't have any quantized module on the cpu lowercase__ : Any = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowercase__ : Union[str, Any] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( ''' Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules in `torch_dtype`, you need to pass a custom `device_map` to `load_and_quantize_model`. Check https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk for more details. ''' ) else: logger.info( '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit''' ) del device_map_without_some_modules return device_map def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None ) -> str: if modules_to_not_convert is None: lowercase__ : Optional[int] = [] lowercase__ , lowercase__ : Optional[Any] = _replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) 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.''' ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ) -> int: lowercase__ : Optional[Any] = False for name, module in model.named_children(): if current_key_name is None: lowercase__ : Optional[int] = [] current_key_name.append(__lowerCamelCase ) if isinstance(__lowerCamelCase , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowercase__ : Union[str, Any] = '''.'''.join(__lowerCamelCase ) lowercase__ : Dict = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowercase__ : int = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowercase__ : Optional[int] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__lowerCamelCase , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowercase__ : Dict = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False''' ) lowercase__ : List[str] = module.weight.data if module.bias is not None: lowercase__ : Dict = module.bias.data bnb_module.requires_grad_(__lowerCamelCase ) setattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) lowercase__ : Tuple = True if len(list(module.children() ) ) > 0: lowercase__ , lowercase__ : int = _replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) lowercase__ : Union[str, Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def __UpperCAmelCase ( __lowerCamelCase ) -> List[str]: # Create a copy of the model with init_empty_weights(): lowercase__ : int = deepcopy(__lowerCamelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowercase__ : Optional[Any] = find_tied_parameters(__lowerCamelCase ) # For compatibility with Accelerate < 0.18 if isinstance(__lowerCamelCase , __lowerCamelCase ): lowercase__ : List[str] = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowercase__ : Optional[int] = sum(__lowerCamelCase , [] ) lowercase__ : List[str] = len(__lowerCamelCase ) > 0 # Check if it is a base model lowercase__ : Any = False if hasattr(__lowerCamelCase , '''base_model_prefix''' ): lowercase__ : Optional[int] = not hasattr(__lowerCamelCase , 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 lowercase__ : int = list(model.named_children() ) lowercase__ : List[Any] = [list_modules[-1][0]] # add last module together with tied weights lowercase__ : Union[str, Any] = set(__lowerCamelCase ) - set(__lowerCamelCase ) lowercase__ : List[str] = list(set(__lowerCamelCase ) ) + list(__lowerCamelCase ) # remove ".weight" from the keys lowercase__ : int = ['''.weight''', '''.bias'''] lowercase__ : Optional[Any] = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowercase__ : str = name.replace(__lowerCamelCase , '''''' ) filtered_module_names.append(__lowerCamelCase ) return filtered_module_names def __UpperCAmelCase ( __lowerCamelCase ) -> Dict: for m in model.modules(): if isinstance(__lowerCamelCase , bnb.nn.Linearabit ): return True return False def __UpperCAmelCase ( __lowerCamelCase ) -> Dict: return next(parameter.parameters() ).device def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> List[str]: # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(__lowerCamelCase , __lowerCamelCase , 0 , dtype=__lowerCamelCase , value=__lowerCamelCase ) lowercase__ : Any = param_name lowercase__ : List[Any] = model if "." in tensor_name: lowercase__ : Dict = tensor_name.split('''.''' ) for split in splits[:-1]: lowercase__ : int = getattr(__lowerCamelCase , __lowerCamelCase ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) lowercase__ : int = new_module lowercase__ : str = splits[-1] # offload weights lowercase__ : Any = False offload_weight(module._parameters[tensor_name] , __lowerCamelCase , __lowerCamelCase , index=__lowerCamelCase ) if hasattr(module._parameters[tensor_name] , '''SCB''' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('''weight''' , '''SCB''' ) , __lowerCamelCase , index=__lowerCamelCase , ) else: offload_weight(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , index=__lowerCamelCase ) offload_weight(__lowerCamelCase , param_name.replace('''weight''' , '''SCB''' ) , __lowerCamelCase , index=__lowerCamelCase ) set_module_tensor_to_device(__lowerCamelCase , __lowerCamelCase , '''meta''' , dtype=__lowerCamelCase , value=torch.empty(*param.size() ) )
16
'''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
0
"""simple docstring""" import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights __lowercase = FlaxDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=UpperCAmelCase__, cache_dir=UpperCAmelCase__ ) __lowercase = [t[-1] for t in os.walk(os.path.join(UpperCAmelCase__, os.listdir(UpperCAmelCase__ )[0], "snapshots" ) )] __lowercase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(".bin" ) for f in files ) @slow @require_flax class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def _lowercase ( self : List[Any] ): __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=UpperCAmelCase__ ) __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.random.PRNGKey(0 ) __lowercase = 4 __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) # shard inputs and rng __lowercase = replicate(UpperCAmelCase__ ) __lowercase = jax.random.split(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 6_4, 6_4, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:], dtype=np.floataa ).sum() - 4.1_514_745 ) < 1E-3 assert np.abs(np.abs(UpperCAmelCase__, dtype=np.floataa ).sum() - 49_947.875 ) < 5E-1 __lowercase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(UpperCAmelCase__ ) == num_samples def _lowercase ( self : int ): __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="flax", safety_checker=UpperCAmelCase__ ) __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.random.PRNGKey(0 ) __lowercase = 5_0 __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) # shard inputs and rng __lowercase = replicate(UpperCAmelCase__ ) __lowercase = jax.random.split(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.floataa ).sum() - 0.05_652_401) ) < 1E-3 assert np.abs((np.abs(UpperCAmelCase__, dtype=np.floataa ).sum() - 2_383_808.2) ) < 5E-1 def _lowercase ( self : Optional[int] ): __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jnp.bfloataa, safety_checker=UpperCAmelCase__ ) __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.random.PRNGKey(0 ) __lowercase = 5_0 __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) # shard inputs and rng __lowercase = replicate(UpperCAmelCase__ ) __lowercase = jax.random.split(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3 assert np.abs((np.abs(UpperCAmelCase__, dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1 def _lowercase ( self : Optional[int] ): __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jnp.bfloataa ) __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.random.PRNGKey(0 ) __lowercase = 5_0 __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) # shard inputs and rng __lowercase = replicate(UpperCAmelCase__ ) __lowercase = jax.random.split(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.floataa ).sum() - 0.04_003_906) ) < 1E-3 assert np.abs((np.abs(UpperCAmelCase__, dtype=np.floataa ).sum() - 2_373_516.75) ) < 5E-1 def _lowercase ( self : Optional[int] ): __lowercase = FlaxDDIMScheduler( beta_start=0.00_085, beta_end=0.012, beta_schedule="scaled_linear", set_alpha_to_one=UpperCAmelCase__, steps_offset=1, ) __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jnp.bfloataa, scheduler=UpperCAmelCase__, safety_checker=UpperCAmelCase__, ) __lowercase = scheduler.create_state() __lowercase = scheduler_state __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.random.PRNGKey(0 ) __lowercase = 5_0 __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) # shard inputs and rng __lowercase = replicate(UpperCAmelCase__ ) __lowercase = jax.random.split(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.floataa ).sum() - 0.045_043_945) ) < 1E-3 assert np.abs((np.abs(UpperCAmelCase__, dtype=np.floataa ).sum() - 2_347_693.5) ) < 5E-1 def _lowercase ( self : Dict ): __lowercase = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __lowercase = jax.device_count() __lowercase = num_samples * [prompt] __lowercase = jax.random.split(jax.random.PRNGKey(0 ), UpperCAmelCase__ ) __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jnp.bfloataa, safety_checker=UpperCAmelCase__, ) __lowercase = replicate(UpperCAmelCase__ ) __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) __lowercase = images[2, 0, 2_5_6, 1_0:1_7, 1] # With memory efficient attention __lowercase ,__lowercase = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", revision="bf16", dtype=jnp.bfloataa, safety_checker=UpperCAmelCase__, use_memory_efficient_attention=UpperCAmelCase__, ) __lowercase = replicate(UpperCAmelCase__ ) __lowercase = pipeline.prepare_inputs(UpperCAmelCase__ ) __lowercase = shard(UpperCAmelCase__ ) __lowercase = pipeline(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, jit=UpperCAmelCase__ ).images assert images_eff.shape == (num_samples, 1, 5_1_2, 5_1_2, 3) __lowercase = images[2, 0, 2_5_6, 1_0:1_7, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
17
'''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
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase : str = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Any = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys __lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
18
'''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
0
import math def lowerCamelCase_ ( lowerCamelCase__ ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCamelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCamelCase_ ( lowerCamelCase__ = 0.1 ): lowerCamelCase_ = 3 lowerCamelCase_ = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(lowerCamelCase__ ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
19
'''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
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType lowercase : Any = logging.get_logger(__name__) lowercase : Optional[int] = { """microsoft/deberta-v2-xlarge""": """https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json""", """microsoft/deberta-v2-xxlarge""": """https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json""", """microsoft/deberta-v2-xlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json""" ), """microsoft/deberta-v2-xxlarge-mnli""": ( """https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json""" ), } class __snake_case ( lowerCAmelCase ): _a : Any= "deberta-v2" def __init__( self ,snake_case=128100 ,snake_case=1536 ,snake_case=24 ,snake_case=24 ,snake_case=6144 ,snake_case="gelu" ,snake_case=0.1 ,snake_case=0.1 ,snake_case=512 ,snake_case=0 ,snake_case=0.02 ,snake_case=1e-7 ,snake_case=False ,snake_case=-1 ,snake_case=0 ,snake_case=True ,snake_case=None ,snake_case=0 ,snake_case="gelu" ,**snake_case ,): '''simple docstring''' super().__init__(**snake_case ) lowercase : Union[str, Any] = hidden_size lowercase : int = num_hidden_layers lowercase : str = num_attention_heads lowercase : Any = intermediate_size lowercase : Any = hidden_act lowercase : Optional[Any] = hidden_dropout_prob lowercase : List[Any] = attention_probs_dropout_prob lowercase : Optional[Any] = max_position_embeddings lowercase : Optional[int] = type_vocab_size lowercase : Optional[int] = initializer_range lowercase : Tuple = relative_attention lowercase : Any = max_relative_positions lowercase : Any = pad_token_id lowercase : Optional[int] = position_biased_input # Backwards compatibility if type(snake_case ) == str: lowercase : Tuple = [x.strip() for x in pos_att_type.lower().split("""|""" )] lowercase : List[str] = pos_att_type lowercase : Dict = vocab_size lowercase : int = layer_norm_eps lowercase : Union[str, Any] = kwargs.get("""pooler_hidden_size""" ,snake_case ) lowercase : Any = pooler_dropout lowercase : Dict = pooler_hidden_act class __snake_case ( lowerCAmelCase ): @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' if self.task == "multiple-choice": lowercase : Union[str, Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowercase : List[str] = {0: """batch""", 1: """sequence"""} if self._config.type_vocab_size > 0: return OrderedDict( [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)] ) else: return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)] ) @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return 12 def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case = -1 ,snake_case = -1 ,snake_case = -1 ,snake_case = False ,snake_case = None ,snake_case = 3 ,snake_case = 40 ,snake_case = 40 ,snake_case = None ,): '''simple docstring''' lowercase : Union[str, Any] = super().generate_dummy_inputs(preprocessor=snake_case ,framework=snake_case ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
20
'''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
0
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[Any] = 'laion/clap-htsat-unfused' _lowercase : Optional[Any] = tempfile.mkdtemp() def UpperCamelCase ( self, **lowerCamelCase) -> List[Any]: """simple docstring""" return RobertaTokenizer.from_pretrained(self.checkpoint, **lowerCamelCase) def UpperCamelCase ( self, **lowerCamelCase) -> str: """simple docstring""" return ClapFeatureExtractor.from_pretrained(self.checkpoint, **lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : str = self.get_tokenizer() _lowercase : Optional[int] = self.get_feature_extractor() _lowercase : int = ClapProcessor(tokenizer=lowerCamelCase, feature_extractor=lowerCamelCase) processor.save_pretrained(self.tmpdirname) _lowercase : Union[str, Any] = ClapProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer, lowerCamelCase) self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor, lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Optional[int] = ClapProcessor(tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()) processor.save_pretrained(self.tmpdirname) _lowercase : str = self.get_tokenizer(bos_token='(BOS)', eos_token='(EOS)') _lowercase : List[str] = self.get_feature_extractor(do_normalize=lowerCamelCase, padding_value=1.0) _lowercase : Tuple = ClapProcessor.from_pretrained( self.tmpdirname, bos_token='(BOS)', eos_token='(EOS)', do_normalize=lowerCamelCase, padding_value=1.0) self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab()) self.assertIsInstance(processor.tokenizer, lowerCamelCase) self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string()) self.assertIsInstance(processor.feature_extractor, lowerCamelCase) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Union[str, Any] = self.get_feature_extractor() _lowercase : List[Any] = self.get_tokenizer() _lowercase : Dict = ClapProcessor(tokenizer=lowerCamelCase, feature_extractor=lowerCamelCase) _lowercase : Union[str, Any] = floats_list((3, 10_00)) _lowercase : str = feature_extractor(lowerCamelCase, return_tensors='np') _lowercase : Tuple = processor(audios=lowerCamelCase, return_tensors='np') for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1E-2) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[int] = self.get_feature_extractor() _lowercase : Any = self.get_tokenizer() _lowercase : Dict = ClapProcessor(tokenizer=lowerCamelCase, feature_extractor=lowerCamelCase) _lowercase : Any = 'This is a test string' _lowercase : List[Any] = processor(text=lowerCamelCase) _lowercase : Dict = tokenizer(lowerCamelCase) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key], encoded_processor[key]) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Tuple = self.get_feature_extractor() _lowercase : str = self.get_tokenizer() _lowercase : List[str] = ClapProcessor(tokenizer=lowerCamelCase, feature_extractor=lowerCamelCase) _lowercase : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _lowercase : str = processor.batch_decode(lowerCamelCase) _lowercase : Any = tokenizer.batch_decode(lowerCamelCase) self.assertListEqual(lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Dict = self.get_feature_extractor() _lowercase : Any = self.get_tokenizer() _lowercase : Tuple = ClapProcessor(tokenizer=lowerCamelCase, feature_extractor=lowerCamelCase) self.assertListEqual( processor.model_input_names[2:], feature_extractor.model_input_names, msg='`processor` and `feature_extractor` model input names do not match', )
21
'''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
0
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase_ ( __lowercase : int , __lowercase : Dict , __lowercase : str , __lowercase : Optional[Any] , __lowercase : str ) -> List[str]: '''simple docstring''' _UpperCAmelCase = TapasConfig.from_json_file(__lowercase ) # set absolute/relative position embeddings parameter _UpperCAmelCase = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": _UpperCAmelCase = TapasForQuestionAnswering(config=__lowercase ) elif task == "WTQ": # run_task_main.py hparams _UpperCAmelCase = 4 _UpperCAmelCase = True # hparam_utils.py hparams _UpperCAmelCase = 0.66_4694 _UpperCAmelCase = 0.20_7951 _UpperCAmelCase = 0.12_1194 _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = False _UpperCAmelCase = 0.035_2513 _UpperCAmelCase = TapasForQuestionAnswering(config=__lowercase ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams _UpperCAmelCase = 4 _UpperCAmelCase = False # hparam_utils.py hparams _UpperCAmelCase = 36.4519 _UpperCAmelCase = 0.90_3421 _UpperCAmelCase = 222.088 _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = 0.76_3141 _UpperCAmelCase = TapasForQuestionAnswering(config=__lowercase ) elif task == "TABFACT": _UpperCAmelCase = TapasForSequenceClassification(config=__lowercase ) elif task == "MLM": _UpperCAmelCase = TapasForMaskedLM(config=__lowercase ) elif task == "INTERMEDIATE_PRETRAINING": _UpperCAmelCase = TapasModel(config=__lowercase ) else: raise ValueError(f'Task {task} not supported.' ) print(f'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(__lowercase , __lowercase , __lowercase ) # Save pytorch-model (weights and configuration) print(f'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__lowercase ) # Save tokenizer files print(f'Save tokenizer files to {pytorch_dump_path}' ) _UpperCAmelCase = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + "vocab.txt" , model_max_length=512 ) tokenizer.save_pretrained(__lowercase ) print("Used relative position embeddings:" , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--task''', default='''SQA''', type=str, help='''Model task for which to convert a checkpoint. Defaults to SQA.''' ) parser.add_argument( '''--reset_position_index_per_cell''', default=False, action='''store_true''', help='''Whether to use relative position embeddings or not. Defaults to True.''', ) parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--tapas_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained TAPAS model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) __SCREAMING_SNAKE_CASE :List[str] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
22
'''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
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase__: Tuple = logging.get_logger(__name__) UpperCamelCase__: Optional[int] = {"vocab_file": "sentencepiece.bpe.model"} UpperCamelCase__: Optional[int] = { "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, } UpperCamelCase__: Dict = { "moussaKam/mbarthez": 1024, "moussaKam/barthez": 1024, "moussaKam/barthez-orangesum-title": 1024, } UpperCamelCase__: Tuple = "▁" class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Tuple="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="</s>" , __snake_case : Any="<s>" , __snake_case : Optional[int]="<unk>" , __snake_case : Union[str, Any]="<pad>" , __snake_case : Union[str, Any]="<mask>" , __snake_case : Optional[Dict[str, Any]] = None , **__snake_case : Dict , ) -> None: # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase : int = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else mask_token UpperCAmelCase : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__snake_case , eos_token=__snake_case , unk_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , sp_model_kwargs=self.sp_model_kwargs , **__snake_case , ) UpperCAmelCase : Optional[int] = vocab_file UpperCAmelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__snake_case ) ) UpperCAmelCase : int = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} UpperCAmelCase : Optional[Any] = len(self.sp_model ) - 1 UpperCAmelCase : Optional[int] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def A ( self : Tuple , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase : Union[str, Any] = [self.cls_token_id] UpperCAmelCase : Optional[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A ( self : int , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is None: return [1] + ([0] * len(__snake_case )) + [1] return [1] + ([0] * len(__snake_case )) + [1, 1] + ([0] * len(__snake_case )) + [1] def A ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ) -> List[int]: UpperCAmelCase : Tuple = [self.sep_token_id] UpperCAmelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A ( self : Dict ) -> Optional[int]: return len(self.sp_model ) def A ( self : List[str] ) -> Dict: UpperCAmelCase : Optional[Any] = {self.convert_ids_to_tokens(__snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A ( self : Optional[Any] , __snake_case : str ) -> List[str]: return self.sp_model.encode(__snake_case , out_type=__snake_case ) def A ( self : int , __snake_case : int ) -> int: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] UpperCAmelCase : Optional[Any] = self.sp_model.PieceToId(__snake_case ) return spm_id if spm_id else self.unk_token_id def A ( self : int , __snake_case : Any ) -> List[Any]: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__snake_case ) def A ( self : List[Any] , __snake_case : Union[str, Any] ) -> List[str]: UpperCAmelCase : Optional[Any] = [] UpperCAmelCase : int = '''''' UpperCAmelCase : Union[str, Any] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__snake_case ) + token UpperCAmelCase : str = True UpperCAmelCase : List[str] = [] else: current_sub_tokens.append(__snake_case ) UpperCAmelCase : Optional[int] = False out_string += self.sp_model.decode(__snake_case ) return out_string.strip() def __getstate__( self : Union[str, Any] ) -> Union[str, Any]: UpperCAmelCase : Optional[Any] = self.__dict__.copy() UpperCAmelCase : Any = None return state def __setstate__( self : Optional[int] , __snake_case : Union[str, Any] ) -> List[Any]: UpperCAmelCase : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase : Optional[Any] = {} UpperCAmelCase : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A ( self : Optional[int] , __snake_case : str , __snake_case : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__snake_case ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase : Union[str, Any] = os.path.join( __snake_case , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__snake_case ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __snake_case ) elif not os.path.isfile(self.vocab_file ): with open(__snake_case , '''wb''' ) as fi: UpperCAmelCase : Any = self.sp_model.serialized_model_proto() fi.write(__snake_case ) return (out_vocab_file,)
23
'''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
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 snake_case_ = get_tests_dir('fixtures') class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def a (self : List[str] ): """simple docstring""" __snake_case = mock.Mock() __snake_case = 500 __snake_case = {} __snake_case = HTTPError __snake_case = {} # Download this model to make sure it's in the cache. __snake_case = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=a__ ) as mock_head: __snake_case = WavaVecaFeatureExtractor.from_pretrained('''hf-internal-testing/tiny-random-wav2vec2''' ) # This check we did call the fake head request mock_head.assert_called() def a (self : Any ): """simple docstring""" __snake_case = WavaVecaFeatureExtractor.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json''' ) @is_staging_test class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @classmethod def a (cls : List[Any] ): """simple docstring""" __snake_case = TOKEN HfFolder.save_token(a__ ) @classmethod def a (cls : Optional[int] ): """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-feature-extractor''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-feature-extractor-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-feature-extractor''' ) except HTTPError: pass def a (self : Optional[int] ): """simple docstring""" __snake_case = WavaVecaFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''test-feature-extractor''' , use_auth_token=self._token ) __snake_case = WavaVecaFeatureExtractor.from_pretrained(f"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a__ , repo_id='''test-feature-extractor''' , push_to_hub=a__ , use_auth_token=self._token ) __snake_case = WavaVecaFeatureExtractor.from_pretrained(f"""{USER}/test-feature-extractor""" ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) def a (self : str ): """simple docstring""" __snake_case = WavaVecaFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''valid_org/test-feature-extractor''' , use_auth_token=self._token ) __snake_case = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-feature-extractor''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a__ , repo_id='''valid_org/test-feature-extractor-org''' , push_to_hub=a__ , use_auth_token=self._token ) __snake_case = WavaVecaFeatureExtractor.from_pretrained('''valid_org/test-feature-extractor-org''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a__ , getattr(a__ , a__ ) ) def a (self : Any ): """simple docstring""" CustomFeatureExtractor.register_for_auto_class() __snake_case = CustomFeatureExtractor.from_pretrained(a__ ) feature_extractor.push_to_hub('''test-dynamic-feature-extractor''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor'''} , ) __snake_case = AutoFeatureExtractor.from_pretrained( f"""{USER}/test-dynamic-feature-extractor""" , trust_remote_code=a__ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , '''CustomFeatureExtractor''' )
24
'''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
0
"""simple docstring""" import argparse import os import re UpperCAmelCase__ : Any = 'src/transformers' # Pattern that looks at the indentation in a line. UpperCAmelCase__ : Union[str, Any] = re.compile(r'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. UpperCAmelCase__ : Union[str, Any] = re.compile(r'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. UpperCAmelCase__ : Optional[Any] = re.compile(r'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. UpperCAmelCase__ : List[str] = re.compile(r'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. UpperCAmelCase__ : Optional[Any] = re.compile(r'\[([^\]]+)\]') def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = _re_indent.search(_snake_case ) return "" if search is None else search.groups()[0] def lowercase_ ( _snake_case ,_snake_case="" ,_snake_case=None ,_snake_case=None ): SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Dict = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(_snake_case ): index += 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = ["""\n""".join(lines[:index] )] else: SCREAMING_SNAKE_CASE__ : List[Any] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). SCREAMING_SNAKE_CASE__ : Any = [lines[index]] index += 1 while index < len(_snake_case ) and (end_prompt is None or not lines[index].startswith(_snake_case )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_snake_case ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(_snake_case ) ) if index < len(_snake_case ) - 1: SCREAMING_SNAKE_CASE__ : Dict = [lines[index + 1]] index += 1 else: SCREAMING_SNAKE_CASE__ : int = [] else: blocks.append("""\n""".join(_snake_case ) ) SCREAMING_SNAKE_CASE__ : List[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_snake_case ) > 0: blocks.append("""\n""".join(_snake_case ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_snake_case ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def lowercase_ ( _snake_case ): def _inner(_snake_case ): return key(_snake_case ).lower().replace("""_""" ,"""""" ) return _inner def lowercase_ ( _snake_case ,_snake_case=None ): # If no key is provided, we use a noop. def noop(_snake_case ): return x if key is None: SCREAMING_SNAKE_CASE__ : str = noop # Constants are all uppercase, they go first. SCREAMING_SNAKE_CASE__ : Dict = [obj for obj in objects if key(_snake_case ).isupper()] # Classes are not all uppercase but start with a capital, they go second. SCREAMING_SNAKE_CASE__ : List[str] = [obj for obj in objects if key(_snake_case )[0].isupper() and not key(_snake_case ).isupper()] # Functions begin with a lowercase, they go last. SCREAMING_SNAKE_CASE__ : Optional[int] = [obj for obj in objects if not key(_snake_case )[0].isupper()] SCREAMING_SNAKE_CASE__ : str = ignore_underscore(_snake_case ) return sorted(_snake_case ,key=_snake_case ) + sorted(_snake_case ,key=_snake_case ) + sorted(_snake_case ,key=_snake_case ) def lowercase_ ( _snake_case ): # This inner function sort imports between [ ]. def _replace(_snake_case ): SCREAMING_SNAKE_CASE__ : List[str] = match.groups()[0] if "," not in imports: return f'''[{imports}]''' SCREAMING_SNAKE_CASE__ : int = [part.strip().replace("""\"""" ,"""""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = keys[:-1] return "[" + ", ".join([f'''"{k}"''' for k in sort_objects(_snake_case )] ) + "]" SCREAMING_SNAKE_CASE__ : Optional[Any] = import_statement.split("""\n""" ) if len(_snake_case ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. SCREAMING_SNAKE_CASE__ : Dict = 2 if lines[1].strip() == """[""" else 1 SCREAMING_SNAKE_CASE__ : Dict = [(i, _re_strip_line.search(_snake_case ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] SCREAMING_SNAKE_CASE__ : Optional[Any] = sort_objects(_snake_case ,key=lambda _snake_case : x[1] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_snake_case ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: SCREAMING_SNAKE_CASE__ : List[Any] = _re_bracket_content.sub(_replace ,lines[1] ) else: SCREAMING_SNAKE_CASE__ : Dict = [part.strip().replace("""\"""" ,"""""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE__ : Optional[int] = keys[:-1] SCREAMING_SNAKE_CASE__ : str = get_indent(lines[1] ) + """, """.join([f'''"{k}"''' for k in sort_objects(_snake_case )] ) return "\n".join(_snake_case ) else: # Finally we have to deal with imports fitting on one line SCREAMING_SNAKE_CASE__ : Dict = _re_bracket_content.sub(_replace ,_snake_case ) return import_statement def lowercase_ ( _snake_case ,_snake_case=True ): with open(_snake_case ,encoding="""utf-8""" ) as f: SCREAMING_SNAKE_CASE__ : List[Any] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 SCREAMING_SNAKE_CASE__ : Optional[int] = split_code_in_indented_blocks( _snake_case ,start_prompt="""_import_structure = {""" ,end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(_snake_case ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. SCREAMING_SNAKE_CASE__ : Optional[Any] = main_blocks[block_idx] SCREAMING_SNAKE_CASE__ : Dict = block.split("""\n""" ) # Get to the start of the imports. SCREAMING_SNAKE_CASE__ : int = 0 while line_idx < len(_snake_case ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: SCREAMING_SNAKE_CASE__ : Dict = len(_snake_case ) else: line_idx += 1 if line_idx >= len(_snake_case ): continue # Ignore beginning and last line: they don't contain anything. SCREAMING_SNAKE_CASE__ : Dict = """\n""".join(block_lines[line_idx:-1] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. SCREAMING_SNAKE_CASE__ : Dict = split_code_in_indented_blocks(_snake_case ,indent_level=_snake_case ) # We have two categories of import key: list or _import_structure[key].append/extend SCREAMING_SNAKE_CASE__ : Union[str, Any] = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. SCREAMING_SNAKE_CASE__ : Optional[Any] = [(pattern.search(_snake_case ).groups()[0] if pattern.search(_snake_case ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. SCREAMING_SNAKE_CASE__ : Tuple = [(i, key) for i, key in enumerate(_snake_case ) if key is not None] SCREAMING_SNAKE_CASE__ : List[str] = [x[0] for x in sorted(_snake_case ,key=lambda _snake_case : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for i in range(len(_snake_case ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: SCREAMING_SNAKE_CASE__ : Dict = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(_snake_case ) count += 1 # And we put our main block back together with its first and last line. SCREAMING_SNAKE_CASE__ : Dict = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(_snake_case ): if check_only: return True else: print(f'''Overwriting {file}.''' ) with open(_snake_case ,"""w""" ,encoding="""utf-8""" ) as f: f.write("""\n""".join(_snake_case ) ) def lowercase_ ( _snake_case=True ): SCREAMING_SNAKE_CASE__ : int = [] for root, _, files in os.walk(_snake_case ): if "__init__.py" in files: SCREAMING_SNAKE_CASE__ : Union[str, Any] = sort_imports(os.path.join(_snake_case ,"""__init__.py""" ) ,check_only=_snake_case ) if result: SCREAMING_SNAKE_CASE__ : Dict = [os.path.join(_snake_case ,"""__init__.py""" )] if len(_snake_case ) > 0: raise ValueError(f'''Would overwrite {len(_snake_case )} files, run `make style`.''' ) if __name__ == "__main__": UpperCAmelCase__ : str = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') UpperCAmelCase__ : List[str] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
25
'''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
0
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer _snake_case = "bart" _snake_case = True @st.cache(allow_output_mutation=snake_case_ ) def lowerCAmelCase_ ( ): if LOAD_DENSE_INDEX: _A : Optional[int] = AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased""" ) _A : Tuple = AutoModel.from_pretrained("""yjernite/retribert-base-uncased""" ).to("""cuda:0""" ) _A : str = qar_model.eval() else: _A , _A : Dict = (None, None) if MODEL_TYPE == "bart": _A : Tuple = AutoTokenizer.from_pretrained("""yjernite/bart_eli5""" ) _A : Optional[Any] = AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5""" ).to("""cuda:0""" ) _A : int = torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth""" ) sas_model.load_state_dict(save_dict["""model"""] ) _A : Tuple = sas_model.eval() else: _A , _A : Optional[int] = make_qa_sas_model( model_name="""t5-small""",from_file="""seq2seq_models/eli5_t5_model_1024_4.pth""",device="""cuda:0""" ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=snake_case_ ) def lowerCAmelCase_ ( ): if LOAD_DENSE_INDEX: _A : int = faiss.StandardGpuResources() _A : int = datasets.load_dataset(path="""wiki_snippets""",name="""wiki40b_en_100_0""" )["""train"""] _A : List[str] = np.memmap( """wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat""",dtype="""float32""",mode="""r""",shape=(wikiaab_passages.num_rows, 128),) _A : Any = faiss.IndexFlatIP(128 ) _A : Union[str, Any] = faiss.index_cpu_to_gpu(snake_case_,1,snake_case_ ) wikiaab_gpu_index_flat.add(snake_case_ ) # TODO fix for larger GPU else: _A , _A : List[str] = (None, None) _A : List[str] = Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=snake_case_ ) def lowerCAmelCase_ ( ): _A : Tuple = datasets.load_dataset("""eli5""",name="""LFQA_reddit""" ) _A : Optional[int] = elia["""train_eli5"""] _A : int = np.memmap( """eli5_questions_reps.dat""",dtype="""float32""",mode="""r""",shape=(elia_train.num_rows, 128) ) _A : int = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(snake_case_ ) return (elia_train, eli5_train_q_index) _snake_case , _snake_case , _snake_case = load_indexes() _snake_case , _snake_case , _snake_case , _snake_case = load_models() _snake_case , _snake_case = load_train_data() def lowerCAmelCase_ ( snake_case_,snake_case_=10 ): _A : Union[str, Any] = embed_questions_for_retrieval([question],snake_case_,snake_case_ ) _A , _A : Optional[Any] = eli5_train_q_index.search(snake_case_,snake_case_ ) _A : int = [elia_train[int(snake_case_ )] for i in I[0]] return nn_examples def lowerCAmelCase_ ( snake_case_,snake_case_="wiki40b",snake_case_="dense",snake_case_=10 ): if source == "none": _A , _A : List[str] = (""" <P> """.join(["""""" for _ in range(11 )] ).strip(), []) else: if method == "dense": _A , _A : int = query_qa_dense_index( snake_case_,snake_case_,snake_case_,snake_case_,snake_case_,snake_case_ ) else: _A , _A : Union[str, Any] = query_es_index( snake_case_,snake_case_,index_name="""english_wiki40b_snippets_100w""",n_results=snake_case_,) _A : Tuple = [ (res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst ] _A : Dict = """question: {} context: {}""".format(snake_case_,snake_case_ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda snake_case_ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda snake_case_ : None), } ) def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_,snake_case_=64,snake_case_=256,snake_case_=False,snake_case_=2,snake_case_=0.95,snake_case_=0.8 ): with torch.no_grad(): _A : Union[str, Any] = qa_sas_generate( snake_case_,snake_case_,snake_case_,num_answers=1,num_beams=snake_case_,min_len=snake_case_,max_len=snake_case_,do_sample=snake_case_,temp=snake_case_,top_p=snake_case_,top_k=snake_case_,max_input_length=1024,device="""cuda:0""",)[0] return (answer, support_list) st.title("Long Form Question Answering with ELI5") # Start sidebar _snake_case = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>" _snake_case = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia _snake_case = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n" st.sidebar.markdown(description, unsafe_allow_html=True) _snake_case = [ "Answer the question", "View the retrieved document only", "View the most similar ELI5 question and answer", "Show me everything, please!", ] _snake_case = st.sidebar.checkbox("Demo options") if demo_options: _snake_case = st.sidebar.selectbox( "", action_list, index=3, ) _snake_case = action_list.index(action_st) _snake_case = st.sidebar.selectbox( "", ["Show full text of passages", "Show passage section titles"], index=0, ) _snake_case = show_type == "Show full text of passages" else: _snake_case = 3 _snake_case = True _snake_case = st.sidebar.checkbox("Retrieval options") if retrieval_options: _snake_case = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n " st.sidebar.markdown(retriever_info) _snake_case = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"]) _snake_case = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"]) else: _snake_case = "wiki40b" _snake_case = "dense" _snake_case = "beam" _snake_case = 2 _snake_case = 64 _snake_case = 256 _snake_case = None _snake_case = None _snake_case = st.sidebar.checkbox("Generation options") if generate_options: _snake_case = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n " st.sidebar.markdown(generate_info) _snake_case = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"]) _snake_case = st.sidebar.slider( "Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None ) _snake_case = st.sidebar.slider( "Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": _snake_case = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: _snake_case = st.sidebar.slider( "Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.9_5, step=0.0_1, format=None, key=None ) _snake_case = st.sidebar.slider( "Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.0_1, format=None, key=None ) _snake_case = None # start main text _snake_case = [ "<MY QUESTION>", "How do people make chocolate?", "Why do we get a fever when we are sick?", "How can different animals perceive different colors?", "What is natural language processing?", "What's the best way to treat a sunburn?", "What exactly are vitamins ?", "How does nuclear energy provide electricity?", "What's the difference between viruses and bacteria?", "Why are flutes classified as woodwinds when most of them are made out of metal ?", "Why do people like drinking coffee even though it tastes so bad?", "What happens when wine ages? How does it make the wine taste better?", "If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?", "How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?", "How does New Zealand have so many large bird predators?", ] _snake_case = st.selectbox( "What would you like to ask? ---- select <MY QUESTION> to enter a new query", questions_list, index=1, ) if question_s == "<MY QUESTION>": _snake_case = st.text_input("Enter your question here:", "") else: _snake_case = question_s if st.button("Show me!"): if action in [0, 1, 3]: if index_type == "mixed": _snake_case , _snake_case = make_support(question, source=wiki_source, method="dense", n_results=10) _snake_case , _snake_case = make_support(question, source=wiki_source, method="sparse", n_results=10) _snake_case = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] _snake_case = support_list[:10] _snake_case = "<P> " + " <P> ".join([res[-1] for res in support_list]) else: _snake_case , _snake_case = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: _snake_case , _snake_case = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == "sampled"), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown("### The model generated answer is:") st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:") for i, res in enumerate(support_list): _snake_case = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_")) _snake_case = res[1].strip() if sec_titles == "": _snake_case = "[{}]({})".format(res[0], wiki_url) else: _snake_case = sec_titles.split(" & ") _snake_case = " & ".join( ["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list] ) st.markdown( "{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( "> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True ) if action in [2, 3]: _snake_case = find_nearest_training(question) _snake_case = nn_train_list[0] st.markdown( "--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"]) ) _snake_case = [ "{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""])) for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"])) if i == 0 or sc > 2 ] st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st))) _snake_case = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n" st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
26
'''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
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ): __a : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den __a : int = x_den * y_den * z_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase (_SCREAMING_SNAKE_CASE : int = 35 ): __a : set = set() __a : int __a : Fraction = Fraction(0 ) __a : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 __a : Union[str, Any] = x_num * y_den + x_den * y_num __a : Optional[Any] = x_den * y_den __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : Optional[int] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) __a : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : List[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Any = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Optional[int] = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[Any] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=-1 __a : int = x_num * y_num __a : Optional[Any] = x_den * y_num + x_num * y_den __a : Tuple = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : Any = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) # n=2 __a : List[Any] = x_num * x_num * y_num * y_num __a : List[Any] = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_SCREAMING_SNAKE_CASE ) and is_sq(_SCREAMING_SNAKE_CASE ): __a : Optional[Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : Union[str, Any] = int(sqrt(_SCREAMING_SNAKE_CASE ) ) __a : int = gcd(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: __a : List[str] = add_three( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) unique_s.add(_SCREAMING_SNAKE_CASE ) for num, den in unique_s: total += Fraction(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return total.denominator + total.numerator if __name__ == "__main__": print(f'''{solution() = }''')
27
'''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
0
'''simple docstring''' import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( _a , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = BloomTokenizerFast _SCREAMING_SNAKE_CASE = BloomTokenizerFast _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = """tokenizer_file""" _SCREAMING_SNAKE_CASE = {"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""} def A ( self : List[str] ): """simple docstring""" super().setUp() UpperCamelCase = BloomTokenizerFast.from_pretrained('bigscience/tokenizer' ) tokenizer.save_pretrained(self.tmpdirname ) def A ( self : List[str] , **UpperCamelCase__ : Union[str, Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ ) def A ( self : Dict ): """simple docstring""" UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = ['The quick brown fox</s>', 'jumps over the lazy dog</s>'] UpperCamelCase = [[2_1_7_5, 2_3_7_1_4, 7_3_1_7_3, 1_4_4_2_5_2, 2], [7_7, 1_3_2_6_1_9, 3_4_7_8, 3_6_8, 1_0_9_5_8_6, 3_5_4_3_3, 2]] UpperCamelCase = tokenizer.batch_encode_plus(UpperCamelCase__ )['input_ids'] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) UpperCamelCase = tokenizer.batch_decode(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) def A ( self : int , UpperCamelCase__ : Tuple=6 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCamelCase = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input UpperCamelCase = 'This is a simple input' UpperCamelCase = ['This is a simple input 1', 'This is a simple input 2'] UpperCamelCase = ('This is a simple input', 'This is a pair') UpperCamelCase = [ ('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 try: tokenizer_r.encode(UpperCamelCase__ , max_length=UpperCamelCase__ ) tokenizer_r.encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__ ) tokenizer_r.batch_encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__ ) tokenizer_r.encode(UpperCamelCase__ , max_length=UpperCamelCase__ ) tokenizer_r.batch_encode_plus(UpperCamelCase__ , max_length=UpperCamelCase__ ) except ValueError: self.fail('Bloom Tokenizer should be able to deal with padding' ) UpperCamelCase = None # Hotfixing padding = None self.assertRaises(UpperCamelCase__ , tokenizer_r.encode , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' ) # Simple input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' ) # Simple input self.assertRaises( UpperCamelCase__ , tokenizer_r.batch_encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' , ) # Pair input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' ) # Pair input self.assertRaises(UpperCamelCase__ , tokenizer_r.encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' ) # Pair input self.assertRaises( UpperCamelCase__ , tokenizer_r.batch_encode_plus , UpperCamelCase__ , max_length=UpperCamelCase__ , padding='max_length' , ) def A ( self : List[str] ): """simple docstring""" UpperCamelCase = self.get_rust_tokenizer() UpperCamelCase = load_dataset('xnli' , 'all_languages' , split='test' , streaming=UpperCamelCase__ ) UpperCamelCase = next(iter(UpperCamelCase__ ) )['premise'] # pick up one data UpperCamelCase = list(sample_data.values() ) UpperCamelCase = list(map(tokenizer.encode , UpperCamelCase__ ) ) UpperCamelCase = [tokenizer.decode(UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ ) for x in output_tokens] self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) def A ( self : List[Any] ): """simple docstring""" self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
28
'''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
0
from collections.abc import Sequence def lowercase__ ( __snake_case : Sequence[int] | None = None ): '''simple docstring''' if nums is None or not nums: raise ValueError('Input sequence should not be empty' ) UpperCAmelCase_ : Optional[int] = nums[0] for i in range(1 , len(__snake_case ) ): UpperCAmelCase_ : Dict = nums[i] UpperCAmelCase_ : Optional[Any] = max(__snake_case , ans + num , __snake_case ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user __UpperCAmelCase = int(input('Enter number of elements : ').strip()) __UpperCAmelCase = list(map(int, input('\nEnter the numbers : ').strip().split()))[:n] print(max_subsequence_sum(array))
29
'''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
0
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--txt2img_unclip', default='kakaobrain/karlo-v1-alpha', type=str, required=False, help='The pretrained txt2img unclip.', ) __a = parser.parse_args() __a = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) __a = CLIPImageProcessor() __a = CLIPVisionModelWithProjection.from_pretrained('openai/clip-vit-large-patch14') __a = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
30
'''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
0
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs __SCREAMING_SNAKE_CASE : Any = imread(R"""digital_image_processing/image_data/lena_small.jpg""") __SCREAMING_SNAKE_CASE : Tuple = cvtColor(img, COLOR_BGR2GRAY) def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : List[Any] = cn.convert_to_negative(_UpperCAmelCase ) # assert negative_img array for at least one True assert negative_img.any() def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" with Image.open("digital_image_processing/image_data/lena_small.jpg" ) as img: # Work around assertion for response assert str(cc.change_contrast(_UpperCAmelCase , 110 ) ).startswith( "<PIL.Image.Image image mode=RGB size=100x100 at" ) def UpperCamelCase_ ( ) -> Tuple: """simple docstring""" _UpperCAmelCase : int = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def UpperCamelCase_ ( ) -> Tuple: """simple docstring""" _UpperCAmelCase : str = imread("digital_image_processing/image_data/lena_small.jpg" , 0 ) # assert ambiguous array for all == True assert canny_img.all() _UpperCAmelCase : str = canny.canny(_UpperCAmelCase ) # assert canny array for at least one True assert canny_array.any() def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" assert gg.gaussian_filter(_UpperCAmelCase , 5 , sigma=0.9 ).all() def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : List[str] = array([[0.2_5, 0.5, 0.2_5], [0.5, -3, 0.5], [0.2_5, 0.5, 0.2_5]] ) _UpperCAmelCase : List[str] = conv.img_convolve(_UpperCAmelCase , _UpperCAmelCase ).astype(_UpperCAmelCase ) assert res.any() def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" assert med.median_filter(_UpperCAmelCase , 3 ).any() def UpperCamelCase_ ( ) -> List[str]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase : Any = sob.sobel_filter(_UpperCAmelCase ) assert grad.any() and theta.any() def UpperCamelCase_ ( ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase : Optional[Any] = sp.make_sepia(_UpperCAmelCase , 20 ) assert sepia.all() def UpperCamelCase_ ( _UpperCAmelCase : str = "digital_image_processing/image_data/lena_small.jpg" ) -> Tuple: """simple docstring""" _UpperCAmelCase : Tuple = bs.Burkes(imread(_UpperCAmelCase , 1 ) , 120 ) burkes.process() assert burkes.output_img.any() def UpperCamelCase_ ( _UpperCAmelCase : str = "digital_image_processing/image_data/lena_small.jpg" , ) -> List[str]: """simple docstring""" _UpperCAmelCase : Tuple = rs.NearestNeighbour(imread(_UpperCAmelCase , 1 ) , 400 , 200 ) nn.process() assert nn.output.any() def UpperCamelCase_ ( ) -> Tuple: """simple docstring""" _UpperCAmelCase : str = "digital_image_processing/image_data/lena.jpg" # Reading the image and converting it to grayscale. _UpperCAmelCase : Tuple = imread(_UpperCAmelCase , 0 ) # Test for get_neighbors_pixel function() return not None _UpperCAmelCase : Any = 0 _UpperCAmelCase : str = 0 _UpperCAmelCase : Tuple = image[x_coordinate][y_coordinate] _UpperCAmelCase : Dict = lbp.get_neighbors_pixel( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image _UpperCAmelCase : Dict = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): _UpperCAmelCase : List[str] = lbp.local_binary_value(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) assert lbp_image.any()
31
'''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
0
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : UNetaDModel snake_case__ : ScoreSdeVeScheduler def __init__( self : str , SCREAMING_SNAKE_CASE__ : UNetaDModel , SCREAMING_SNAKE_CASE__ : ScoreSdeVeScheduler ) -> Optional[int]: super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def __call__( self : str , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 2_0_0_0 , SCREAMING_SNAKE_CASE__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , SCREAMING_SNAKE_CASE__ : Optional[str] = "pil" , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[ImagePipelineOutput, Tuple]: a_ : Tuple = self.unet.config.sample_size a_ : Optional[Any] = (batch_size, 3, img_size, img_size) a_ : Optional[Any] = self.unet a_ : List[str] = randn_tensor(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) * self.scheduler.init_noise_sigma a_ : Tuple = sample.to(self.device ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) self.scheduler.set_sigmas(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): a_ : Dict = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): a_ : Tuple = self.unet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).sample a_ : Optional[Any] = self.scheduler.step_correct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample # prediction step a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).sample a_ : Tuple = self.scheduler.step_pred(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ) a_ , a_ : Union[str, Any] = output.prev_sample, output.prev_sample_mean a_ : Dict = sample_mean.clamp(0 , 1 ) a_ : Optional[Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a_ : List[Any] = self.numpy_to_pil(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE__ )
32
'''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
0
"""simple docstring""" import argparse import os import re import packaging.version __A : List[str] = '''examples/''' __A : int = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } __A : Dict = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } __A : Optional[int] = '''README.md''' def lowercase ( __snake_case : int , __snake_case : Any , __snake_case : int ): with open(__snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : int = f.read() lowercase_ , lowercase_ : List[str] = REPLACE_PATTERNS[pattern] lowercase_ : Union[str, Any] = replace.replace('''VERSION''' , __snake_case ) lowercase_ : Optional[Any] = re_pattern.sub(__snake_case , __snake_case ) with open(__snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(__snake_case ) def lowercase ( __snake_case : int ): for folder, directories, fnames in os.walk(__snake_case ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('''research_projects''' ) if "legacy" in directories: directories.remove('''legacy''' ) for fname in fnames: if fname.endswith('''.py''' ): update_version_in_file(os.path.join(__snake_case , __snake_case ) , __snake_case , pattern='''examples''' ) def lowercase ( __snake_case : Optional[Any] , __snake_case : Optional[Any]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(__snake_case , __snake_case , __snake_case ) if not patch: update_version_in_examples(__snake_case ) def lowercase ( ): lowercase_ : Union[str, Any] = '''🤗 Transformers currently provides the following architectures''' lowercase_ : Union[str, Any] = '''1. Want to contribute a new model?''' with open(__snake_case , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: lowercase_ : List[str] = f.readlines() # Find the start of the list. lowercase_ : Optional[Any] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 lowercase_ : str = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): lowercase_ : str = lines[index].replace( '''https://huggingface.co/docs/transformers/main/model_doc''' , '''https://huggingface.co/docs/transformers/model_doc''' , ) index += 1 with open(__snake_case , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(__snake_case ) def lowercase ( ): with open(REPLACE_FILES['''init'''] , '''r''' ) as f: lowercase_ : List[Any] = f.read() lowercase_ : List[str] = REPLACE_PATTERNS['''init'''][0].search(__snake_case ).groups()[0] return packaging.version.parse(__snake_case ) def lowercase ( __snake_case : Optional[Any]=False ): lowercase_ : str = get_version() if patch and default_version.is_devrelease: raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!''' ) if default_version.is_devrelease: lowercase_ : Optional[Any] = default_version.base_version elif patch: lowercase_ : Optional[int] = F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: lowercase_ : Optional[int] = F'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. lowercase_ : int = input(F'''Which version are you releasing? [{default_version}]''' ) if len(__snake_case ) == 0: lowercase_ : Dict = default_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case , patch=__snake_case ) if not patch: print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() def lowercase ( ): lowercase_ : List[Any] = get_version() lowercase_ : List[str] = F'''{current_version.major}.{current_version.minor + 1}.0.dev0''' lowercase_ : Any = current_version.base_version # Check with the user we got that right. lowercase_ : Tuple = input(F'''Which version are we developing now? [{dev_version}]''' ) if len(__snake_case ) == 0: lowercase_ : str = dev_version print(F'''Updating version to {version}.''' ) global_version_update(__snake_case ) print('''Cleaning main README, don\'t forget to run `make fix-copies`.''' ) clean_main_ref_in_model_list() if __name__ == "__main__": __A : int = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') __A : Any = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
33
'''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
0
'''simple docstring''' class _a : def __init__( self : int ): '''simple docstring''' UpperCAmelCase = {} def A ( self : Tuple ): '''simple docstring''' print(self.vertex ) for i in self.vertex: print(lowercase , ''' -> ''' , ''' -> '''.join([str(lowercase ) for j in self.vertex[i]] ) ) def A ( self : str , lowercase : int , lowercase : int ): '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(lowercase ) else: # else make a new vertex UpperCAmelCase = [to_vertex] def A ( self : List[str] ): '''simple docstring''' UpperCAmelCase = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowercase , lowercase ) def A ( self : Dict , lowercase : int , lowercase : list ): '''simple docstring''' UpperCAmelCase = True print(lowercase , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowercase , lowercase ) if __name__ == "__main__": A =Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
34
'''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
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_a ): """simple docstring""" lowercase = ["torch", "scipy"] def __init__( self : int , *snake_case_ : List[Any] , **snake_case_ : Optional[Any] ): requires_backends(self , ["""torch""", """scipy"""] ) @classmethod def lowerCamelCase ( cls : int , *snake_case_ : Any , **snake_case_ : List[Any] ): requires_backends(cls , ["""torch""", """scipy"""] ) @classmethod def lowerCamelCase ( cls : Optional[int] , *snake_case_ : List[Any] , **snake_case_ : str ): requires_backends(cls , ["""torch""", """scipy"""] )
35
'''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
0
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image _snake_case = ["text", "image", "audio"] def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : str = [] for input_type in input_types: if input_type == "text": inputs.append("Text input" ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" ).resize((512, 512) ) ) elif input_type == "audio": inputs.append(torch.ones(3_000 ) ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): inputs.append(create_inputs(_lowerCamelCase ) ) else: raise ValueError(F"Invalid type requested: {input_type}" ) return inputs def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = [] for output in outputs: if isinstance(_lowerCamelCase , (str, AgentText) ): output_types.append("text" ) elif isinstance(_lowerCamelCase , (Image.Image, AgentImage) ): output_types.append("image" ) elif isinstance(_lowerCamelCase , (torch.Tensor, AgentAudio) ): output_types.append("audio" ) else: raise ValueError(F"Invalid output: {output}" ) return output_types @is_tool_test class UpperCAmelCase_ : def snake_case__ ( self): '''simple docstring''' self.assertTrue(hasattr(self.tool, "inputs")) self.assertTrue(hasattr(self.tool, "outputs")) _lowerCAmelCase : List[Any] = self.tool.inputs for _input in inputs: if isinstance(_input, __a): for __input in _input: self.assertTrue(__input in authorized_types) else: self.assertTrue(_input in authorized_types) _lowerCAmelCase : str = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : List[Any] = create_inputs(self.tool.inputs) _lowerCAmelCase : Dict = self.tool(*__a) # There is a single output if len(self.tool.outputs) == 1: _lowerCAmelCase : Dict = [outputs] self.assertListEqual(output_types(__a), self.tool.outputs) def snake_case__ ( self): '''simple docstring''' self.assertTrue(hasattr(self.tool, "description")) self.assertTrue(hasattr(self.tool, "default_checkpoint")) self.assertTrue(self.tool.description.startswith("This is a tool that")) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Dict = create_inputs(self.tool.inputs) _lowerCAmelCase : Any = self.tool(*__a) if not isinstance(__a, __a): _lowerCAmelCase : str = [outputs] self.assertEqual(len(__a), len(self.tool.outputs)) for output, output_type in zip(__a, self.tool.outputs): _lowerCAmelCase : Any = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(__a, __a)) def snake_case__ ( self): '''simple docstring''' _lowerCAmelCase : Tuple = create_inputs(self.tool.inputs) _lowerCAmelCase : Tuple = [] for _input, input_type in zip(__a, self.tool.inputs): if isinstance(__a, __a): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type]) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input)) # Should not raise an error _lowerCAmelCase : Dict = self.tool(*__a) if not isinstance(__a, __a): _lowerCAmelCase : Any = [outputs] self.assertEqual(len(__a), len(self.tool.outputs))
36
'''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
0
'''simple docstring''' # Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar _lowerCAmelCase = TypeVar('''T''') class lowerCAmelCase_( Generic[T] ): '''simple docstring''' def __init__( self ,__UpperCAmelCase = True ) -> None: lowerCAmelCase__ : dict[T, list[T]] = {} # dictionary of lists lowerCAmelCase__ : Optional[int] = directed def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> GraphAdjacencyList[T]: if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(__UpperCAmelCase ) self.adj_list[destination_vertex].append(__UpperCAmelCase ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(__UpperCAmelCase ) lowerCAmelCase__ : List[str] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(__UpperCAmelCase ) lowerCAmelCase__ : str = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: lowerCAmelCase__ : List[Any] = [destination_vertex] lowerCAmelCase__ : str = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(__UpperCAmelCase ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(__UpperCAmelCase ) lowerCAmelCase__ : List[str] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: lowerCAmelCase__ : List[str] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: lowerCAmelCase__ : Dict = [destination_vertex] lowerCAmelCase__ : Optional[Any] = [] return self def __repr__( self ) -> str: return pformat(self.adj_list )
37
'''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
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : int ) -> Tuple: """simple docstring""" return params[f"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : Any="attention" ) -> str: """simple docstring""" UpperCamelCase :str = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) UpperCamelCase :Optional[Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase :Dict = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) UpperCamelCase :List[str] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase :List[str] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) UpperCamelCase :int = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase :Optional[Any] = np.ascontiguousarray(params[f"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) UpperCamelCase :int = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Any=False ) -> Tuple: """simple docstring""" if split_mlp_wi: UpperCamelCase :Optional[Any] = params[f"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] UpperCamelCase :List[str] = params[f"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] UpperCamelCase :Dict = (wi_a, wi_a) else: UpperCamelCase :Union[str, Any] = params[f"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] UpperCamelCase :Tuple = params[f"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" return params[f"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def SCREAMING_SNAKE_CASE_ ( __magic_name__ : dict , *, __magic_name__ : int , __magic_name__ : bool , __magic_name__ : bool = False ) -> Dict: """simple docstring""" UpperCamelCase :Dict = traverse_util.flatten_dict(variables["""target"""] ) UpperCamelCase :int = {"""/""".join(__magic_name__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :str = """encoder/encoder/mlp/wi_0/kernel""" in old print("""Split MLP:""" , __magic_name__ ) UpperCamelCase :Optional[int] = collections.OrderedDict() # Shared embeddings. UpperCamelCase :Dict = old["""token_embedder/embedding"""] # Encoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Optional[int] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = tax_attention_lookup(__magic_name__ , __magic_name__ , """encoder""" , """attention""" ) UpperCamelCase :Union[str, Any] = layer_norm UpperCamelCase :Tuple = k.T UpperCamelCase :Optional[Any] = o.T UpperCamelCase :Dict = q.T UpperCamelCase :List[str] = v.T # Block i, layer 1 (MLP). UpperCamelCase :Optional[Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """encoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Dict = tax_mlp_lookup(__magic_name__ , __magic_name__ , """encoder""" , __magic_name__ ) UpperCamelCase :List[Any] = layer_norm if split_mlp_wi: UpperCamelCase :Any = wi[0].T UpperCamelCase :Optional[Any] = wi[1].T else: UpperCamelCase :Optional[int] = wi.T UpperCamelCase :Any = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Optional[Any] = tax_relpos_bias_lookup( __magic_name__ , __magic_name__ , """encoder""" ).T UpperCamelCase :Tuple = old["""encoder/encoder_norm/scale"""] if not scalable_attention: UpperCamelCase :Dict = tax_relpos_bias_lookup( __magic_name__ , 0 , """encoder""" ).T UpperCamelCase :Tuple = tax_relpos_bias_lookup( __magic_name__ , 0 , """decoder""" ).T if not is_encoder_only: # Decoder. for i in range(__magic_name__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Dict = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_self_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """self_attention""" ) UpperCamelCase :int = layer_norm UpperCamelCase :Optional[Any] = k.T UpperCamelCase :Tuple = o.T UpperCamelCase :Optional[Any] = q.T UpperCamelCase :int = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :str = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_cross_attention_layer_norm""" ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = tax_attention_lookup(__magic_name__ , __magic_name__ , """decoder""" , """encoder_decoder_attention""" ) UpperCamelCase :str = layer_norm UpperCamelCase :List[str] = k.T UpperCamelCase :Optional[int] = o.T UpperCamelCase :Union[str, Any] = q.T UpperCamelCase :Tuple = v.T # Block i, layer 2 (MLP). UpperCamelCase :Optional[Any] = tax_layer_norm_lookup(__magic_name__ , __magic_name__ , """decoder""" , """pre_mlp_layer_norm""" ) UpperCamelCase , UpperCamelCase :Optional[int] = tax_mlp_lookup(__magic_name__ , __magic_name__ , """decoder""" , __magic_name__ ) UpperCamelCase :str = layer_norm if split_mlp_wi: UpperCamelCase :Any = wi[0].T UpperCamelCase :int = wi[1].T else: UpperCamelCase :List[str] = wi.T UpperCamelCase :Union[str, Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Union[str, Any] = tax_relpos_bias_lookup(__magic_name__ , __magic_name__ , """decoder""" ).T UpperCamelCase :int = old["""decoder/decoder_norm/scale"""] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Optional[Any] = old["""decoder/logits_dense/kernel"""].T return new def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Optional[int] , __magic_name__ : bool ) -> List[Any]: """simple docstring""" UpperCamelCase :Union[str, Any] = 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: UpperCamelCase :int = state_dict["""shared.weight"""] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :List[str] = 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.""" ) UpperCamelCase :Optional[Any] = state_dict["""shared.weight"""] return state_dict def SCREAMING_SNAKE_CASE_ ( __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : List[str] ) -> int: """simple docstring""" UpperCamelCase :Any = checkpoints.load_tax_checkpoint(__magic_name__ ) UpperCamelCase :int = convert_tax_to_pytorch( __magic_name__ , num_layers=config.num_layers , is_encoder_only=__magic_name__ , scalable_attention=__magic_name__ ) UpperCamelCase :Any = make_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ , strict=__magic_name__ ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : bool = False , __magic_name__ : bool = False , ) -> Dict: """simple docstring""" UpperCamelCase :Optional[Any] = MTaConfig.from_json_file(__magic_name__ ) 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: UpperCamelCase :List[str] = UMTaEncoderModel(__magic_name__ ) else: UpperCamelCase :List[Any] = UMTaForConditionalGeneration(__magic_name__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__magic_name__ ) # Verify that we can load the checkpoint. model.from_pretrained(__magic_name__ ) print("""Done""" ) if __name__ == "__main__": UpperCAmelCase_ : str = 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 ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) UpperCAmelCase_ : Tuple = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
38
'''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
0
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class __lowerCamelCase ( unittest.TestCase): """simple docstring""" def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'hf-internal-testing/tiny-random-t5' _UpperCAmelCase = AutoTokenizer.from_pretrained(UpperCAmelCase ) _UpperCAmelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase ) _UpperCAmelCase = tokenizer('This is me' , return_tensors='pt' ) _UpperCAmelCase = model.to_bettertransformer() self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) _UpperCAmelCase = model.generate(**UpperCAmelCase ) _UpperCAmelCase = model.reverse_bettertransformer() self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase ) _UpperCAmelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase ) self.assertFalse( any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) _UpperCAmelCase = model_reloaded.generate(**UpperCAmelCase ) self.assertTrue(torch.allclose(UpperCAmelCase , UpperCAmelCase ) ) def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 'hf-internal-testing/tiny-random-t5' _UpperCAmelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase ) _UpperCAmelCase = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(UpperCAmelCase ): model.save_pretrained(UpperCAmelCase ) _UpperCAmelCase = model.reverse_bettertransformer() model.save_pretrained(UpperCAmelCase )
39
'''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
0
"""simple docstring""" import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArguments, set_seed, ) def lowercase ( )-> List[Any]: '''simple docstring''' a : Any = argparse.ArgumentParser() parser.add_argument("--model_ckpt" , type=A_ , default="microsoft/unixcoder-base-nine" ) parser.add_argument("--num_epochs" , type=A_ , default=5 ) parser.add_argument("--batch_size" , type=A_ , default=6 ) parser.add_argument("--gradient_accumulation_steps" , type=A_ , default=1 ) parser.add_argument("--freeze" , type=A_ , default=A_ ) parser.add_argument("--learning_rate" , type=A_ , default=5e-4 ) parser.add_argument("--seed" , type=A_ , default=0 ) parser.add_argument("--lr_scheduler_type" , type=A_ , default="cosine" ) parser.add_argument("--num_warmup_steps" , type=A_ , default=10 ) parser.add_argument("--weight_decay" , type=A_ , default=0.0_1 ) parser.add_argument("--output_dir" , type=A_ , default="./results" ) return parser.parse_args() __lowercase = load("""accuracy""") def lowercase ( A_ )-> Tuple: '''simple docstring''' a , a : List[str] = eval_pred a : str = np.argmax(A_ , axis=1 ) return metric.compute(predictions=A_ , references=A_ ) class _A ( _a ): """simple docstring""" def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]): super().__init__() a : int = trainer def __snake_case ( self : Optional[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] , **__UpperCAmelCase : List[Any]): if control.should_evaluate: a : Union[str, Any] = deepcopy(__UpperCAmelCase) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix="train") return control_copy def lowercase ( )-> Union[str, Any]: '''simple docstring''' a : List[str] = get_args() set_seed(args.seed ) a : int = load_dataset("codeparrot/codecomplex" , split="train" ) a : Dict = dataset.train_test_split(test_size=0.2 ) a : int = train_test["test"].train_test_split(test_size=0.5 ) a : Union[str, Any] = DatasetDict( { "train": train_test["train"], "test": test_validation["train"], "valid": test_validation["test"], } ) print("Loading tokenizer and model" ) a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : Optional[int] = tokenizer.eos_token a : Any = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt , num_labels=7 ) a : Any = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): a : Optional[Any] = False a : Union[str, Any] = ClassLabel(num_classes=7 , names=list(set(train_test_validation["train"]["complexity"] ) ) ) def tokenize(A_ ): a : List[str] = tokenizer(example["src"] , truncation=A_ , max_length=1_024 ) a : Optional[int] = labels.straint(example["complexity"] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } a : Optional[Any] = train_test_validation.map( A_ , batched=A_ , remove_columns=train_test_validation["train"].column_names , ) a : Dict = DataCollatorWithPadding(tokenizer=A_ ) a : Optional[Any] = TrainingArguments( output_dir=args.output_dir , learning_rate=args.learning_rate , lr_scheduler_type=args.lr_scheduler_type , evaluation_strategy="epoch" , save_strategy="epoch" , logging_strategy="epoch" , per_device_train_batch_size=args.batch_size , per_device_eval_batch_size=args.batch_size , num_train_epochs=args.num_epochs , gradient_accumulation_steps=args.gradient_accumulation_steps , weight_decay=0.0_1 , metric_for_best_model="accuracy" , run_name="complexity-java" , report_to="wandb" , ) a : Union[str, Any] = Trainer( model=A_ , args=A_ , train_dataset=tokenized_datasets["train"] , eval_dataset=tokenized_datasets["valid"] , tokenizer=A_ , data_collator=A_ , compute_metrics=A_ , ) print("Training..." ) trainer.add_callback(CustomCallback(A_ ) ) trainer.train() if __name__ == "__main__": main()
40
'''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
0