code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup lowerCAmelCase_ = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def lowerCamelCase_ ( _UpperCamelCase = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" snake_case_ : Tuple = BeautifulSoup(requests.get(url + location ).content , '''html.parser''' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('''div''' , attrs={'''data-tn-component''': '''organicJob'''} ): snake_case_ : Tuple = job.find('''a''' , attrs={'''data-tn-element''': '''jobTitle'''} ).text.strip() snake_case_ : int = job.find('''span''' , {'''class''': '''company'''} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(F'''Job {i:>2} is {job[0]} at {job[1]}''')
60
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __snake_case = 10 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if array[i] == target: return i return -1 def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Tuple = 0 UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1 UpperCamelCase :str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase :int = one_third - 1 elif array[two_third] < target: UpperCamelCase :Any = two_third + 1 else: UpperCamelCase :Any = one_third + 1 UpperCamelCase :int = two_third - 1 else: return -1 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = (left + right) // 3 + 1 UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __snake_case = input("""Enter numbers separated by comma:\n""").strip() __snake_case = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __snake_case = int(input("""Enter the number to be found in the list:\n""").strip()) __snake_case = ite_ternary_search(collection, target) __snake_case = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
658
0
from io import BytesIO from typing import List, Union import requests from ..utils import add_end_docstrings, is_decord_available, is_torch_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_decord_available(): import numpy as np from decord import VideoReader if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING UpperCamelCase = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Any ) -> List[Any]: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , "decord" ) self.check_model_type(SCREAMING_SNAKE_CASE__ ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Any: lowerCAmelCase__ = {} if frame_sampling_rate is not None: lowerCAmelCase__ = frame_sampling_rate if num_frames is not None: lowerCAmelCase__ = num_frames lowerCAmelCase__ = {} if top_k is not None: lowerCAmelCase__ = top_k return preprocess_params, {}, postprocess_params def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, List[str]] , **SCREAMING_SNAKE_CASE__ : Any ) -> Optional[int]: return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1 ) -> Optional[Any]: if num_frames is None: lowerCAmelCase__ = self.model.config.num_frames if video.startswith("http://" ) or video.startswith("https://" ): lowerCAmelCase__ = BytesIO(requests.get(SCREAMING_SNAKE_CASE__ ).content ) lowerCAmelCase__ = VideoReader(SCREAMING_SNAKE_CASE__ ) videoreader.seek(0 ) lowerCAmelCase__ = 0 lowerCAmelCase__ = num_frames * frame_sampling_rate - 1 lowerCAmelCase__ = np.linspace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num=SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) lowerCAmelCase__ = videoreader.get_batch(SCREAMING_SNAKE_CASE__ ).asnumpy() lowerCAmelCase__ = list(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) return model_inputs def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: lowerCAmelCase__ = self.model(**SCREAMING_SNAKE_CASE__ ) return model_outputs def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]=5 ) -> Any: if top_k > self.model.config.num_labels: lowerCAmelCase__ = self.model.config.num_labels if self.framework == "pt": lowerCAmelCase__ = model_outputs.logits.softmax(-1 )[0] lowerCAmelCase__ , lowerCAmelCase__ = probs.topk(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f'Unsupported framework: {self.framework}' ) lowerCAmelCase__ = scores.tolist() lowerCAmelCase__ = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )]
61
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 UpperCamelCase :Union[str, Any] = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Dict = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :str = max_revenue return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )] UpperCamelCase :Dict = 0 for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Tuple = max_revenue_i return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): if n < 0: UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :str = 36 UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
658
0
import argparse import struct import unittest class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : int , UpperCAmelCase_ : bytes ): SCREAMING_SNAKE_CASE : Dict = data # Initialize hash values SCREAMING_SNAKE_CASE : List[str] = [ 0X6A_09_E6_67, 0XBB_67_AE_85, 0X3C_6E_F3_72, 0XA5_4F_F5_3A, 0X51_0E_52_7F, 0X9B_05_68_8C, 0X1F_83_D9_AB, 0X5B_E0_CD_19, ] # Initialize round constants SCREAMING_SNAKE_CASE : List[str] = [ 0X42_8A_2F_98, 0X71_37_44_91, 0XB5_C0_FB_CF, 0XE9_B5_DB_A5, 0X39_56_C2_5B, 0X59_F1_11_F1, 0X92_3F_82_A4, 0XAB_1C_5E_D5, 0XD8_07_AA_98, 0X12_83_5B_01, 0X24_31_85_BE, 0X55_0C_7D_C3, 0X72_BE_5D_74, 0X80_DE_B1_FE, 0X9B_DC_06_A7, 0XC1_9B_F1_74, 0XE4_9B_69_C1, 0XEF_BE_47_86, 0X0F_C1_9D_C6, 0X24_0C_A1_CC, 0X2D_E9_2C_6F, 0X4A_74_84_AA, 0X5C_B0_A9_DC, 0X76_F9_88_DA, 0X98_3E_51_52, 0XA8_31_C6_6D, 0XB0_03_27_C8, 0XBF_59_7F_C7, 0XC6_E0_0B_F3, 0XD5_A7_91_47, 0X06_CA_63_51, 0X14_29_29_67, 0X27_B7_0A_85, 0X2E_1B_21_38, 0X4D_2C_6D_FC, 0X53_38_0D_13, 0X65_0A_73_54, 0X76_6A_0A_BB, 0X81_C2_C9_2E, 0X92_72_2C_85, 0XA2_BF_E8_A1, 0XA8_1A_66_4B, 0XC2_4B_8B_70, 0XC7_6C_51_A3, 0XD1_92_E8_19, 0XD6_99_06_24, 0XF4_0E_35_85, 0X10_6A_A0_70, 0X19_A4_C1_16, 0X1E_37_6C_08, 0X27_48_77_4C, 0X34_B0_BC_B5, 0X39_1C_0C_B3, 0X4E_D8_AA_4A, 0X5B_9C_CA_4F, 0X68_2E_6F_F3, 0X74_8F_82_EE, 0X78_A5_63_6F, 0X84_C8_78_14, 0X8C_C7_02_08, 0X90_BE_FF_FA, 0XA4_50_6C_EB, 0XBE_F9_A3_F7, 0XC6_71_78_F2, ] SCREAMING_SNAKE_CASE : Tuple = self.preprocessing(self.data ) self.final_hash() @staticmethod def _A ( UpperCAmelCase_ : bytes ): SCREAMING_SNAKE_CASE : Optional[int] = b"\x80" + (b"\x00" * (63 - (len(UpperCAmelCase_ ) + 8) % 64)) SCREAMING_SNAKE_CASE : List[Any] = struct.pack(">Q" , (len(UpperCAmelCase_ ) * 8) ) return data + padding + big_endian_integer def _A ( self : Optional[Any] ): # Convert into blocks of 64 bytes SCREAMING_SNAKE_CASE : int = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers SCREAMING_SNAKE_CASE : Union[str, Any] = list(struct.unpack(">16L" , UpperCAmelCase_ ) ) # add 48 0-ed integers words += [0] * 48 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array SCREAMING_SNAKE_CASE : Optional[int] = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) SCREAMING_SNAKE_CASE : int = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) SCREAMING_SNAKE_CASE : List[str] = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_00_00_00_00 # Compression SCREAMING_SNAKE_CASE : Any = self.ror(UpperCAmelCase_ , 6 ) ^ self.ror(UpperCAmelCase_ , 11 ) ^ self.ror(UpperCAmelCase_ , 25 ) SCREAMING_SNAKE_CASE : Any = (e & f) ^ ((~e & 0XFF_FF_FF_FF) & g) SCREAMING_SNAKE_CASE : Dict = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_00_00_00_00 SCREAMING_SNAKE_CASE : List[Any] = self.ror(UpperCAmelCase_ , 2 ) ^ self.ror(UpperCAmelCase_ , 13 ) ^ self.ror(UpperCAmelCase_ , 22 ) SCREAMING_SNAKE_CASE : Optional[Any] = (a & b) ^ (a & c) ^ (b & c) SCREAMING_SNAKE_CASE : Optional[int] = (sa + maj) % 0X1_00_00_00_00 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = ( g, f, e, ((d + tempa) % 0X1_00_00_00_00), c, b, a, ((tempa + tempa) % 0X1_00_00_00_00), ) SCREAMING_SNAKE_CASE : List[str] = [a, b, c, d, e, f, g, h] # Modify final values SCREAMING_SNAKE_CASE : Union[str, Any] = [ ((element + mutated_hash_values[index]) % 0X1_00_00_00_00) for index, element in enumerate(self.hashes ) ] SCREAMING_SNAKE_CASE : Any = "".join([hex(UpperCAmelCase_ )[2:].zfill(8 ) for value in self.hashes] ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int ): return 0XFF_FF_FF_FF & (value << (32 - rotations)) | (value >> rotations) class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): import hashlib SCREAMING_SNAKE_CASE : int = bytes("Test String" , "utf-8" ) self.assertEqual(SHAaaa(UpperCAmelCase_ ).hash , hashlib.shaaaa(UpperCAmelCase_ ).hexdigest() ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() SCREAMING_SNAKE_CASE : int = argparse.ArgumentParser() parser.add_argument( "-s" , "--string" , dest="input_string" , default="Hello World!! Welcome to Cryptography" , help="Hash the string" , ) parser.add_argument( "-f" , "--file" , dest="input_file" , help="Hash contents of a file" ) SCREAMING_SNAKE_CASE : Tuple = parser.parse_args() SCREAMING_SNAKE_CASE : str = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , "rb" ) as f: SCREAMING_SNAKE_CASE : int = f.read() else: SCREAMING_SNAKE_CASE : Optional[Any] = bytes(lowercase , "utf-8" ) print(SHAaaa(lowercase ).hash ) if __name__ == "__main__": main()
62
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase, lowercase ): """simple docstring""" UpperCamelCase_ : int ='focalnet' def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = image_size UpperCamelCase :Dict = patch_size UpperCamelCase :Tuple = num_channels UpperCamelCase :int = embed_dim UpperCamelCase :Optional[Any] = use_conv_embed UpperCamelCase :str = hidden_sizes UpperCamelCase :str = depths UpperCamelCase :Optional[int] = focal_levels UpperCamelCase :Tuple = focal_windows UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Optional[int] = mlp_ratio UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :int = drop_path_rate UpperCamelCase :Dict = use_layerscale UpperCamelCase :List[str] = layerscale_value UpperCamelCase :Tuple = use_post_layernorm UpperCamelCase :int = use_post_layernorm_in_modulation UpperCamelCase :str = normalize_modulator UpperCamelCase :Any = initializer_range UpperCamelCase :Optional[Any] = layer_norm_eps UpperCamelCase :Dict = encoder_stride UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
658
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer a : List[str] = logging.get_logger(__name__) a : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} a : Any = { "vocab_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json" ), }, } a : List[str] = { "yjernite/retribert-base-uncased": 512, } a : int = { "yjernite/retribert-base-uncased": {"do_lower_case": True}, } class a ( lowercase__ ): """simple docstring""" a : int = VOCAB_FILES_NAMES a : List[str] = PRETRAINED_VOCAB_FILES_MAP a : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[Any] = PRETRAINED_INIT_CONFIGURATION a : Dict = RetriBertTokenizer a : Any = ['input_ids', 'attention_mask'] def __init__( self : Dict , __lowercase : Optional[Any]=None , __lowercase : Any=None , __lowercase : Optional[int]=True , __lowercase : Tuple="[UNK]" , __lowercase : List[str]="[SEP]" , __lowercase : Any="[PAD]" , __lowercase : str="[CLS]" , __lowercase : List[Any]="[MASK]" , __lowercase : Tuple=True , __lowercase : Optional[Any]=None , **__lowercase : List[str] , ) -> Optional[int]: super().__init__( __lowercase , tokenizer_file=__lowercase , do_lower_case=__lowercase , unk_token=__lowercase , sep_token=__lowercase , pad_token=__lowercase , cls_token=__lowercase , mask_token=__lowercase , tokenize_chinese_chars=__lowercase , strip_accents=__lowercase , **__lowercase , ) __UpperCAmelCase : List[str] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __lowercase ) != do_lower_case or normalizer_state.get("""strip_accents""" , __lowercase ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __lowercase ) != tokenize_chinese_chars ): __UpperCAmelCase : List[str] = getattr(__lowercase , normalizer_state.pop("""type""" ) ) __UpperCAmelCase : str = do_lower_case __UpperCAmelCase : Optional[int] = strip_accents __UpperCAmelCase : Optional[int] = tokenize_chinese_chars __UpperCAmelCase : List[str] = normalizer_class(**__lowercase ) __UpperCAmelCase : str = do_lower_case def UpperCAmelCase ( self : Union[str, Any] , __lowercase : Any , __lowercase : Optional[int]=None ) -> Union[str, Any]: __UpperCAmelCase : str = [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 : int , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: __UpperCAmelCase : str = [self.sep_token_id] __UpperCAmelCase : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase ( self : List[Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: __UpperCAmelCase : Any = self._tokenizer.model.save(__lowercase , name=__lowercase ) return tuple(__lowercase )
63
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :Union[str, Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Any = patch_size UpperCamelCase :List[str] = num_channels UpperCamelCase :int = is_training UpperCamelCase :str = use_labels UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = backbone_out_indices UpperCamelCase :str = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :int = backbone_featmap_shape UpperCamelCase :Any = scope UpperCamelCase :int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Dict = (image_size // patch_size) ** 2 UpperCamelCase :List[str] = num_patches + 1 def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Tuple =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Tuple =False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Union[str, Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Any = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = False UpperCamelCase :List[Any] = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Any: pass @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = prepare_img() UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :int = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
import logging import os import sys from dataclasses import dataclass, field from itertools import chain from typing import Optional, Union import datasets import numpy as np import torch from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer_utils import get_last_checkpoint from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') lowercase_ : Tuple = logging.getLogger(__name__) @dataclass class _lowerCamelCase : __a = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) __a = field( default=UpperCamelCase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __a = field( default=UpperCamelCase_ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) __a = field( default=UpperCamelCase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) __a = field( default=UpperCamelCase_ , metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} , ) __a = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __a = field( default=UpperCamelCase_ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) @dataclass class _lowerCamelCase : __a = field(default=UpperCamelCase_ , metadata={"help": "The input training data file (a text file)."} ) __a = field( default=UpperCamelCase_ , metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."} , ) __a = field( default=UpperCamelCase_ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) __a = field( default=UpperCamelCase_ , metadata={"help": "The number of processes to use for the preprocessing."} , ) __a = field( default=UpperCamelCase_ , metadata={ "help": ( "The maximum total input sequence length after tokenization. If passed, sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) __a = field( default=UpperCamelCase_ , metadata={ "help": ( "Whether to pad all samples to the maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) } , ) __a = field( default=UpperCamelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __a = field( default=UpperCamelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def UpperCamelCase_ ( self ) -> List[Any]: if self.train_file is not None: SCREAMING_SNAKE_CASE__: Union[str, Any]= self.train_file.split('''.''' )[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: SCREAMING_SNAKE_CASE__: Union[str, Any]= self.validation_file.split('''.''' )[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file." @dataclass class _lowerCamelCase : __a = 42 __a = True __a = None __a = None def __call__( self , lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__: Tuple= '''label''' if '''label''' in features[0].keys() else '''labels''' SCREAMING_SNAKE_CASE__: Optional[Any]= [feature.pop(lowerCAmelCase ) for feature in features] SCREAMING_SNAKE_CASE__: Dict= len(lowerCAmelCase ) SCREAMING_SNAKE_CASE__: int= len(features[0]['''input_ids'''] ) SCREAMING_SNAKE_CASE__: Union[str, Any]= [ [{k: v[i] for k, v in feature.items()} for i in range(lowerCAmelCase )] for feature in features ] SCREAMING_SNAKE_CASE__: List[Any]= list(chain(*lowerCAmelCase ) ) SCREAMING_SNAKE_CASE__: Any= self.tokenizer.pad( lowerCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' , ) # Un-flatten SCREAMING_SNAKE_CASE__: Union[str, Any]= {k: v.view(lowerCAmelCase , lowerCAmelCase , -1 ) for k, v in batch.items()} # Add back labels SCREAMING_SNAKE_CASE__: List[str]= torch.tensor(lowerCAmelCase , dtype=torch.intaa ) return batch def A__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. SCREAMING_SNAKE_CASE__: Any= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: str= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Optional[Any]= parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_swag''' , snake_case_ , snake_case_ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() SCREAMING_SNAKE_CASE__: Optional[Any]= training_args.get_process_log_level() logger.setLevel(snake_case_ ) datasets.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.set_verbosity(snake_case_ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. SCREAMING_SNAKE_CASE__: Union[str, Any]= None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: SCREAMING_SNAKE_CASE__: List[str]= get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.train_file is not None or data_args.validation_file is not None: SCREAMING_SNAKE_CASE__: Union[str, Any]= {} if data_args.train_file is not None: SCREAMING_SNAKE_CASE__: List[Any]= data_args.train_file if data_args.validation_file is not None: SCREAMING_SNAKE_CASE__: Dict= data_args.validation_file SCREAMING_SNAKE_CASE__: Tuple= data_args.train_file.split('''.''' )[-1] SCREAMING_SNAKE_CASE__: int= load_dataset( snake_case_ , data_files=snake_case_ , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: # Downloading and loading the swag dataset from the hub. SCREAMING_SNAKE_CASE__: Optional[Any]= load_dataset( '''swag''' , '''regular''' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. SCREAMING_SNAKE_CASE__: str= AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__: List[str]= AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) SCREAMING_SNAKE_CASE__: List[str]= AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=snake_case_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # When using your own dataset or a different dataset from swag, you will probably need to change this. SCREAMING_SNAKE_CASE__: Tuple= [F'ending{i}' for i in range(4 )] SCREAMING_SNAKE_CASE__: List[str]= '''sent1''' SCREAMING_SNAKE_CASE__: str= '''sent2''' if data_args.max_seq_length is None: SCREAMING_SNAKE_CASE__: str= tokenizer.model_max_length if max_seq_length > 1_024: logger.warning( '''The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value''' ''' of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can''' ''' override this default with `--block_size xxx`.''' ) SCREAMING_SNAKE_CASE__: List[str]= 1_024 else: if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( F'The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the' F'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) SCREAMING_SNAKE_CASE__: Any= min(data_args.max_seq_length , tokenizer.model_max_length ) # Preprocessing the datasets. def preprocess_function(snake_case_ : int ): SCREAMING_SNAKE_CASE__: Any= [[context] * 4 for context in examples[context_name]] SCREAMING_SNAKE_CASE__: List[Any]= examples[question_header_name] SCREAMING_SNAKE_CASE__: Union[str, Any]= [ [F'{header} {examples[end][i]}' for end in ending_names] for i, header in enumerate(snake_case_ ) ] # Flatten out SCREAMING_SNAKE_CASE__: Dict= list(chain(*snake_case_ ) ) SCREAMING_SNAKE_CASE__: Union[str, Any]= list(chain(*snake_case_ ) ) # Tokenize SCREAMING_SNAKE_CASE__: Tuple= tokenizer( snake_case_ , snake_case_ , truncation=snake_case_ , max_length=snake_case_ , padding='''max_length''' if data_args.pad_to_max_length else False , ) # Un-flatten return {k: [v[i : i + 4] for i in range(0 , len(snake_case_ ) , 4 )] for k, v in tokenized_examples.items()} if training_args.do_train: if "train" not in raw_datasets: raise ValueError('''--do_train requires a train dataset''' ) SCREAMING_SNAKE_CASE__: Optional[int]= raw_datasets['''train'''] if data_args.max_train_samples is not None: SCREAMING_SNAKE_CASE__: Optional[int]= min(len(snake_case_ ) , data_args.max_train_samples ) SCREAMING_SNAKE_CASE__: int= train_dataset.select(range(snake_case_ ) ) with training_args.main_process_first(desc='''train dataset map pre-processing''' ): SCREAMING_SNAKE_CASE__: Any= train_dataset.map( snake_case_ , batched=snake_case_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) if training_args.do_eval: if "validation" not in raw_datasets: raise ValueError('''--do_eval requires a validation dataset''' ) SCREAMING_SNAKE_CASE__: List[str]= raw_datasets['''validation'''] if data_args.max_eval_samples is not None: SCREAMING_SNAKE_CASE__: int= min(len(snake_case_ ) , data_args.max_eval_samples ) SCREAMING_SNAKE_CASE__: Optional[Any]= eval_dataset.select(range(snake_case_ ) ) with training_args.main_process_first(desc='''validation dataset map pre-processing''' ): SCREAMING_SNAKE_CASE__: Dict= eval_dataset.map( snake_case_ , batched=snake_case_ , num_proc=data_args.preprocessing_num_workers , load_from_cache_file=not data_args.overwrite_cache , ) # Data collator SCREAMING_SNAKE_CASE__: str= ( default_data_collator if data_args.pad_to_max_length else DataCollatorForMultipleChoice(tokenizer=snake_case_ , pad_to_multiple_of=8 if training_args.fpaa else None ) ) # Metric def compute_metrics(snake_case_ : Optional[Any] ): SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Tuple= eval_predictions SCREAMING_SNAKE_CASE__: Union[str, Any]= np.argmax(snake_case_ , axis=1 ) return {"accuracy": (preds == label_ids).astype(np.floataa ).mean().item()} # Initialize our Trainer SCREAMING_SNAKE_CASE__: str= Trainer( model=snake_case_ , args=snake_case_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=snake_case_ , data_collator=snake_case_ , compute_metrics=snake_case_ , ) # Training if training_args.do_train: SCREAMING_SNAKE_CASE__: Tuple= None if training_args.resume_from_checkpoint is not None: SCREAMING_SNAKE_CASE__: List[Any]= training_args.resume_from_checkpoint elif last_checkpoint is not None: SCREAMING_SNAKE_CASE__: Optional[int]= last_checkpoint SCREAMING_SNAKE_CASE__: int= trainer.train(resume_from_checkpoint=snake_case_ ) trainer.save_model() # Saves the tokenizer too for easy upload SCREAMING_SNAKE_CASE__: Optional[Any]= train_result.metrics SCREAMING_SNAKE_CASE__: Dict= ( data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case_ ) ) SCREAMING_SNAKE_CASE__: Any= min(snake_case_ , len(snake_case_ ) ) trainer.log_metrics('''train''' , snake_case_ ) trainer.save_metrics('''train''' , snake_case_ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) SCREAMING_SNAKE_CASE__: List[Any]= trainer.evaluate() SCREAMING_SNAKE_CASE__: str= data_args.max_eval_samples if data_args.max_eval_samples is not None else len(snake_case_ ) SCREAMING_SNAKE_CASE__: str= min(snake_case_ , len(snake_case_ ) ) trainer.log_metrics('''eval''' , snake_case_ ) trainer.save_metrics('''eval''' , snake_case_ ) SCREAMING_SNAKE_CASE__: List[Any]= { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''multiple-choice''', '''dataset_tags''': '''swag''', '''dataset_args''': '''regular''', '''dataset''': '''SWAG''', '''language''': '''en''', } if training_args.push_to_hub: trainer.push_to_hub(**snake_case_ ) else: trainer.create_model_card(**snake_case_ ) def A__ ( snake_case_ : List[str] ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
64
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Union[str, Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: UpperCamelCase :Any = 128 elif "12-12" in model_name: UpperCamelCase :Union[str, Any] = 12 UpperCamelCase :Any = 12 elif "14-14" in model_name: UpperCamelCase :Optional[int] = 14 UpperCamelCase :List[str] = 14 elif "16-16" in model_name: UpperCamelCase :List[Any] = 16 UpperCamelCase :Optional[Any] = 16 else: raise ValueError('''Model not supported''' ) UpperCamelCase :Tuple = '''huggingface/label-files''' if "speech-commands" in model_name: UpperCamelCase :Optional[Any] = 35 UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json''' else: UpperCamelCase :Optional[int] = 527 UpperCamelCase :List[Any] = '''audioset-id2label.json''' UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): if "module.v" in name: UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ): for key in orig_state_dict.copy().keys(): UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: UpperCamelCase :Any = key.split('''.''' ) UpperCamelCase :str = int(key_split[3] ) UpperCamelCase :Union[str, Any] = config.hidden_size if "weight" in key: UpperCamelCase :List[str] = val[:dim, :] UpperCamelCase :Optional[Any] = val[dim : dim * 2, :] UpperCamelCase :Optional[Any] = val[-dim:, :] else: UpperCamelCase :Dict = val[:dim] UpperCamelCase :Optional[int] = val[dim : dim * 2] UpperCamelCase :List[Any] = val[-dim:] else: UpperCamelCase :Union[str, Any] = val return orig_state_dict def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[str] = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ): UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict UpperCamelCase :Optional[int] = model_name_to_url[model_name] UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE__ ) # rename some keys UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load 🤗 model UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78 UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26 UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128 UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) if "speech-commands" in model_name: UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array'''] else: UpperCamelCase :List[Any] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = waveform.squeeze().numpy() UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' ) # forward pass UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] ) elif model_name == "ast-finetuned-speech-commands-v2": UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
658
0
"""simple docstring""" import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class __lowercase : def __init__( self : List[str] ,A : int ,A : str=3 ,A : str=7 ,A : Tuple=True ,A : str=True ,A : Optional[int]=False ,A : Dict=True ,A : List[str]=99 ,A : Optional[int]=32 ,A : List[Any]=5 ,A : Optional[int]=4 ,A : Union[str, Any]=37 ,A : Optional[int]="gelu" ,A : Optional[Any]=0.1 ,A : Tuple=0.1 ,A : Optional[int]=512 ,A : Optional[Any]=16 ,A : List[str]=2 ,A : str=0.0_2 ,A : Optional[Any]=3 ,A : Optional[Any]=4 ,A : Optional[Any]=None ,): '''simple docstring''' UpperCAmelCase__ : Tuple = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : Optional[int] = seq_length UpperCAmelCase__ : Optional[Any] = is_training UpperCAmelCase__ : Optional[Any] = use_input_mask UpperCAmelCase__ : List[Any] = use_token_type_ids UpperCAmelCase__ : Union[str, Any] = use_labels UpperCAmelCase__ : Tuple = vocab_size UpperCAmelCase__ : Optional[int] = hidden_size UpperCAmelCase__ : int = num_hidden_layers UpperCAmelCase__ : str = num_attention_heads UpperCAmelCase__ : Dict = intermediate_size UpperCAmelCase__ : Union[str, Any] = hidden_act UpperCAmelCase__ : int = hidden_dropout_prob UpperCAmelCase__ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase__ : Union[str, Any] = max_position_embeddings UpperCAmelCase__ : Optional[Any] = type_vocab_size UpperCAmelCase__ : int = type_sequence_label_size UpperCAmelCase__ : str = initializer_range UpperCAmelCase__ : List[str] = num_labels UpperCAmelCase__ : Union[str, Any] = num_choices UpperCAmelCase__ : Dict = scope def __lowercase ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) UpperCAmelCase__ : Any = None if self.use_input_mask: UpperCAmelCase__ : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ : Dict = None UpperCAmelCase__ : int = None UpperCAmelCase__ : List[Any] = None UpperCAmelCase__ : Optional[int] = None if self.use_labels: UpperCAmelCase__ : Any = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) UpperCAmelCase__ : str = ids_tensor([self.batch_size] ,self.num_choices ) UpperCAmelCase__ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase ( self : Union[str, Any] ): '''simple docstring''' return FalconConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=A ,initializer_range=self.initializer_range ,pad_token_id=1 ,new_decoder_architecture=A ,) def __lowercase ( self : Any ,A : Optional[Any] ,A : Optional[Any] ,A : Union[str, Any] ,A : Union[str, Any] ,A : Optional[Any] ,A : Any ,A : Dict ): '''simple docstring''' UpperCAmelCase__ : str = FalconModel(config=A ) model.to(A ) model.eval() UpperCAmelCase__ : int = model(A ,attention_mask=A ) UpperCAmelCase__ : List[str] = model(A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : Union[str, Any] ,A : str ,A : str ,A : Optional[int] ,A : List[str] ,A : List[str] ,A : Dict ,A : List[str] ,A : Tuple ,A : List[str] ,): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = True UpperCAmelCase__ : Optional[int] = FalconModel(A ) model.to(A ) model.eval() UpperCAmelCase__ : str = model( A ,attention_mask=A ,encoder_hidden_states=A ,encoder_attention_mask=A ,) UpperCAmelCase__ : List[Any] = model( A ,attention_mask=A ,encoder_hidden_states=A ,) UpperCAmelCase__ : int = model(A ,attention_mask=A ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : Dict ,A : Tuple ,A : Dict ,A : Union[str, Any] ,A : Any ,A : Union[str, Any] ,A : Dict ,A : int ,A : Tuple ,A : str ,): '''simple docstring''' UpperCAmelCase__ : List[str] = FalconForCausalLM(config=A ) model.to(A ) model.eval() UpperCAmelCase__ : Tuple = model(A ,attention_mask=A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase ( self : str ,A : Any ,A : Optional[Any] ,A : str ,A : Any ,A : List[str] ,A : Any ,A : Dict ,A : str ,A : Any ,): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = True UpperCAmelCase__ : int = True UpperCAmelCase__ : List[str] = FalconForCausalLM(config=A ) model.to(A ) model.eval() # first forward pass UpperCAmelCase__ : List[str] = model( A ,attention_mask=A ,encoder_hidden_states=A ,encoder_attention_mask=A ,use_cache=A ,) UpperCAmelCase__ : int = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase__ : str = ids_tensor((self.batch_size, 3) ,config.vocab_size ) UpperCAmelCase__ : Optional[Any] = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and UpperCAmelCase__ : Optional[Any] = torch.cat([input_ids, next_tokens] ,dim=-1 ) UpperCAmelCase__ : List[str] = torch.cat([input_mask, next_mask] ,dim=-1 ) UpperCAmelCase__ : Dict = model( A ,attention_mask=A ,encoder_hidden_states=A ,encoder_attention_mask=A ,output_hidden_states=A ,)["""hidden_states"""][0] UpperCAmelCase__ : Any = model( A ,attention_mask=A ,encoder_hidden_states=A ,encoder_attention_mask=A ,past_key_values=A ,output_hidden_states=A ,)["""hidden_states"""][0] # select random slice UpperCAmelCase__ : List[str] = ids_tensor((1,) ,output_from_past.shape[-1] ).item() UpperCAmelCase__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase__ : List[str] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(A ,A ,atol=1e-3 ) ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ) : Tuple = config_and_inputs UpperCAmelCase__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __lowercase ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): snake_case_ = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) snake_case_ = (FalconForCausalLM,) if is_torch_available() else () snake_case_ = ( { """feature-extraction""": FalconModel, """text-classification""": FalconForSequenceClassification, """text-generation""": FalconForCausalLM, """question-answering""": FalconForQuestionAnswering, """token-classification""": FalconForTokenClassification, """zero-shot""": FalconForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False def __lowercase ( self : Any ): '''simple docstring''' UpperCAmelCase__ : List[str] = FalconModelTester(self ) UpperCAmelCase__ : Optional[Any] = ConfigTester(self ,config_class=A ,hidden_size=37 ) def __lowercase ( self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def __lowercase ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def __lowercase ( self : List[str] ): '''simple docstring''' UpperCAmelCase__ , *UpperCAmelCase__ : Any = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: UpperCAmelCase__ : List[Any] = alibi self.model_tester.create_and_check_model(A ,*A ) def __lowercase ( self : str ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Tuple = 3 UpperCAmelCase__ : Dict = input_dict["""input_ids"""] UpperCAmelCase__ : Optional[int] = input_ids.ne(1 ).to(A ) UpperCAmelCase__ : Tuple = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) UpperCAmelCase__ : str = FalconForSequenceClassification(A ) model.to(A ) model.eval() UpperCAmelCase__ : Optional[int] = model(A ,attention_mask=A ,labels=A ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase ( self : Dict ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : List[str] = """single_label_classification""" UpperCAmelCase__ : Optional[int] = input_dict["""input_ids"""] UpperCAmelCase__ : Tuple = input_ids.ne(1 ).to(A ) UpperCAmelCase__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] ,self.model_tester.type_sequence_label_size ) UpperCAmelCase__ : int = FalconForSequenceClassification(A ) model.to(A ) model.eval() UpperCAmelCase__ : List[str] = model(A ,attention_mask=A ,labels=A ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase ( self : int ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Union[str, Any] = input_dict["""input_ids"""] UpperCAmelCase__ : Optional[int] = FalconForCausalLM(A ) model.to(A ) model.eval() UpperCAmelCase__ : Optional[Any] = model(A ,use_cache=A ) UpperCAmelCase__ : Any = input_ids.shape[0] UpperCAmelCase__ : Optional[Any] = model._convert_to_rw_cache(result.past_key_values ) UpperCAmelCase__ : int = model._convert_cache_to_standard_format(A ,A ) for layer in range(len(A ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def __lowercase ( self : str ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase__ : Union[str, Any] = 3 UpperCAmelCase__ : Optional[Any] = """multi_label_classification""" UpperCAmelCase__ : Tuple = input_dict["""input_ids"""] UpperCAmelCase__ : Union[str, Any] = input_ids.ne(1 ).to(A ) UpperCAmelCase__ : Tuple = ids_tensor( [self.model_tester.batch_size, config.num_labels] ,self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase__ : Tuple = FalconForSequenceClassification(A ) model.to(A ) model.eval() UpperCAmelCase__ : int = model(A ,attention_mask=A ,labels=A ) self.assertEqual(result.logits.shape ,(self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase ( self : Optional[Any] ): '''simple docstring''' # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(A ,"""use_cache""" ): return UpperCAmelCase__ : List[Any] = model_class(A ).to(A ) if "use_cache" not in inputs: UpperCAmelCase__ : Optional[int] = True UpperCAmelCase__ : List[Any] = model(**A ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return UpperCAmelCase__ : int = ( getattr(A ,"""decoder_layers""" ,A ) or getattr(A ,"""num_decoder_layers""" ,A ) or config.num_hidden_layers ) UpperCAmelCase__ : Optional[Any] = getattr(A ,"""num_kv_heads""" ,config.num_attention_heads ) UpperCAmelCase__ : Dict = getattr(A ,"""d_model""" ,config.hidden_size ) UpperCAmelCase__ : Optional[int] = embed_dim // num_attention_heads UpperCAmelCase__ : str = outputs["""past_key_values"""] self.assertEqual(len(A ) ,A ) UpperCAmelCase__ , UpperCAmelCase__ : List[str] = inputs["""input_ids"""].shape for i in range(A ): if config.new_decoder_architecture: UpperCAmelCase__ : List[Any] = config.num_attention_heads elif config.multi_query: UpperCAmelCase__ : Dict = 1 self.assertEqual(len(past_kv[0] ) ,2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape ,(batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape ,(batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class __lowercase ( unittest.TestCase ): @slow def __lowercase ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : str = AutoTokenizer.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) UpperCAmelCase__ : str = FalconForCausalLM.from_pretrained("""Rocketknight1/falcon-rw-1b""" ) model.eval() model.to(A ) UpperCAmelCase__ : Optional[int] = tokenizer("""My favorite food is""" ,return_tensors="""pt""" ).to(A ) UpperCAmelCase__ : Tuple = ( """My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.""" ) UpperCAmelCase__ : Any = model.generate(**A ,do_sample=A ,max_new_tokens=19 ) UpperCAmelCase__ : Union[str, Any] = tokenizer.batch_decode(A )[0] self.assertEqual(A ,A ) @slow def __lowercase ( self : Optional[int] ): '''simple docstring''' # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: UpperCAmelCase__ : Any = AutoTokenizer.from_pretrained(A ) UpperCAmelCase__ : Dict = FalconForCausalLM.from_pretrained(A ) model.eval() model.to(A ) UpperCAmelCase__ : Dict = tokenizer("""My favorite food is""" ,return_tensors="""pt""" ).to(A ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**A ,do_sample=A ,max_new_tokens=4 ) model.generate(**A ,do_sample=A ,max_new_tokens=4 ) model.generate(**A ,num_beams=2 ,max_new_tokens=4 ) @slow def __lowercase ( self : str ): '''simple docstring''' # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: UpperCAmelCase__ : List[Any] = AutoTokenizer.from_pretrained(A ) UpperCAmelCase__ : str = FalconForCausalLM.from_pretrained(A ) model.eval() model.to(device=A ) UpperCAmelCase__ : Optional[Any] = tokenizer("""My favorite food is""" ,return_tensors="""pt""" ).to(A ) # Test results are the same with and without cache UpperCAmelCase__ : Optional[Any] = model.generate(**A ,do_sample=A ,max_new_tokens=20 ,use_cache=A ) UpperCAmelCase__ : Optional[Any] = model.generate(**A ,do_sample=A ,max_new_tokens=20 ,use_cache=A ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
65
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class lowerCAmelCase_ ( unittest.TestCase ): _UpperCamelCase : List[Any] = ViTImageProcessor if is_vision_available() else None @property def __a ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __a ( self ): _lowercase : List[Any] = (3, 3_2, 1_2_8) _lowercase : List[Any] = tempfile.mkdtemp() # fmt: off _lowercase : str = ['[GO]', '[s]', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] # fmt: on _lowercase : str = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) _lowercase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_lowerCAmelCase ) + '\n' ) _lowercase : Dict = { 'do_normalize': False, 'do_resize': True, 'image_processor_type': 'ViTImageProcessor', 'resample': 3, 'size': {'height': 3_2, 'width': 1_2_8}, } _lowercase : int = os.path.join(self.tmpdirname , _lowerCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_lowerCAmelCase , _lowerCAmelCase ) def __a ( self , **_lowerCAmelCase ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def __a ( self , **_lowerCAmelCase ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def __a ( self ): shutil.rmtree(self.tmpdirname ) def __a ( self ): _lowercase : List[str] = np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta ) _lowercase : int = Image.fromarray(np.moveaxis(_lowerCAmelCase , 0 , -1 ) ) return image_input def __a ( self ): _lowercase : List[Any] = self.get_tokenizer() _lowercase : List[Any] = self.get_image_processor() _lowercase : str = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) _lowercase : Any = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=_lowerCAmelCase ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , _lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCAmelCase ) def __a ( self ): _lowercase : Dict = self.get_tokenizer() _lowercase : int = self.get_image_processor() _lowercase : List[Any] = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) _lowercase : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) _lowercase : Optional[int] = self.get_image_processor(do_normalize=_lowerCAmelCase , padding_value=1.0 ) _lowercase : Any = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_lowerCAmelCase , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , _lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCAmelCase ) def __a ( self ): _lowercase : Optional[Any] = self.get_image_processor() _lowercase : Optional[int] = self.get_tokenizer() _lowercase : Optional[Any] = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Tuple = self.prepare_image_inputs() _lowercase : str = image_processor(_lowerCAmelCase , return_tensors='np' ) _lowercase : Union[str, Any] = processor(images=_lowerCAmelCase , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __a ( self ): _lowercase : List[Any] = self.get_image_processor() _lowercase : Dict = self.get_tokenizer() _lowercase : str = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Dict = 'test' _lowercase : Optional[int] = processor(text=_lowerCAmelCase ) _lowercase : Any = tokenizer(_lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __a ( self ): _lowercase : int = self.get_image_processor() _lowercase : Tuple = self.get_tokenizer() _lowercase : int = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Optional[Any] = 'test' _lowercase : str = self.prepare_image_inputs() _lowercase : Optional[Any] = processor(text=_lowerCAmelCase , images=_lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'labels'] ) # test if it raises when no input is passed with pytest.raises(_lowerCAmelCase ): processor() def __a ( self ): _lowercase : Tuple = self.get_image_processor() _lowercase : Dict = self.get_tokenizer() _lowercase : Optional[Any] = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] _lowercase : Optional[int] = processor.char_decode(_lowerCAmelCase ) _lowercase : List[Any] = tokenizer.batch_decode(_lowerCAmelCase ) _lowercase : Union[str, Any] = [seq.replace(' ' , '' ) for seq in decoded_tok] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def __a ( self ): _lowercase : Any = self.get_image_processor() _lowercase : List[str] = self.get_tokenizer() _lowercase : Union[str, Any] = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Union[str, Any] = None _lowercase : Tuple = self.prepare_image_inputs() _lowercase : str = processor(text=_lowerCAmelCase , images=_lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __a ( self ): _lowercase : Any = self.get_image_processor() _lowercase : int = self.get_tokenizer() _lowercase : Any = MgpstrProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) _lowercase : Union[str, Any] = torch.randn(1 , 2_7 , 3_8 ) _lowercase : Tuple = torch.randn(1 , 2_7 , 5_0_2_5_7 ) _lowercase : List[str] = torch.randn(1 , 2_7 , 3_0_5_2_2 ) _lowercase : Union[str, Any] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['generated_text', 'scores', 'char_preds', 'bpe_preds', 'wp_preds'] )
66
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = """\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ __snake_case = """\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ __snake_case = R""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Tuple = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0 UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ ) return { "accuracy": accuracy, }
658
0
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def SCREAMING_SNAKE_CASE__ ( snake_case__ :Optional[Any] , snake_case__ :Optional[Any]=0.999 , snake_case__ :Tuple="cosine" , ) -> Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case__ :List[Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case__ :Optional[int] ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) _lowercase = [] for i in range(snake_case__ ): _lowercase = i / num_diffusion_timesteps _lowercase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case__ ) / alpha_bar_fn(snake_case__ ) , snake_case__ ) ) return torch.tensor(snake_case__ , dtype=torch.floataa ) class A_ ( UpperCAmelCase , UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [e.name for e in KarrasDiffusionSchedulers] SCREAMING_SNAKE_CASE_ : Dict = 2 @register_to_config def __init__( self : Union[str, Any] ,__A : int = 1000 ,__A : float = 0.00085 ,__A : float = 0.012 ,__A : str = "linear" ,__A : Optional[Union[np.ndarray, List[float]]] = None ,__A : str = "epsilon" ,__A : str = "linspace" ,__A : int = 0 ,) -> Union[str, Any]: if trained_betas is not None: _lowercase = torch.tensor(__A ,dtype=torch.floataa ) elif beta_schedule == "linear": _lowercase = torch.linspace(__A ,__A ,__A ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _lowercase = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,__A ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _lowercase = betas_for_alpha_bar(__A ) else: raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" ) _lowercase = 1.0 - self.betas _lowercase = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(__A ,__A ,__A ) def __UpperCAmelCase ( self : str ,__A : List[str] ,__A : Any=None ) -> str: if schedule_timesteps is None: _lowercase = self.timesteps _lowercase = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _lowercase = 1 if len(__A ) > 1 else 0 else: _lowercase = timestep.cpu().item() if torch.is_tensor(__A ) else timestep _lowercase = self._index_counter[timestep_int] return indices[pos].item() @property def __UpperCAmelCase ( self : int ) -> Tuple: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def __UpperCAmelCase ( self : List[str] ,__A : torch.FloatTensor ,__A : Union[float, torch.FloatTensor] ,) -> torch.FloatTensor: _lowercase = self.index_for_timestep(__A ) if self.state_in_first_order: _lowercase = self.sigmas[step_index] else: _lowercase = self.sigmas_interpol[step_index] _lowercase = sample / ((sigma**2 + 1) ** 0.5) return sample def __UpperCAmelCase ( self : Tuple ,__A : int ,__A : Union[str, torch.device] = None ,__A : Optional[int] = None ,) -> str: _lowercase = num_inference_steps _lowercase = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _lowercase = np.linspace(0 ,num_train_timesteps - 1 ,__A ,dtype=__A )[::-1].copy() elif self.config.timestep_spacing == "leading": _lowercase = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowercase = (np.arange(0 ,__A ) * step_ratio).round()[::-1].copy().astype(__A ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _lowercase = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _lowercase = (np.arange(__A ,0 ,-step_ratio )).round().copy().astype(__A ) timesteps -= 1 else: raise ValueError( F"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) _lowercase = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _lowercase = torch.from_numpy(np.log(__A ) ).to(__A ) _lowercase = np.interp(__A ,np.arange(0 ,len(__A ) ) ,__A ) _lowercase = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _lowercase = torch.from_numpy(__A ).to(device=__A ) # interpolate sigmas _lowercase = sigmas.log().lerp(sigmas.roll(1 ).log() ,0.5 ).exp() _lowercase = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) _lowercase = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(__A ).startswith('mps' ): # mps does not support float64 _lowercase = torch.from_numpy(__A ).to(__A ,dtype=torch.floataa ) else: _lowercase = torch.from_numpy(__A ).to(__A ) # interpolate timesteps _lowercase = self.sigma_to_t(__A ).to(__A ,dtype=timesteps.dtype ) _lowercase = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) ,dim=-1 ).flatten() _lowercase = torch.cat([timesteps[:1], interleaved_timesteps] ) _lowercase = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _lowercase = defaultdict(__A ) def __UpperCAmelCase ( self : Optional[Any] ,__A : str ) -> List[str]: # get log sigma _lowercase = sigma.log() # get distribution _lowercase = log_sigma - self.log_sigmas[:, None] # get sigmas range _lowercase = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) _lowercase = low_idx + 1 _lowercase = self.log_sigmas[low_idx] _lowercase = self.log_sigmas[high_idx] # interpolate sigmas _lowercase = (low - log_sigma) / (low - high) _lowercase = w.clamp(0 ,1 ) # transform interpolation to time range _lowercase = (1 - w) * low_idx + w * high_idx _lowercase = t.view(sigma.shape ) return t @property def __UpperCAmelCase ( self : Any ) -> Union[str, Any]: return self.sample is None def __UpperCAmelCase ( self : Dict ,__A : Union[torch.FloatTensor, np.ndarray] ,__A : Union[float, torch.FloatTensor] ,__A : Union[torch.FloatTensor, np.ndarray] ,__A : bool = True ,) -> Union[SchedulerOutput, Tuple]: _lowercase = self.index_for_timestep(__A ) # advance index counter by 1 _lowercase = timestep.cpu().item() if torch.is_tensor(__A ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _lowercase = self.sigmas[step_index] _lowercase = self.sigmas_interpol[step_index + 1] _lowercase = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method _lowercase = self.sigmas[step_index - 1] _lowercase = self.sigmas_interpol[step_index] _lowercase = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _lowercase = 0 _lowercase = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _lowercase = sigma_hat if self.state_in_first_order else sigma_interpol _lowercase = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _lowercase = sigma_hat if self.state_in_first_order else sigma_interpol _lowercase = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('prediction_type not implemented yet: sample' ) else: raise ValueError( F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _lowercase = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _lowercase = sigma_interpol - sigma_hat # store for 2nd order step _lowercase = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order _lowercase = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep _lowercase = sigma_next - sigma_hat _lowercase = self.sample _lowercase = None _lowercase = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__A ) def __UpperCAmelCase ( self : List[Any] ,__A : torch.FloatTensor ,__A : torch.FloatTensor ,__A : torch.FloatTensor ,) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples _lowercase = self.sigmas.to(device=original_samples.device ,dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__A ): # mps does not support float64 _lowercase = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) _lowercase = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: _lowercase = self.timesteps.to(original_samples.device ) _lowercase = timesteps.to(original_samples.device ) _lowercase = [self.index_for_timestep(__A ,__A ) for t in timesteps] _lowercase = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _lowercase = sigma.unsqueeze(-1 ) _lowercase = original_samples + noise * sigma return noisy_samples def __len__( self : str ) -> Tuple: return self.config.num_train_timesteps
67
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def _A ( ): UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase :Dict = parser.parse_args() return args.f def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ): UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) raise ValueError(F'''can\'t find {path}''' ) __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = self.get_auto_remove_tmp_dir() UpperCamelCase :Any = F''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :List[str] = F''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :int = F''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def UpperCAmelCase ( self ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2 UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[int] = F''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :Dict = F''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
658
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf __A = logging.get_logger(__name__) @dataclass class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[int] = [ 'no_inference', 'no_cuda', 'no_tpu', 'no_speed', 'no_memory', 'no_env_print', 'no_multi_process', ] def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Dict: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: __UpperCAmelCase =deprecated_arg[3:] __UpperCAmelCase =not kwargs.pop(__SCREAMING_SNAKE_CASE ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) __UpperCAmelCase =kwargs.pop("""tpu_name""" , self.tpu_name ) __UpperCAmelCase =kwargs.pop("""device_idx""" , self.device_idx ) __UpperCAmelCase =kwargs.pop("""eager_mode""" , self.eager_mode ) __UpperCAmelCase =kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**__SCREAMING_SNAKE_CASE ) lowerCamelCase : str = field( default=UpperCamelCase , metadata={'help': 'Name of TPU'} , ) lowerCamelCase : int = field( default=0 , metadata={'help': 'CPU / GPU device index. Defaults to 0.'} , ) lowerCamelCase : bool = field(default=UpperCamelCase , metadata={'help': 'Benchmark models in eager model.'} ) lowerCamelCase : bool = field( default=UpperCamelCase , metadata={ 'help': 'Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.' } , ) @cached_property def _a ( self : List[str] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) __UpperCAmelCase =None if self.tpu: try: if self.tpu_name: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: __UpperCAmelCase =tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: __UpperCAmelCase =None return tpu @cached_property def _a ( self : Tuple ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]: requires_backends(self , ["""tf"""] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) __UpperCAmelCase =tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , """GPU""" ) __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU __UpperCAmelCase =tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def _a ( self : Optional[Any] ) -> bool: requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def _a ( self : str ) -> "tf.distribute.Strategy": requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def _a ( self : Dict ) -> Optional[int]: requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def _a ( self : List[str] ) -> int: requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def _a ( self : List[str] ) -> bool: return self.n_gpu > 0
68
from __future__ import annotations from collections.abc import Callable def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ): UpperCamelCase :Optional[Any] = x_start UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCamelCase :Any = (x_end - x_start) / steps + xa UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCamelCase :Optional[int] = xa UpperCamelCase :List[str] = fxa return area if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE__ : int ): return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 10_00_00: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
658
0
'''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 : List[Any] = False @skip_mps class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE = StableDiffusionAttendAndExcitePipeline __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_PARAMS __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""} ) __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS __SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS @classmethod def A ( cls : Union[str, Any] ): """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(a_ ) @classmethod def A ( cls : List[Any] ): """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(a_ ) def A ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) __snake_case = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=a_ , ) __snake_case = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a_ , set_alpha_to_one=a_ , ) torch.manual_seed(0 ) __snake_case = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __snake_case = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) __snake_case = CLIPTextModel(a_ ) __snake_case = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __snake_case = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A ( self : Optional[Any] , a_ : Optional[Any] , a_ : Optional[int]=0 ): """simple docstring""" if str(a_ ).startswith("mps" ): __snake_case = torch.manual_seed(a_ ) else: __snake_case = torch.Generator(device=a_ ).manual_seed(a_ ) __snake_case = __snake_case = { "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 A ( self : Optional[Any] ): """simple docstring""" __snake_case = "cpu" __snake_case = self.get_dummy_components() __snake_case = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) __snake_case = self.get_dummy_inputs(a_ ) __snake_case = pipe(**a_ ).images __snake_case = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 64, 64, 3) ) __snake_case = np.array( [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496] ) __snake_case = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_ , 1e-3 ) def A ( self : str ): """simple docstring""" super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 ) def A ( self : str ): """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A ( self : int ): """simple docstring""" self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7e-4 ) def A ( self : List[str] ): """simple docstring""" super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def A ( self : Tuple ): """simple docstring""" super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 ) def A ( self : str ): """simple docstring""" super().test_save_load_local(expected_max_difference=5e-4 ) def A ( self : str ): """simple docstring""" super().test_save_load_optional_components(expected_max_difference=4e-4 ) @require_torch_gpu @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @classmethod def A ( cls : Optional[Any] ): """simple docstring""" super().setUpClass() torch.use_deterministic_algorithms(a_ ) @classmethod def A ( cls : List[str] ): """simple docstring""" super().tearDownClass() torch.use_deterministic_algorithms(a_ ) def A ( self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : Union[str, Any] ): """simple docstring""" __snake_case = torch.manual_seed(51 ) __snake_case = StableDiffusionAttendAndExcitePipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , safety_checker=a_ , torch_dtype=torch.floataa ) pipe.to("cuda" ) __snake_case = "a painting of an elephant with glasses" __snake_case = [5, 7] __snake_case = pipe( prompt=a_ , token_indices=a_ , guidance_scale=7.5 , generator=a_ , num_inference_steps=5 , max_iter_to_alter=5 , output_type="numpy" , ).images[0] __snake_case = 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
69
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :str = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = 10 UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps[0] UpperCamelCase :Union[str, Any] = scheduler.timesteps[1] UpperCamelCase :str = self.dummy_sample UpperCamelCase :List[str] = 0.1 * sample UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase ( self ) -> List[str]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # 1. scale model input UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :Tuple = pred_prev_sample UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = scheduler.timesteps UpperCamelCase :int = torch.manual_seed(0 ) UpperCamelCase :str = self.dummy_model() UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :int = pred_prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :Tuple = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = [39, 30, 12, 1, 0] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[int] = self.scheduler_classes[0] UpperCamelCase :List[str] = self.get_scheduler_config() UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
658
0
def _SCREAMING_SNAKE_CASE ( lowercase : str ): '''simple docstring''' assert column_title.isupper() lowerCamelCase_ = 0 lowerCamelCase_ = len(lowercase ) - 1 lowerCamelCase_ = 0 while index >= 0: lowerCamelCase_ = (ord(column_title[index] ) - 64) * pow(26 , lowercase ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
70
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
'''simple docstring''' def a__ ( _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : int ) -> float: """simple docstring""" UpperCAmelCase_ : Optional[int] = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def a__ ( ) -> Optional[int]: """simple docstring""" print(sum_of_series(1 , 1 , 10 ) ) if __name__ == "__main__": import doctest doctest.testmod()
71
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: return None class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: return None class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =[ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[int]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> int: from transformers import BertModel UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCAmelCase ( self ) -> str: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[str]: from transformers import BertModel UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' ) @require_tf @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[Any]: from transformers import TFBertModel UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
658
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __magic_name__ ( metaclass=__SCREAMING_SNAKE_CASE ): UpperCamelCase__ = ['note_seq'] def __init__( self , *snake_case_ , **snake_case_ ): requires_backends(self , ['''note_seq'''] ) @classmethod def _A( cls , *snake_case_ , **snake_case_ ): requires_backends(cls , ['''note_seq'''] ) @classmethod def _A( cls , *snake_case_ , **snake_case_ ): requires_backends(cls , ['''note_seq'''] )
72
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Union[str, Any] = tempfile.mkdtemp() UpperCamelCase :List[str] = 5 # Realm tok UpperCamelCase :List[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , 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] ) ) UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def UpperCAmelCase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records ) return config def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Tuple = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=SCREAMING_SNAKE_CASE_ , ) return block_records def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Optional[int] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[Any] = self.get_config() UpperCamelCase :str = self.get_dummy_retriever() UpperCamelCase :int = retriever.tokenizer UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' ) UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Tuple = tokenizer( ['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Optional[Any] = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = self.get_config() UpperCamelCase :Union[str, Any] = self.get_dummy_retriever() UpperCamelCase :Dict = retriever.tokenizer UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' ) UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Optional[Any] = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Any = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: UpperCamelCase :Tuple = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
658
0
import heapq as hq import math from collections.abc import Iterator class _snake_case : def __init__( self , a) -> Optional[Any]: SCREAMING_SNAKE_CASE = str(id_) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = {} # {vertex:distance} def __lt__( self , a) -> Dict: return self.key < other.key def __repr__( self) -> Optional[Any]: return self.id def SCREAMING_SNAKE_CASE__ ( self , a) -> Optional[Any]: self.neighbors.append(a) def SCREAMING_SNAKE_CASE__ ( self , a , a) -> Tuple: SCREAMING_SNAKE_CASE = weight def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase): # add the neighbors: graph[a - 1].add_neighbor(graph[b - 1]) graph[b - 1].add_neighbor(graph[a - 1]) # add the edges: graph[a - 1].add_edge(graph[b - 1] , _UpperCAmelCase) graph[b - 1].add_edge(graph[a - 1] , _UpperCAmelCase) def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): SCREAMING_SNAKE_CASE = [] for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = graph[:] while q: SCREAMING_SNAKE_CASE = min(_UpperCAmelCase) q.remove(_UpperCAmelCase) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] for i in range(1 , len(_UpperCAmelCase)): a.append((int(graph[i].id) + 1, int(graph[i].pi.id) + 1)) return a def lowerCamelCase__ (_UpperCAmelCase , _UpperCAmelCase): for u in graph: SCREAMING_SNAKE_CASE = math.inf SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = list(_UpperCAmelCase) hq.heapify(_UpperCAmelCase) while h: SCREAMING_SNAKE_CASE = hq.heappop(_UpperCAmelCase) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE = u SCREAMING_SNAKE_CASE = u.edges[v.id] hq.heapify(_UpperCAmelCase) for i in range(1 , len(_UpperCAmelCase)): yield (int(graph[i].id) + 1, int(graph[i].pi.id) + 1) def lowerCamelCase__ (): pass if __name__ == "__main__": import doctest doctest.testmod()
73
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]: UpperCamelCase :int = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[int] = max_length UpperCamelCase :Union[str, Any] = num_mel_bins UpperCamelCase :Optional[int] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :Dict = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :str = num_attention_heads UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :str = type_sequence_label_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = scope UpperCamelCase :List[Any] = frequency_stride UpperCamelCase :Tuple = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension UpperCamelCase :Optional[int] = num_patches + 2 def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :str = self.get_config() return config, input_values, labels def UpperCAmelCase ( self ) -> List[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :List[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) UpperCamelCase_ : Any =( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[Any] =False UpperCamelCase_ : Dict =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = ASTModelTester(self ) UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> str: pass def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Any = [*signature.parameters.keys()] UpperCamelCase :Optional[int] = ['''input_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Optional[int]: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Any = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase ( self ) -> Tuple: return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.default_feature_extractor UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = self.default_feature_extractor UpperCamelCase , UpperCamelCase :Dict = prepare_audio() UpperCamelCase :Dict = audio.squeeze().numpy() UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase :List[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class __UpperCamelCase : """simple docstring""" def __init__( self : int , _A : str = "cpu" , _A : str = "openai/clip-vit-large-patch14" ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = device __SCREAMING_SNAKE_CASE : int = CLIPTokenizerFast.from_pretrained(_A ) __SCREAMING_SNAKE_CASE : int = [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] __SCREAMING_SNAKE_CASE : Optional[int] = [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] __SCREAMING_SNAKE_CASE : Optional[int] = torchvision.transforms.Normalize(self.image_mean , self.image_std ) __SCREAMING_SNAKE_CASE : List[str] = torchvision.transforms.Resize(224 ) __SCREAMING_SNAKE_CASE : int = torchvision.transforms.CenterCrop(224 ) def UpperCAmelCase__ ( self : Any , _A : List[Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = self.resize(_A ) __SCREAMING_SNAKE_CASE : Any = self.center_crop(_A ) __SCREAMING_SNAKE_CASE : List[Any] = self.normalize(_A ) return images def __call__( self : int , _A : Dict=None , _A : str=None , **_A : Dict ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer(text=_A , **_A ) __SCREAMING_SNAKE_CASE : List[Any] = self.preprocess_img(_A ) __SCREAMING_SNAKE_CASE : str = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class __UpperCamelCase ( nn.Module ): """simple docstring""" def __init__( self : Any , _A : Any=10 , _A : Tuple=0.01 , _A : int=None , _A : Any=None , _A : str=None , _A : str=None , _A : Union[str, Any]=None , _A : int=None , _A : str=False , _A : int=True , _A : str="image" , _A : Union[str, Any]=True , _A : Tuple=False , _A : str=False , _A : Dict=False , ): """simple docstring""" super().__init__() __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = device if device else get_device() if vqgan: __SCREAMING_SNAKE_CASE : Any = vqgan else: __SCREAMING_SNAKE_CASE : Optional[Any] = load_vqgan(self.device , conf_path=_A , ckpt_path=_A ) self.vqgan.eval() if clip: __SCREAMING_SNAKE_CASE : int = clip else: __SCREAMING_SNAKE_CASE : Optional[Any] = CLIPModel.from_pretrained('''openai/clip-vit-base-patch32''' ) self.clip.to(self.device ) __SCREAMING_SNAKE_CASE : Any = ProcessorGradientFlow(device=self.device ) __SCREAMING_SNAKE_CASE : Any = iterations __SCREAMING_SNAKE_CASE : List[str] = lr __SCREAMING_SNAKE_CASE : List[str] = log __SCREAMING_SNAKE_CASE : List[str] = make_grid __SCREAMING_SNAKE_CASE : Optional[Any] = return_val __SCREAMING_SNAKE_CASE : Optional[Any] = quantize __SCREAMING_SNAKE_CASE : Any = self.vqgan.decoder.z_shape def UpperCAmelCase__ ( self : List[str] , _A : int=None , _A : str=None , _A : str=5 , _A : str=True ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = [] if output_path is None: __SCREAMING_SNAKE_CASE : Dict = '''./animation.gif''' if input_path is None: __SCREAMING_SNAKE_CASE : Optional[int] = self.save_path __SCREAMING_SNAKE_CASE : List[Any] = sorted(glob(input_path + '''/*''' ) ) if not len(_A ): raise ValueError( '''No images found in save path, aborting (did you pass save_intermediate=True to the generate''' ''' function?)''' ) if len(_A ) == 1: print('''Only one image found in save path, (did you pass save_intermediate=True to the generate function?)''' ) __SCREAMING_SNAKE_CASE : Tuple = total_duration / len(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [frame_duration] * len(_A ) if extend_frames: __SCREAMING_SNAKE_CASE : List[Any] = 1.5 __SCREAMING_SNAKE_CASE : Optional[int] = 3 for file_name in paths: if file_name.endswith('''.png''' ): images.append(imageio.imread(_A ) ) imageio.mimsave(_A , _A , duration=_A ) print(F'''gif saved to {output_path}''' ) def UpperCAmelCase__ ( self : List[Any] , _A : Dict=None , _A : Tuple=None ): """simple docstring""" if not (path or img): raise ValueError('''Input either path or tensor''' ) if img is not None: raise NotImplementedError __SCREAMING_SNAKE_CASE : Union[str, Any] = preprocess(Image.open(_A ) , target_image_size=256 ).to(self.device ) __SCREAMING_SNAKE_CASE : Tuple = preprocess_vqgan(_A ) __SCREAMING_SNAKE_CASE, *__SCREAMING_SNAKE_CASE : List[str] = self.vqgan.encode(_A ) return z def UpperCAmelCase__ ( self : Optional[Any] , _A : List[str] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.latent.detach().requires_grad_() __SCREAMING_SNAKE_CASE : Any = base_latent + transform_vector if self.quantize: __SCREAMING_SNAKE_CASE, *__SCREAMING_SNAKE_CASE : List[Any] = self.vqgan.quantize(_A ) else: __SCREAMING_SNAKE_CASE : Tuple = trans_latent return self.vqgan.decode(_A ) def UpperCAmelCase__ ( self : List[Any] , _A : Tuple , _A : Dict , _A : Optional[Any]=None ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.clip_preprocessor(text=_A , images=_A , return_tensors='''pt''' , padding=_A ) __SCREAMING_SNAKE_CASE : str = self.clip(**_A ) __SCREAMING_SNAKE_CASE : List[str] = clip_outputs.logits_per_image if weights is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = similarity_logits * weights return similarity_logits.sum() def UpperCAmelCase__ ( self : Tuple , _A : List[Any] , _A : List[Any] , _A : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = self._get_clip_similarity(pos_prompts['''prompts'''] , _A , weights=(1 / pos_prompts['''weights''']) ) if neg_prompts: __SCREAMING_SNAKE_CASE : Tuple = self._get_clip_similarity(neg_prompts['''prompts'''] , _A , weights=neg_prompts['''weights'''] ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([1] , device=self.device ) __SCREAMING_SNAKE_CASE : Dict = -torch.log(_A ) + torch.log(_A ) return loss def UpperCAmelCase__ ( self : int , _A : str , _A : List[Any] , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = torch.randn_like(self.latent , requires_grad=_A , device=self.device ) __SCREAMING_SNAKE_CASE : List[Any] = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() __SCREAMING_SNAKE_CASE : List[Any] = self._add_vector(_A ) __SCREAMING_SNAKE_CASE : Union[str, Any] = loop_post_process(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = self._get_CLIP_loss(_A , _A , _A ) print('''CLIP loss''' , _A ) if self.log: wandb.log({'''CLIP Loss''': clip_loss} ) clip_loss.backward(retain_graph=_A ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def UpperCAmelCase__ ( self : str , _A : List[str] , _A : int , _A : List[Any] ): """simple docstring""" wandb.init(reinit=_A , project='''face-editor''' ) wandb.config.update({'''Positive Prompts''': positive_prompts} ) wandb.config.update({'''Negative Prompts''': negative_prompts} ) wandb.config.update({'''lr''': self.lr, '''iterations''': self.iterations} ) if image_path: __SCREAMING_SNAKE_CASE : Dict = Image.open(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = image.resize((256, 256) ) wandb.log('''Original Image''' , wandb.Image(_A ) ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : Optional[int] ): """simple docstring""" if not prompts: return [] __SCREAMING_SNAKE_CASE : Dict = [] __SCREAMING_SNAKE_CASE : Tuple = [] if isinstance(_A , _A ): __SCREAMING_SNAKE_CASE : int = [prompt.strip() for prompt in prompts.split('''|''' )] for prompt in prompts: if isinstance(_A , (tuple, list) ): __SCREAMING_SNAKE_CASE : Union[str, Any] = prompt[0] __SCREAMING_SNAKE_CASE : int = float(prompt[1] ) elif ":" in prompt: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[Any] = prompt.split(''':''' ) __SCREAMING_SNAKE_CASE : str = float(_A ) else: __SCREAMING_SNAKE_CASE : int = prompt __SCREAMING_SNAKE_CASE : List[Any] = 1.0 processed_prompts.append(_A ) weights.append(_A ) return { "prompts": processed_prompts, "weights": torch.tensor(_A , device=self.device ), } def UpperCAmelCase__ ( self : Optional[int] , _A : List[str] , _A : List[Any]=None , _A : Tuple=None , _A : Dict=True , _A : int=False , _A : List[Any]=True , _A : Tuple=True , _A : int=None , ): """simple docstring""" if image_path: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._get_latent(_A ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(_A , _A , _A ) assert pos_prompts, "You must provide at least one positive prompt." __SCREAMING_SNAKE_CASE : Tuple = self.process_prompts(_A ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.process_prompts(_A ) if save_final and save_path is None: __SCREAMING_SNAKE_CASE : List[str] = os.path.join('''./outputs/''' , '''_'''.join(pos_prompts['''prompts'''] ) ) if not os.path.exists(_A ): os.makedirs(_A ) else: __SCREAMING_SNAKE_CASE : str = save_path + '''_''' + get_timestamp() os.makedirs(_A ) __SCREAMING_SNAKE_CASE : Dict = save_path __SCREAMING_SNAKE_CASE : str = self.vqgan.decode(self.latent )[0] if show_intermediate: print('''Original Image''' ) show_pil(custom_to_pil(_A ) ) __SCREAMING_SNAKE_CASE : str = loop_post_process(_A ) for iter, transformed_img in enumerate(self._optimize_CLIP(_A , _A , _A ) ): if show_intermediate: show_pil(_A ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({'''Image''': wandb.Image(_A )} ) if show_final: show_pil(_A ) if save_final: transformed_img.save(os.path.join(self.save_path , F'''iter_{iter:03d}_final.png''' ) )
74
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): UpperCamelCase :Dict = [image] if isinstance(image[0] , PIL.Image.Image ): UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0 UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 ) UpperCamelCase :Tuple = 2.0 * image - 1.0 UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ): if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): UpperCamelCase :int = True UpperCamelCase :Dict = va.device UpperCamelCase :List[Any] = va.cpu().numpy() UpperCamelCase :str = va.cpu().numpy() UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: UpperCamelCase :Any = (1 - t) * va + t * va else: UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = theta_a * t UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a UpperCamelCase :Union[str, Any] = sa * va + sa * va if inputs_are_torch: UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ): for param in model.parameters(): UpperCamelCase :Any = value class UpperCAmelCase_ ( lowercase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str: super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = ( feature_extractor.size if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ ) else feature_extractor.size['''shortest_edge'''] ) UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ ) set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: # get the original timestep using init_timestep UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int: if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ ) ] UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) else: UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[str] = 0.1_8215 * init_latents UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) # get latents UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = init_latents return latents def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: UpperCamelCase :List[str] = latents.detach().requires_grad_() UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep] UpperCamelCase :Optional[int] = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = self.scheduler.sigmas[index] UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :int = 1 / 0.1_8215 * sample UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype ) UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = latents.detach() + grads * (sigma**2) UpperCamelCase :Optional[Any] = noise_pred_original else: UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1: UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1) UpperCamelCase :Tuple = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]] UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ ) if style_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ ) # get prompt text embeddings for content and style UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # duplicate text embeddings for each generation per prompt UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # set timesteps UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) UpperCamelCase :List[str] = {} if accepts_offset: UpperCamelCase :Tuple = 1 self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ ) # Preprocess image UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if clip_guidance_scale > 0: UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = slerp( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase :Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase :Any = content_text_input.input_ids.shape[-1] UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase :int = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase :int = 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}''' ) UpperCamelCase :str = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase :Dict = {} if accepts_eta: UpperCamelCase :int = eta # check if the scheduler accepts generator UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: UpperCamelCase :List[str] = generator with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ): for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # expand the latents if we are doing classifier free guidance UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform classifier free guidance if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 ) UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: UpperCamelCase :int = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) UpperCamelCase , UpperCamelCase :str = self.cond_fn( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
658
0
'''simple docstring''' import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase__ = get_tests_dir('''fixtures/test_sentencepiece.model''') UpperCamelCase__ = get_tests_dir('''fixtures/test_sentencepiece_bpe.model''') UpperCamelCase__ = '''pt''' if is_torch_available() else '''tf''' @require_sentencepiece @require_tokenizers class lowerCamelCase_ ( __a , unittest.TestCase ): lowerCAmelCase__ = CamembertTokenizer lowerCAmelCase__ = CamembertTokenizerFast lowerCAmelCase__ = True lowerCAmelCase__ = True def lowercase_ ( self : str ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase__ : Optional[int] = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase_ ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = '''<pad>''' UpperCAmelCase__ : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def lowercase_ ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>NOTUSED''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(_A ) , 1_004 ) def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_005 ) def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : Dict = CamembertTokenizer(_A ) tokenizer.save_pretrained(self.tmpdirname ) UpperCAmelCase__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) UpperCAmelCase__ : Any = '''I was born in 92000, and this is falsé.''' UpperCAmelCase__ : Any = tokenizer.encode(_A ) UpperCAmelCase__ : Tuple = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : Dict = tokenizer.encode(_A , add_special_tokens=_A ) UpperCAmelCase__ : Optional[Any] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) UpperCAmelCase__ : Tuple = tokenizer.convert_ids_to_tokens(_A ) UpperCAmelCase__ : int = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) def lowercase_ ( self : Optional[Any] ): '''simple docstring''' if not self.test_rust_tokenizer: return UpperCAmelCase__ : str = self.get_tokenizer() UpperCAmelCase__ : Tuple = self.get_rust_tokenizer() UpperCAmelCase__ : List[Any] = '''I was born in 92000, and this is falsé.''' UpperCAmelCase__ : List[str] = tokenizer.tokenize(_A ) UpperCAmelCase__ : Any = rust_tokenizer.tokenize(_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : Any = tokenizer.encode(_A , add_special_tokens=_A ) UpperCAmelCase__ : Optional[int] = rust_tokenizer.encode(_A , add_special_tokens=_A ) self.assertListEqual(_A , _A ) UpperCAmelCase__ : str = self.get_rust_tokenizer() UpperCAmelCase__ : Optional[int] = tokenizer.encode(_A ) UpperCAmelCase__ : Optional[Any] = rust_tokenizer.encode(_A ) self.assertListEqual(_A , _A ) @slow def lowercase_ ( self : Any ): '''simple docstring''' UpperCAmelCase__ : int = {'''input_ids''': [[5, 54, 7_196, 297, 30, 23, 776, 18, 11, 3_215, 3_705, 8_252, 22, 3_164, 1_181, 2_116, 29, 16, 813, 25, 791, 3_314, 20, 3_446, 38, 27_575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9_088, 20, 1_517, 8, 22_804, 18_818, 10, 38, 629, 607, 607, 142, 19, 7_196, 867, 56, 10_326, 24, 2_267, 20, 416, 5_072, 15_612, 233, 734, 7, 2_399, 27, 16, 3_015, 1_649, 7, 24, 20, 4_338, 2_399, 27, 13, 3_400, 14, 13, 6_189, 8, 930, 9, 6]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. UpperCAmelCase__ : Tuple = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=_A , model_name='''camembert-base''' , revision='''3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf''' , sequences=_A , )
75
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :list[list[int]] = [] UpperCamelCase :list[int] = [] UpperCamelCase :List[str] = 0 UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) __snake_case = [3, 34, 4, 12, 5, 2] __snake_case = 9 __snake_case = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
658
0
"""simple docstring""" import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : List[str] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: __lowercase : Optional[int] = 1_28 elif "12-12" in model_name: __lowercase : Optional[int] = 12 __lowercase : Optional[int] = 12 elif "14-14" in model_name: __lowercase : Optional[Any] = 14 __lowercase : List[Any] = 14 elif "16-16" in model_name: __lowercase : List[Any] = 16 __lowercase : List[Any] = 16 else: raise ValueError('''Model not supported''' ) __lowercase : str = '''huggingface/label-files''' if "speech-commands" in model_name: __lowercase : Optional[Any] = 35 __lowercase : Optional[int] = '''speech-commands-v2-id2label.json''' else: __lowercase : int = 5_27 __lowercase : int = '''audioset-id2label.json''' __lowercase : Optional[Any] = json.load(open(hf_hub_download(__UpperCamelCase , __UpperCamelCase , repo_type='''dataset''' ) , '''r''' ) ) __lowercase : Optional[int] = {int(__UpperCamelCase ): v for k, v in idalabel.items()} __lowercase : Tuple = idalabel __lowercase : Optional[int] = {v: k for k, v in idalabel.items()} return config def __UpperCAmelCase ( __UpperCamelCase ): if "module.v" in name: __lowercase : Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: __lowercase : List[str] = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: __lowercase : Any = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: __lowercase : List[Any] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: __lowercase : Optional[int] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: __lowercase : Optional[int] = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: __lowercase : Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: __lowercase : str = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: __lowercase : List[str] = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: __lowercase : int = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: __lowercase : int = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: __lowercase : Tuple = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: __lowercase : List[Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: __lowercase : str = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: __lowercase : Dict = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): for key in orig_state_dict.copy().keys(): __lowercase : List[str] = orig_state_dict.pop(__UpperCamelCase ) if "qkv" in key: __lowercase : Union[str, Any] = key.split('''.''' ) __lowercase : Optional[int] = int(key_split[3] ) __lowercase : List[str] = config.hidden_size if "weight" in key: __lowercase : Tuple = val[:dim, :] __lowercase : Union[str, Any] = val[dim : dim * 2, :] __lowercase : List[Any] = val[-dim:, :] else: __lowercase : List[str] = val[:dim] __lowercase : Dict = val[dim : dim * 2] __lowercase : List[Any] = val[-dim:] else: __lowercase : Dict = val return orig_state_dict def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Dict = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(__UpperCamelCase , __UpperCamelCase ) @torch.no_grad() def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=False ): __lowercase : Union[str, Any] = get_audio_spectrogram_transformer_config(__UpperCamelCase ) __lowercase : Union[str, Any] = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict __lowercase : List[Any] = model_name_to_url[model_name] __lowercase : List[str] = torch.hub.load_state_dict_from_url(__UpperCamelCase , map_location='''cpu''' ) # remove some keys remove_keys(__UpperCamelCase ) # rename some keys __lowercase : Optional[Any] = convert_state_dict(__UpperCamelCase , __UpperCamelCase ) # load 🤗 model __lowercase : List[Any] = ASTForAudioClassification(__UpperCamelCase ) model.eval() model.load_state_dict(__UpperCamelCase ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 __lowercase : Dict = -4.2_677_393 if '''speech-commands''' not in model_name else -6.845_978 __lowercase : Union[str, Any] = 4.5_689_974 if '''speech-commands''' not in model_name else 5.5_654_526 __lowercase : Dict = 10_24 if '''speech-commands''' not in model_name else 1_28 __lowercase : int = ASTFeatureExtractor(mean=__UpperCamelCase , std=__UpperCamelCase , max_length=__UpperCamelCase ) if "speech-commands" in model_name: __lowercase : Tuple = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) __lowercase : str = dataset[0]['''audio''']['''array'''] else: __lowercase : Any = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) __lowercase ,__lowercase : List[str] = torchaudio.load(__UpperCamelCase ) __lowercase : Optional[Any] = waveform.squeeze().numpy() __lowercase : str = feature_extractor(__UpperCamelCase , sampling_rate=1_60_00 , return_tensors='''pt''' ) # forward pass __lowercase : Optional[Any] = model(**__UpperCamelCase ) __lowercase : str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": __lowercase : Dict = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": __lowercase : Tuple = torch.tensor([-1.1_986, -7.0_903, -8.2_718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": __lowercase : Tuple = torch.tensor([-2.6_128, -8.0_080, -9.4_344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": __lowercase : Union[str, Any] = torch.tensor([-1.5_080, -7.4_534, -8.8_917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": __lowercase : List[Any] = torch.tensor([-0.5_050, -6.5_833, -8.0_843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": __lowercase : str = torch.tensor([-0.3_826, -7.0_336, -8.2_413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": __lowercase : List[Any] = torch.tensor([-1.2_113, -6.9_101, -8.3_470] ) elif model_name == "ast-finetuned-speech-commands-v2": __lowercase : Optional[Any] = torch.tensor([6.1_589, -8.0_566, -8.7_984] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , __UpperCamelCase , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(__UpperCamelCase ) print(f"""Saving feature extractor to {pytorch_dump_folder_path}""" ) feature_extractor.save_pretrained(__UpperCamelCase ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(f"""MIT/{model_name}""" ) feature_extractor.push_to_hub(f"""MIT/{model_name}""" ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a_ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''check_bouncy() accepts only integer arguments''' ) UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ): if not 0 < percent < 100: raise ValueError('''solution() only accepts values from 0 to 100''' ) UpperCamelCase :Tuple = 0 UpperCamelCase :str = 1 while True: if check_bouncy(SCREAMING_SNAKE_CASE__ ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(99)}''')
658
0
"""simple docstring""" import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() A = logging.get_logger(__name__) def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: """simple docstring""" __UpperCAmelCase : int = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"encoder.deit.blocks.{i}.norm1.weight", f"encoder.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm1.bias", f"encoder.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.weight", f"encoder.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.attn.proj.bias", f"encoder.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.norm2.weight", f"encoder.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.norm2.bias", f"encoder.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.weight", f"encoder.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc1.bias", f"encoder.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append( (f"encoder.deit.blocks.{i}.mlp.fc2.weight", f"encoder.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"encoder.deit.blocks.{i}.mlp.fc2.bias", f"encoder.encoder.layer.{i}.output.dense.bias") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("encoder.deit.cls_token", "encoder.embeddings.cls_token"), ("encoder.deit.pos_embed", "encoder.embeddings.position_embeddings"), ("encoder.deit.patch_embed.proj.weight", "encoder.embeddings.patch_embeddings.projection.weight"), ("encoder.deit.patch_embed.proj.bias", "encoder.embeddings.patch_embeddings.projection.bias"), ("encoder.deit.norm.weight", "encoder.layernorm.weight"), ("encoder.deit.norm.bias", "encoder.layernorm.bias"), ] ) return rename_keys def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> int: """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) __UpperCAmelCase : Optional[Any] = state_dict.pop(f"encoder.deit.blocks.{i}.attn.qkv.weight" ) __UpperCAmelCase : List[Any] = in_proj_weight[ : encoder_config.hidden_size, : ] __UpperCAmelCase : List[str] = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] __UpperCAmelCase : List[Any] = in_proj_weight[ -encoder_config.hidden_size :, : ] def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Any: """simple docstring""" __UpperCAmelCase : str = dct.pop(UpperCamelCase ) __UpperCAmelCase : List[Any] = val def _UpperCamelCase ( UpperCamelCase ) -> str: """simple docstring""" if "handwritten" in checkpoint_url: __UpperCAmelCase : Any = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: __UpperCAmelCase : Any = "https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg" __UpperCAmelCase : Tuple = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ).convert("RGB" ) return im @torch.no_grad() def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> List[Any]: """simple docstring""" __UpperCAmelCase : List[str] = ViTConfig(image_size=384 , qkv_bias=UpperCamelCase ) __UpperCAmelCase : Any = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: __UpperCAmelCase : Optional[int] = 768 elif "large" in checkpoint_url: # use ViT-large encoder __UpperCAmelCase : Any = 1024 __UpperCAmelCase : int = 4096 __UpperCAmelCase : Tuple = 24 __UpperCAmelCase : Any = 16 __UpperCAmelCase : Union[str, Any] = 1024 else: raise ValueError("Should either find 'base' or 'large' in checkpoint URL" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: __UpperCAmelCase : List[str] = False __UpperCAmelCase : Any = "relu" __UpperCAmelCase : Any = 1024 __UpperCAmelCase : str = True __UpperCAmelCase : Any = False __UpperCAmelCase : Optional[int] = False # load HuggingFace model __UpperCAmelCase : Optional[Any] = ViTModel(UpperCamelCase , add_pooling_layer=UpperCamelCase ) __UpperCAmelCase : str = TrOCRForCausalLM(UpperCamelCase ) __UpperCAmelCase : Optional[int] = VisionEncoderDecoderModel(encoder=UpperCamelCase , decoder=UpperCamelCase ) model.eval() # load state_dict of original model, rename some keys __UpperCAmelCase : Optional[int] = torch.hub.load_state_dict_from_url(UpperCamelCase , map_location="cpu" , check_hash=UpperCamelCase )["model"] __UpperCAmelCase : Optional[Any] = create_rename_keys(UpperCamelCase , UpperCamelCase ) for src, dest in rename_keys: rename_key(UpperCamelCase , UpperCamelCase , UpperCamelCase ) read_in_q_k_v(UpperCamelCase , UpperCamelCase ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): __UpperCAmelCase : Optional[int] = state_dict.pop(UpperCamelCase ) if key.startswith("decoder" ) and "output_projection" not in key: __UpperCAmelCase : Any = val else: __UpperCAmelCase : int = val # load state dict model.load_state_dict(UpperCamelCase ) # Check outputs on an image __UpperCAmelCase : List[str] = ViTImageProcessor(size=encoder_config.image_size ) __UpperCAmelCase : Union[str, Any] = RobertaTokenizer.from_pretrained("roberta-large" ) __UpperCAmelCase : Dict = TrOCRProcessor(UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : Optional[Any] = processor(images=prepare_img(UpperCamelCase ) , return_tensors="pt" ).pixel_values # verify logits __UpperCAmelCase : Dict = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) __UpperCAmelCase : Optional[Any] = model(pixel_values=UpperCamelCase , decoder_input_ids=UpperCamelCase ) __UpperCAmelCase : List[Any] = outputs.logits __UpperCAmelCase : List[str] = torch.Size([1, 1, 5_0265] ) if "trocr-base-handwritten" in checkpoint_url: __UpperCAmelCase : str = torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: __UpperCAmelCase : int = torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: __UpperCAmelCase : str = torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: __UpperCAmelCase : Union[str, Any] = torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , UpperCamelCase , atol=1e-3 ), "First elements of logits not as expected" Path(UpperCamelCase ).mkdir(exist_ok=UpperCamelCase ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(UpperCamelCase ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(UpperCamelCase ) if __name__ == "__main__": A = argparse.ArgumentParser() parser.add_argument( """--checkpoint_url""", default="""https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt""", type=str, help="""URL 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.""" ) A = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
77
def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Union[str, Any] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) UpperCamelCase :str = hex_num[0] == '''-''' if is_negative: UpperCamelCase :Union[str, Any] = hex_num[1:] try: UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) UpperCamelCase :Dict = '''''' while int_num > 0: UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor SCREAMING_SNAKE_CASE_: Union[str, Any] =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): def __init__(self : List[Any] , *__a : Union[str, Any] , **__a : Tuple ): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
78
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase , UpperCamelCase :List[Any] = position UpperCamelCase :Any = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] UpperCamelCase :Dict = [] for position in positions: UpperCamelCase , UpperCamelCase :str = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(SCREAMING_SNAKE_CASE__ ) return permissible_positions def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): if is_complete(SCREAMING_SNAKE_CASE__ ): return True for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): UpperCamelCase , UpperCamelCase :Optional[int] = position if board[y][x] == 0: UpperCamelCase :Any = curr + 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ): return True UpperCamelCase :Union[str, Any] = 0 return False def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Tuple = 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ): return board UpperCamelCase :str = 0 UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
SCREAMING_SNAKE_CASE__ : Dict = 6_55_21 def _lowerCamelCase ( __lowerCamelCase ) -> int: '''simple docstring''' UpperCAmelCase__ : str = 1 UpperCAmelCase__ : Tuple = 0 for plain_chr in plain_text: UpperCAmelCase__ : int = (a + ord(__lowerCamelCase )) % MOD_ADLER UpperCAmelCase__ : List[str] = (b + a) % MOD_ADLER return (b << 16) | a
79
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('''foo.json''',)] ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :int = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = GenerationConfig() UpperCamelCase :List[str] = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = GenerationConfig() UpperCamelCase :Tuple = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Dict = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) UpperCamelCase :Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase ( cls ) -> Optional[Any]: UpperCamelCase :List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase ( cls ) -> Union[str, Any]: try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
658
0
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __UpperCamelCase ( _lowerCAmelCase ): __snake_case :Dict = 'char' __snake_case :List[Any] = 'bpe' __snake_case :int = 'wp' __UpperCamelCase : List[str] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __UpperCamelCase ( _lowerCAmelCase ): __snake_case :int = ['image_processor', 'char_tokenizer'] __snake_case :Dict = 'ViTImageProcessor' __snake_case :List[str] = 'MgpstrTokenizer' def __init__( self : Optional[int] , _lowerCAmelCase : List[str]=None , _lowerCAmelCase : int=None , **_lowerCAmelCase : Dict ) -> Dict: """simple docstring""" __lowercase = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , _lowerCAmelCase , ) __lowercase = kwargs.pop("""feature_extractor""" ) __lowercase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) __lowercase = tokenizer __lowercase = AutoTokenizer.from_pretrained("""gpt2""" ) __lowercase = AutoTokenizer.from_pretrained("""bert-base-uncased""" ) super().__init__(_lowerCAmelCase , _lowerCAmelCase ) def __call__( self : str , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : List[str]=None , **_lowerCAmelCase : List[str] ) -> Dict: """simple docstring""" if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: __lowercase = self.image_processor(_lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase ) if text is not None: __lowercase = self.char_tokenizer(_lowerCAmelCase , return_tensors=_lowerCAmelCase , **_lowerCAmelCase ) if text is None: return inputs elif images is None: return encodings else: __lowercase = encodings["""input_ids"""] return inputs def _a ( self : int , _lowerCAmelCase : int ) -> List[Any]: """simple docstring""" __lowercase , __lowercase , __lowercase = sequences __lowercase = char_preds.size(0 ) __lowercase , __lowercase = self._decode_helper(_lowerCAmelCase , """char""" ) __lowercase , __lowercase = self._decode_helper(_lowerCAmelCase , """bpe""" ) __lowercase , __lowercase = self._decode_helper(_lowerCAmelCase , """wp""" ) __lowercase = [] __lowercase = [] for i in range(_lowerCAmelCase ): __lowercase = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowercase = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowercase = scores.index(max(_lowerCAmelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowercase = {} __lowercase = final_strs __lowercase = final_scores __lowercase = char_strs __lowercase = bpe_strs __lowercase = wp_strs return out def _a ( self : str , _lowerCAmelCase : List[str] , _lowerCAmelCase : Union[str, Any] ) -> Tuple: """simple docstring""" if format == DecodeType.CHARACTER: __lowercase = self.char_decode __lowercase = 1 __lowercase = """[s]""" elif format == DecodeType.BPE: __lowercase = self.bpe_decode __lowercase = 2 __lowercase = """#""" elif format == DecodeType.WORDPIECE: __lowercase = self.wp_decode __lowercase = 102 __lowercase = """[SEP]""" else: raise ValueError(F'Format {format} is not supported.' ) __lowercase , __lowercase = [], [] __lowercase = pred_logits.size(0 ) __lowercase = pred_logits.size(1 ) __lowercase , __lowercase = pred_logits.topk(1 , dim=-1 , largest=_lowerCAmelCase , sorted=_lowerCAmelCase ) __lowercase = preds_index.view(-1 , _lowerCAmelCase )[:, 1:] __lowercase = decoder(_lowerCAmelCase ) __lowercase , __lowercase = torch.nn.functional.softmax(_lowerCAmelCase , dim=2 ).max(dim=2 ) __lowercase = preds_max_prob[:, 1:] for index in range(_lowerCAmelCase ): __lowercase = preds_str[index].find(_lowerCAmelCase ) __lowercase = preds_str[index][:pred_eos] __lowercase = preds_index[index].cpu().tolist() __lowercase = pred_index.index(_lowerCAmelCase ) if eos_token in pred_index else -1 __lowercase = preds_max_prob[index][: pred_eos_index + 1] __lowercase = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(_lowerCAmelCase ) conf_scores.append(_lowerCAmelCase ) return dec_strs, conf_scores def _a ( self : Optional[int] , _lowerCAmelCase : Any ) -> str: """simple docstring""" __lowercase = [seq.replace(""" """ , """""" ) for seq in self.char_tokenizer.batch_decode(_lowerCAmelCase )] return decode_strs def _a ( self : Union[str, Any] , _lowerCAmelCase : List[Any] ) -> int: """simple docstring""" return self.bpe_tokenizer.batch_decode(_lowerCAmelCase ) def _a ( self : str , _lowerCAmelCase : int ) -> Optional[Any]: """simple docstring""" __lowercase = [seq.replace(""" """ , """""" ) for seq in self.wp_tokenizer.batch_decode(_lowerCAmelCase )] return decode_strs
80
def _A ( SCREAMING_SNAKE_CASE__ : int ): if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
658
0
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _snake_case : List[Any] = 6_37_81_37.0 _snake_case : int = 6_35_67_52.31_42_45 _snake_case : Dict = 6_378_137 def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude __snake_case : Tuple = atan((1 - flattening) * tan(radians(__lowerCamelCase ) ) ) __snake_case : List[Any] = atan((1 - flattening) * tan(radians(__lowerCamelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius __snake_case : Union[str, Any] = haversine_distance(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values __snake_case : Tuple = (b_lata + b_lata) / 2 __snake_case : Union[str, Any] = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) __snake_case : Tuple = (sin(__lowerCamelCase ) ** 2) * (cos(__lowerCamelCase ) ** 2) __snake_case : Union[str, Any] = cos(sigma / 2 ) ** 2 __snake_case : Optional[int] = (sigma - sin(__lowerCamelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) __snake_case : int = (cos(__lowerCamelCase ) ** 2) * (sin(__lowerCamelCase ) ** 2) __snake_case : Tuple = sin(sigma / 2 ) ** 2 __snake_case : Any = (sigma + sin(__lowerCamelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
81
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __snake_case = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M' UpperCamelCase_ : Optional[Any] =( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) UpperCamelCase_ : Dict ='translator' UpperCamelCase_ : Any =AutoTokenizer UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM UpperCamelCase_ : List[Any] =LANGUAGE_CODES UpperCamelCase_ : int =['text', 'text', 'text'] UpperCamelCase_ : Union[str, Any] =['text'] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: if src_lang not in self.lang_to_code: raise ValueError(F'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'''{tgt_lang} is not a supported language.''' ) UpperCamelCase :Optional[int] = self.lang_to_code[src_lang] UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
658
0
"""simple docstring""" import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() lowerCamelCase = 2 class lowercase__ : '''simple docstring''' def __init__( self : Union[str, Any] , *, # begin keyword-only arguments _UpperCAmelCase : Optional[Any]="<s>" , _UpperCAmelCase : List[Any]="<pad>" , _UpperCAmelCase : List[Any]="</s>" , _UpperCAmelCase : Union[str, Any]="<unk>" , _UpperCAmelCase : Union[str, Any]=None , ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = bos, unk, pad, eos UpperCAmelCase_ = [] UpperCAmelCase_ = [] UpperCAmelCase_ = {} UpperCAmelCase_ = self.add_symbol(_UpperCAmelCase ) UpperCAmelCase_ = self.add_symbol(_UpperCAmelCase ) UpperCAmelCase_ = self.add_symbol(_UpperCAmelCase ) UpperCAmelCase_ = self.add_symbol(_UpperCAmelCase ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(_UpperCAmelCase ) UpperCAmelCase_ = len(self.symbols ) def __eq__( self : int , _UpperCAmelCase : int ) -> Optional[int]: '''simple docstring''' return self.indices == other.indices def __getitem__( self : Optional[int] , _UpperCAmelCase : str ) -> Tuple: '''simple docstring''' if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : Tuple ) -> str: '''simple docstring''' return len(self.symbols ) def __contains__( self : List[str] , _UpperCAmelCase : Optional[int] ) -> Optional[Any]: '''simple docstring''' return sym in self.indices @classmethod def lowercase__ ( cls : Tuple , _UpperCAmelCase : int ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = cls() d.add_from_file(_UpperCAmelCase ) return d def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict=1 , _UpperCAmelCase : List[str]=False ) -> List[str]: '''simple docstring''' if word in self.indices and not overwrite: UpperCAmelCase_ = self.indices[word] UpperCAmelCase_ = self.count[idx] + n return idx else: UpperCAmelCase_ = len(self.symbols ) UpperCAmelCase_ = idx self.symbols.append(_UpperCAmelCase ) self.count.append(_UpperCAmelCase ) return idx def lowercase__ ( self : Optional[int] , _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: '''simple docstring''' return 0 def lowercase__ ( self : Optional[Any] , _UpperCAmelCase : Dict ) -> str: '''simple docstring''' if isinstance(_UpperCAmelCase , _UpperCAmelCase ): try: with open(_UpperCAmelCase , "r" , encoding="utf-8" ) as fd: self.add_from_file(_UpperCAmelCase ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception("Incorrect encoding detected in {}, please rebuild the dataset".format(_UpperCAmelCase ) ) return UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = self._load_meta(_UpperCAmelCase ) for line in lines[indices_start_line:]: try: UpperCAmelCase_ , UpperCAmelCase_ = line.rstrip().rsplit(" " , 1 ) if field == "#fairseq:overwrite": UpperCAmelCase_ = True UpperCAmelCase_ , UpperCAmelCase_ = line.rsplit(" " , 1 ) else: UpperCAmelCase_ = False UpperCAmelCase_ = int(_UpperCAmelCase ) UpperCAmelCase_ = line if word in self and not overwrite: raise RuntimeError( "Duplicate word found when loading Dictionary: '{}'. " "Duplicate words can overwrite earlier ones by adding the " "#fairseq:overwrite flag at the end of the corresponding row " "in the dictionary file. If using the Camembert model, please " "download an updated copy of the model file.".format(_UpperCAmelCase ) ) self.add_symbol(_UpperCAmelCase , n=_UpperCAmelCase , overwrite=_UpperCAmelCase ) except ValueError: raise ValueError("Incorrect dictionary format, expected '<token> <cnt> [flags]'" ) def a__ ( lowerCAmelCase__ ): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} UpperCAmelCase_ = dict((re.sub(r"@@$" , "" , lowerCAmelCase__ ), v) if k.endswith("@@" ) else (re.sub(r"$" , "</w>" , lowerCAmelCase__ ), v) for k, v in d.items() ) UpperCAmelCase_ = "<s> <pad> </s> <unk>".split() # restore the special tokens for k in keep_keys: del da[f"""{k}</w>"""] UpperCAmelCase_ = d[k] # restore return da def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): # prep if not os.path.exists(lowerCAmelCase__ ): raise ValueError(f"""path {biogpt_checkpoint_path} does not exist!""" ) os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) print(f"""Writing results to {pytorch_dump_folder_path}""" ) # handle various types of models UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , "checkpoint.pt" ) if not os.path.isfile(lowerCAmelCase__ ): raise ValueError(f"""path to the file {checkpoint_file} does not exist!""" ) UpperCAmelCase_ = torch.load(lowerCAmelCase__ , map_location="cpu" ) UpperCAmelCase_ = chkpt["cfg"]["model"] # dicts UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , "dict.txt" ) if not os.path.isfile(lowerCAmelCase__ ): raise ValueError(f"""path to the file {dict_file} does not exist!""" ) UpperCAmelCase_ = Dictionary.load(lowerCAmelCase__ ) UpperCAmelCase_ = rewrite_dict_keys(src_dict.indices ) UpperCAmelCase_ = len(lowerCAmelCase__ ) UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , VOCAB_FILES_NAMES["vocab_file"] ) print(f"""Generating {src_vocab_file} of {src_vocab_size} records""" ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ , indent=lowerCAmelCase__ ) ) # merges_file (bpecodes) UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , "bpecodes" ) if not os.path.isfile(lowerCAmelCase__ ): raise ValueError(f"""path to the file {bpecodes_file} does not exist!""" ) UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , VOCAB_FILES_NAMES["merges_file"] ) shutil.copyfile(lowerCAmelCase__ , lowerCAmelCase__ ) # model config UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , "config.json" ) UpperCAmelCase_ = { "activation_dropout": args["activation_dropout"], "architectures": ["BioGptForCausalLM"], "attention_probs_dropout_prob": args["attention_dropout"], "bos_token_id": 0, "eos_token_id": 2, "hidden_act": args["activation_fn"], "hidden_dropout_prob": args["dropout"], "hidden_size": args["decoder_embed_dim"], "initializer_range": 0.02, "intermediate_size": args["decoder_ffn_embed_dim"], "layer_norm_eps": 1e-12, "layerdrop": args["decoder_layerdrop"], "max_position_embeddings": args["max_target_positions"], "model_type": "biogpt", "num_attention_heads": args["decoder_attention_heads"], "num_hidden_layers": args["decoder_layers"], "pad_token_id": 1, "scale_embedding": not args["no_scale_embedding"], "tie_word_embeddings": args["share_decoder_input_output_embed"], "vocab_size": src_vocab_size, } # good hparam defaults to start with print(f"""Generating {biogpt_model_config_file}""" ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ , indent=lowerCAmelCase__ ) ) # tokenizer config UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase_ = { "bos_token": "<s>", "eos_token": "</s>", "model_max_length": 1024, "pad_token": "<pad>", "special_tokens_map_file": None, "tokenizer_class": "BioGptTokenizer", "unk_token": "<unk>", } print(f"""Generating {biogpt_tokenizer_config_file}""" ) with open(lowerCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ , indent=lowerCAmelCase__ ) ) # model UpperCAmelCase_ = chkpt["model"] # remove unneeded keys UpperCAmelCase_ = [ "decoder.version", ] for k in ignore_keys: model_state_dict.pop(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCAmelCase_ = list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith("output_projection.weight" ): UpperCAmelCase_ = model_state_dict.pop(lowerCAmelCase__ ) else: UpperCAmelCase_ = model_state_dict.pop(lowerCAmelCase__ ) UpperCAmelCase_ = BioGptConfig.from_pretrained(lowerCAmelCase__ ) UpperCAmelCase_ = BioGptForCausalLM(lowerCAmelCase__ ) # check that it loads ok model_new.load_state_dict(lowerCAmelCase__ ) # save UpperCAmelCase_ = os.path.join(lowerCAmelCase__ , lowerCAmelCase__ ) print(f"""Generating {pytorch_weights_dump_path}""" ) torch.save(lowerCAmelCase__ , lowerCAmelCase__ ) print("Conversion is done!" ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( """--biogpt_checkpoint_path""", default=None, type=str, required=True, help=( """Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,""" """ bpecodes, etc.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCamelCase = parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
82
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __snake_case = 10 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if array[i] == target: return i return -1 def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Tuple = 0 UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1 UpperCamelCase :str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase :int = one_third - 1 elif array[two_third] < target: UpperCamelCase :Any = two_third + 1 else: UpperCamelCase :Any = one_third + 1 UpperCamelCase :int = two_third - 1 else: return -1 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = (left + right) // 3 + 1 UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __snake_case = input("""Enter numbers separated by comma:\n""").strip() __snake_case = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __snake_case = int(input("""Enter the number to be found in the list:\n""").strip()) __snake_case = ite_ternary_search(collection, target) __snake_case = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
658
0
"""simple docstring""" import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py lowerCAmelCase__ = '''.''' # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) lowerCAmelCase__ = [ '''Assert''', '''AssignVariableOp''', '''EmptyTensorList''', '''MergeV2Checkpoints''', '''ReadVariableOp''', '''ResourceGather''', '''RestoreV2''', '''SaveV2''', '''ShardedFilename''', '''StatefulPartitionedCall''', '''StaticRegexFullMatch''', '''VarHandleOp''', ] def snake_case_ ( A_ : int, A_ : Optional[Any], A_ : str ): '''simple docstring''' _lowerCamelCase : List[str] = SavedModel() _lowerCamelCase : Dict = [] with open(os.path.join(A_, '''utils''', '''tf_ops''', '''onnx.json''' ) ) as f: _lowerCamelCase : List[Any] = json.load(A_ )['''opsets'''] for i in range(1, opset + 1 ): onnx_ops.extend(onnx_opsets[str(A_ )] ) with open(A_, '''rb''' ) as f: saved_model.ParseFromString(f.read() ) _lowerCamelCase : List[str] = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want _lowerCamelCase : int = sorted(A_ ) _lowerCamelCase : List[str] = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(A_ ) if strict and len(A_ ) > 0: raise Exception(F'''Found the following incompatible ops for the opset {opset}:\n''' + incompatible_ops ) elif len(A_ ) > 0: print(F'''Found the following incompatible ops for the opset {opset}:''' ) print(*A_, sep='''\n''' ) else: print(F'''The saved model {saved_model_path} can properly be converted with ONNX.''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--saved_model_path''', help='''Path of the saved model to check (the .pb file).''') parser.add_argument( '''--opset''', default=12, type=int, help='''The ONNX opset against which the model has to be tested.''' ) parser.add_argument( '''--framework''', choices=['''onnx'''], default='''onnx''', help='''Frameworks against which to test the saved model.''' ) parser.add_argument( '''--strict''', action='''store_true''', help='''Whether make the checking strict (raise errors) or not (raise warnings)''' ) lowerCAmelCase__ = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
83
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 UpperCamelCase :Union[str, Any] = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Dict = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :str = max_revenue return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )] UpperCamelCase :Dict = 0 for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Tuple = max_revenue_i return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): if n < 0: UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :str = 36 UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
658
0
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger UpperCAmelCase = get_logger(__name__) class A_ ( enum.Enum ): '''simple docstring''' _UpperCamelCase : Tuple = """all_checks""" _UpperCamelCase : Optional[Any] = """basic_checks""" _UpperCamelCase : str = """no_checks""" class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) ) if len(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedDownloadedFile(str(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) ) lowercase = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] lowercase = ' for ' + verification_name if verification_name is not None else '' if len(__SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingChecksumError( F'''Checksums didn\'t match{for_verification_name}:\n''' F'''{bad_urls}\n''' 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' class A_ ( __lowerCamelCase ): '''simple docstring''' def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreSplits(str(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) ) if len(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedSplits(str(set(__SCREAMING_SNAKE_CASE ) - set(__SCREAMING_SNAKE_CASE ) ) ) lowercase = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(__SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingSplitsSizesError(str(__SCREAMING_SNAKE_CASE ) ) logger.info('All the splits matched successfully.' ) def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True ): if record_checksum: lowercase = shaaaa() with open(__SCREAMING_SNAKE_CASE , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b'' ): m.update(__SCREAMING_SNAKE_CASE ) lowercase = m.hexdigest() else: lowercase = None return {"num_bytes": os.path.getsize(__SCREAMING_SNAKE_CASE ), "checksum": checksum} def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE ): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
84
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase, lowercase ): """simple docstring""" UpperCamelCase_ : int ='focalnet' def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = image_size UpperCamelCase :Dict = patch_size UpperCamelCase :Tuple = num_channels UpperCamelCase :int = embed_dim UpperCamelCase :Optional[Any] = use_conv_embed UpperCamelCase :str = hidden_sizes UpperCamelCase :str = depths UpperCamelCase :Optional[int] = focal_levels UpperCamelCase :Tuple = focal_windows UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Optional[int] = mlp_ratio UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :int = drop_path_rate UpperCamelCase :Dict = use_layerscale UpperCamelCase :List[str] = layerscale_value UpperCamelCase :Tuple = use_post_layernorm UpperCamelCase :int = use_post_layernorm_in_modulation UpperCamelCase :str = normalize_modulator UpperCamelCase :Any = initializer_range UpperCamelCase :Optional[Any] = layer_norm_eps UpperCamelCase :Dict = encoder_stride UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
658
0
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :Union[str, Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Any = patch_size UpperCamelCase :List[str] = num_channels UpperCamelCase :int = is_training UpperCamelCase :str = use_labels UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = backbone_out_indices UpperCamelCase :str = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :int = backbone_featmap_shape UpperCamelCase :Any = scope UpperCamelCase :int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Dict = (image_size // patch_size) ** 2 UpperCamelCase :List[str] = num_patches + 1 def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Tuple =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Tuple =False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Union[str, Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Any = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = False UpperCamelCase :List[Any] = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Any: pass @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = prepare_img() UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :int = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __a :Optional[Any] = '2.13.1' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('3.7'): raise ImportWarning( 'To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( 'To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n' 'If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip __a :List[str] = concatenate_datasets __a :Optional[Any] = DownloadConfig __a :Any = DownloadManager __a :Any = DownloadMode __a :Any = DownloadConfig __a :int = DownloadMode __a :Union[str, Any] = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
86
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Union[str, Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: UpperCamelCase :Any = 128 elif "12-12" in model_name: UpperCamelCase :Union[str, Any] = 12 UpperCamelCase :Any = 12 elif "14-14" in model_name: UpperCamelCase :Optional[int] = 14 UpperCamelCase :List[str] = 14 elif "16-16" in model_name: UpperCamelCase :List[Any] = 16 UpperCamelCase :Optional[Any] = 16 else: raise ValueError('''Model not supported''' ) UpperCamelCase :Tuple = '''huggingface/label-files''' if "speech-commands" in model_name: UpperCamelCase :Optional[Any] = 35 UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json''' else: UpperCamelCase :Optional[int] = 527 UpperCamelCase :List[Any] = '''audioset-id2label.json''' UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): if "module.v" in name: UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ): for key in orig_state_dict.copy().keys(): UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: UpperCamelCase :Any = key.split('''.''' ) UpperCamelCase :str = int(key_split[3] ) UpperCamelCase :Union[str, Any] = config.hidden_size if "weight" in key: UpperCamelCase :List[str] = val[:dim, :] UpperCamelCase :Optional[Any] = val[dim : dim * 2, :] UpperCamelCase :Optional[Any] = val[-dim:, :] else: UpperCamelCase :Dict = val[:dim] UpperCamelCase :Optional[int] = val[dim : dim * 2] UpperCamelCase :List[Any] = val[-dim:] else: UpperCamelCase :Union[str, Any] = val return orig_state_dict def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[str] = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ): UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict UpperCamelCase :Optional[int] = model_name_to_url[model_name] UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE__ ) # rename some keys UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load 🤗 model UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78 UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26 UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128 UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) if "speech-commands" in model_name: UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array'''] else: UpperCamelCase :List[Any] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = waveform.squeeze().numpy() UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' ) # forward pass UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] ) elif model_name == "ast-finetuned-speech-commands-v2": UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
658
0
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse("""0.8.3"""): raise Exception("""requires gluonnlp == 0.8.3""") if version.parse(mx.__version__) != version.parse("""1.5.0"""): raise Exception("""requires mxnet == 1.5.0""") logging.set_verbosity_info() _lowerCamelCase : Dict = logging.get_logger(__name__) _lowerCamelCase : int = """The Nymphenburg Palace is a beautiful palace in Munich!""" def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Optional[int]: """simple docstring""" A__ = { '''attention_cell''': '''multi_head''', '''num_layers''': 4, '''units''': 1_024, '''hidden_size''': 768, '''max_length''': 512, '''num_heads''': 8, '''scaled''': True, '''dropout''': 0.1, '''use_residual''': True, '''embed_size''': 1_024, '''embed_dropout''': 0.1, '''word_embed''': None, '''layer_norm_eps''': 1E-5, '''token_type_vocab_size''': 2, } A__ = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py A__ = BERTEncoder( attention_cell=predefined_args['''attention_cell'''] , num_layers=predefined_args['''num_layers'''] , units=predefined_args['''units'''] , hidden_size=predefined_args['''hidden_size'''] , max_length=predefined_args['''max_length'''] , num_heads=predefined_args['''num_heads'''] , scaled=predefined_args['''scaled'''] , dropout=predefined_args['''dropout'''] , output_attention=lowercase_ , output_all_encodings=lowercase_ , use_residual=predefined_args['''use_residual'''] , activation=predefined_args.get('''activation''' , '''gelu''' ) , layer_norm_eps=predefined_args.get('''layer_norm_eps''' , lowercase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later A__ = '''openwebtext_ccnews_stories_books_cased''' # Specify download folder to Gluonnlp's vocab A__ = os.path.join(get_home_dir() , '''models''' ) A__ = _load_vocab(lowercase_ , lowercase_ , lowercase_ , cls=lowercase_ ) A__ = nlp.model.BERTModel( lowercase_ , len(lowercase_ ) , units=predefined_args['''units'''] , embed_size=predefined_args['''embed_size'''] , embed_dropout=predefined_args['''embed_dropout'''] , word_embed=predefined_args['''word_embed'''] , use_pooler=lowercase_ , use_token_type_embed=lowercase_ , token_type_vocab_size=predefined_args['''token_type_vocab_size'''] , use_classifier=lowercase_ , use_decoder=lowercase_ , ) original_bort.load_parameters(lowercase_ , cast_dtype=lowercase_ , ignore_extra=lowercase_ ) A__ = original_bort._collect_params_with_prefix() # Build our config 🤗 A__ = { '''architectures''': ['''BertForMaskedLM'''], '''attention_probs_dropout_prob''': predefined_args['''dropout'''], '''hidden_act''': '''gelu''', '''hidden_dropout_prob''': predefined_args['''dropout'''], '''hidden_size''': predefined_args['''embed_size'''], '''initializer_range''': 0.02, '''intermediate_size''': predefined_args['''hidden_size'''], '''layer_norm_eps''': predefined_args['''layer_norm_eps'''], '''max_position_embeddings''': predefined_args['''max_length'''], '''model_type''': '''bort''', '''num_attention_heads''': predefined_args['''num_heads'''], '''num_hidden_layers''': predefined_args['''num_layers'''], '''pad_token_id''': 1, # 2 = BERT, 1 = RoBERTa '''type_vocab_size''': 1, # 2 = BERT, 1 = RoBERTa '''vocab_size''': len(lowercase_ ), } A__ = BertConfig.from_dict(lowercase_ ) A__ = BertForMaskedLM(lowercase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowercase_ ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowercase_ , lowercase_ ): A__ = hf_param.shape A__ = to_torch(params[gluon_param] ) A__ = gluon_param.shape assert ( shape_hf == shape_gluon ), f"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param A__ = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , '''word_embed.0.weight''' ) A__ = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , '''encoder.position_weight''' ) A__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , '''encoder.layer_norm.beta''' ) A__ = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , '''encoder.layer_norm.gamma''' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) A__ = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): A__ = hf_bort_model.bert.encoder.layer[i] # self attention A__ = layer.attention.self A__ = check_and_map_params( self_attn.key.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) A__ = check_and_map_params( self_attn.key.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) A__ = check_and_map_params( self_attn.query.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) A__ = check_and_map_params( self_attn.query.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) A__ = check_and_map_params( self_attn.value.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) A__ = check_and_map_params( self_attn.value.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output A__ = layer.attention.output A__ = check_and_map_params( self_output.dense.bias , f"""encoder.transformer_cells.{i}.proj.bias""" ) A__ = check_and_map_params( self_output.dense.weight , f"""encoder.transformer_cells.{i}.proj.weight""" ) A__ = check_and_map_params( self_output.LayerNorm.bias , f"""encoder.transformer_cells.{i}.layer_norm.beta""" ) A__ = check_and_map_params( self_output.LayerNorm.weight , f"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate A__ = layer.intermediate A__ = check_and_map_params( intermediate.dense.bias , f"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) A__ = check_and_map_params( intermediate.dense.weight , f"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output A__ = layer.output A__ = check_and_map_params( bert_output.dense.bias , f"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) A__ = check_and_map_params( bert_output.dense.weight , f"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) A__ = check_and_map_params( bert_output.LayerNorm.bias , f"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) A__ = check_and_map_params( bert_output.LayerNorm.weight , f"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models A__ = RobertaTokenizer.from_pretrained('''roberta-base''' ) A__ = tokenizer.encode_plus(lowercase_ )['''input_ids'''] # Get gluon output A__ = mx.nd.array([input_ids] ) A__ = original_bort(inputs=lowercase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowercase_ ) A__ = BertModel.from_pretrained(lowercase_ ) hf_bort_model.eval() A__ = tokenizer.encode_plus(lowercase_ , return_tensors='''pt''' ) A__ = hf_bort_model(**lowercase_ )[0] A__ = output_gluon[0].asnumpy() A__ = output_hf[0].detach().numpy() A__ = np.max(np.abs(hf_layer - gluon_layer ) ).item() A__ = np.allclose(lowercase_ , lowercase_ , atol=1E-3 ) if success: print('''✔️ Both model do output the same tensors''' ) else: print('''❌ Both model do **NOT** output the same tensors''' ) print('''Absolute difference is:''' , lowercase_ ) if __name__ == "__main__": _lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--bort_checkpoint_path""", default=None, type=str, required=True, help="""Path the official Bort params file.""" ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) _lowerCamelCase : str = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
87
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
"""simple docstring""" from ... import PretrainedConfig UpperCAmelCase = { """sijunhe/nezha-cn-base""": """https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json""", } class lowercase__ ( A_ ): __UpperCAmelCase = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP __UpperCAmelCase = '''nezha''' def __init__( self , SCREAMING_SNAKE_CASE=2_1128 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=64 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-1_2 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=True , **SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE , bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Dict = vocab_size _lowerCamelCase : Tuple = hidden_size _lowerCamelCase : Dict = num_hidden_layers _lowerCamelCase : List[Any] = num_attention_heads _lowerCamelCase : Any = hidden_act _lowerCamelCase : Dict = intermediate_size _lowerCamelCase : List[str] = hidden_dropout_prob _lowerCamelCase : int = attention_probs_dropout_prob _lowerCamelCase : List[str] = max_position_embeddings _lowerCamelCase : Dict = max_relative_position _lowerCamelCase : Union[str, Any] = type_vocab_size _lowerCamelCase : int = initializer_range _lowerCamelCase : Tuple = layer_norm_eps _lowerCamelCase : Union[str, Any] = classifier_dropout _lowerCamelCase : str = use_cache
88
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = """\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ __snake_case = """\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ __snake_case = R""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Tuple = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0 UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ ) return { "accuracy": accuracy, }
658
0
SCREAMING_SNAKE_CASE : List[str] = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" SCREAMING_SNAKE_CASE : str = [{"type": "code", "content": INSTALL_CONTENT}] SCREAMING_SNAKE_CASE : Optional[int] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
89
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def _A ( ): UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase :Dict = parser.parse_args() return args.f def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ): UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) raise ValueError(F'''can\'t find {path}''' ) __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = self.get_auto_remove_tmp_dir() UpperCamelCase :Any = F''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :List[str] = F''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :int = F''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def UpperCAmelCase ( self ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2 UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[int] = F''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :Dict = F''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
658
0
'''simple docstring''' # 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 __UpperCAmelCase = '''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)
90
from __future__ import annotations from collections.abc import Callable def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ): UpperCamelCase :Optional[Any] = x_start UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCamelCase :Any = (x_end - x_start) / steps + xa UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCamelCase :Optional[int] = xa UpperCamelCase :List[str] = fxa return area if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE__ : int ): return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 10_00_00: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
658
0
"""simple docstring""" import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: # A mock response for an HTTP head request to emulate server down A = mock.Mock() A = 500 A = {} A = HTTPError A = {} # Download this model to make sure it's in the cache. A = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=A_ ) as mock_head: A = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : int ) -> Optional[int]: # A mock response for an HTTP head request to emulate server down A = mock.Mock() A = 500 A = {} A = HTTPError A = {} # Download this model to make sure it's in the cache. A = GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=A_ ) as mock_head: A = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _SCREAMING_SNAKE_CASE ( self : Any ) -> int: # This test is for deprecated behavior and can be removed in v5 try: A = tempfile.mktemp() with open(A_ ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,A_ ) A = AlbertTokenizer.from_pretrained(A_ ) finally: os.remove(A_ ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,A_ ) A = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Any: # This test is for deprecated behavior and can be removed in v5 A = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ) -> Optional[Any]: A = TOKEN HfFolder.save_token(A_ ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ) -> List[Any]: try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizer(A_ ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(A_ ,repo_id='test-tokenizer' ,push_to_hub=A_ ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained(F'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizer(A_ ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( A_ ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=A_ ,use_auth_token=self._token ) A = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = CustomTokenizer(A_ ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) A = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: A = os.path.join(A_ ,'vocab.txt' ) with open(A_ ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) A = BertTokenizerFast.from_pretrained(A_ ) bert_tokenizer.save_pretrained(A_ ) A = CustomTokenizerFast.from_pretrained(A_ ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) A = AutoTokenizer.from_pretrained(F'{USER}/test-dynamic-tokenizer' ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) A = AutoTokenizer.from_pretrained( F'{USER}/test-dynamic-tokenizer' ,use_fast=A_ ,trust_remote_code=A_ ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: A = Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> List[Any]: A = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _SCREAMING_SNAKE_CASE ( self : str ) -> List[str]: A = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]: A = Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _SCREAMING_SNAKE_CASE ( self : Any ) -> Tuple: A = Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: A = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: A = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> List[str]: # Even if the offsets are wrong, we necessarily output correct string # parts. A = Trie() A = trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(A_ ,['AB', 'C'] )
91
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :str = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = 10 UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps[0] UpperCamelCase :Union[str, Any] = scheduler.timesteps[1] UpperCamelCase :str = self.dummy_sample UpperCamelCase :List[str] = 0.1 * sample UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase ( self ) -> List[str]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # 1. scale model input UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :Tuple = pred_prev_sample UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = scheduler.timesteps UpperCamelCase :int = torch.manual_seed(0 ) UpperCamelCase :str = self.dummy_model() UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :int = pred_prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :Tuple = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = [39, 30, 12, 1, 0] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[int] = self.scheduler_classes[0] UpperCamelCase :List[str] = self.get_scheduler_config() UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
658
0
'''simple docstring''' import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __init__( self : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any]=13 , UpperCAmelCase__ : Union[str, Any]=7 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Tuple=99 , UpperCAmelCase__ : Tuple=32 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Optional[int]=37 , UpperCAmelCase__ : Optional[Any]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Optional[int]=512 , UpperCAmelCase__ : Optional[int]=16 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : List[Any]=4 , ): '''simple docstring''' lowercase : str =parent lowercase : Tuple =batch_size lowercase : List[Any] =seq_length lowercase : str =is_training lowercase : Optional[Any] =use_attention_mask lowercase : Union[str, Any] =use_token_type_ids lowercase : int =use_labels lowercase : Optional[int] =vocab_size lowercase : Any =hidden_size lowercase : Dict =num_hidden_layers lowercase : Optional[Any] =num_attention_heads lowercase : List[str] =intermediate_size lowercase : Dict =hidden_act lowercase : List[Any] =hidden_dropout_prob lowercase : Union[str, Any] =attention_probs_dropout_prob lowercase : Any =max_position_embeddings lowercase : str =type_vocab_size lowercase : List[str] =type_sequence_label_size lowercase : Optional[int] =initializer_range lowercase : Any =num_choices def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' lowercase : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase : Optional[int] =None if self.use_attention_mask: lowercase : str =random_attention_mask([self.batch_size, self.seq_length] ) lowercase : Union[str, Any] =None if self.use_token_type_ids: lowercase : List[str] =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase : Any =RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase : List[Any] =self.prepare_config_and_inputs() lowercase , lowercase , lowercase , lowercase : List[Any] =config_and_inputs lowercase : List[Any] ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def lowerCamelCase_ ( self : str ): '''simple docstring''' lowercase : str =self.prepare_config_and_inputs() lowercase , lowercase , lowercase , lowercase : Dict =config_and_inputs lowercase : Any =True lowercase : List[Any] =floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowercase : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): lowerCamelCase_ = True lowerCamelCase_ = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase_ ( self : Optional[Any] ): '''simple docstring''' lowercase : Optional[Any] =FlaxRobertaModelTester(self ) @slow def lowerCamelCase_ ( self : Tuple ): '''simple docstring''' for model_class_name in self.all_model_classes: lowercase : str =model_class_name.from_pretrained('''roberta-base''' , from_pt=UpperCAmelCase__ ) lowercase : Optional[int] =model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCAmelCase__ )
92
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = tempfile.mkdtemp() lowerCAmelCase__ :Union[str, Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] lowerCAmelCase__ :List[str] = 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] ) ) lowerCAmelCase__ :Tuple = { 'do_resize': True, 'size': {'height': 2_2_4, 'width': 2_2_4}, 'do_center_crop': True, 'crop_size': {'height': 1_8, 'width': 1_8}, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], 'do_convert_rgb': True, } lowerCAmelCase__ :List[Any] = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] lowerCAmelCase__ :str = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.get_tokenizer() lowerCAmelCase__ :Any = self.get_rust_tokenizer() lowerCAmelCase__ :List[Any] = self.get_image_processor() lowerCAmelCase__ :Any = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :List[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) lowerCAmelCase__ :str = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Tuple = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , __UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Any = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) lowerCAmelCase__ :Union[str, Any] = self.get_image_processor(do_normalize=__UpperCAmelCase ) lowerCAmelCase__ :Dict = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=__UpperCAmelCase ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.get_image_processor() lowerCAmelCase__ :int = self.get_tokenizer() lowerCAmelCase__ :Optional[int] = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Any = self.prepare_image_inputs() lowerCAmelCase__ :int = image_processor(__UpperCAmelCase , return_tensors='np' ) lowerCAmelCase__ :List[Any] = processor(images=__UpperCAmelCase , 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 snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[int] = self.get_image_processor() lowerCAmelCase__ :str = self.get_tokenizer() lowerCAmelCase__ :Any = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Any = 'Alexandra,T-shirt的价格是15便士。' lowerCAmelCase__ :str = processor(text=__UpperCAmelCase ) lowerCAmelCase__ :List[str] = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.get_image_processor() lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :Optional[int] = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :int = 'Alexandra,T-shirt的价格是15便士。' lowerCAmelCase__ :int = self.prepare_image_inputs() lowerCAmelCase__ :List[str] = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = self.get_image_processor() lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :Union[str, Any] = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase__ :str = processor.batch_decode(__UpperCAmelCase ) lowerCAmelCase__ :Dict = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :str = self.get_image_processor() lowerCAmelCase__ :Optional[int] = self.get_tokenizer() lowerCAmelCase__ :List[str] = ChineseCLIPProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :str = 'Alexandra,T-shirt的价格是15便士。' lowerCAmelCase__ :Optional[Any] = self.prepare_image_inputs() lowerCAmelCase__ :Dict = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
93
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: return None class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: return None class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =[ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[int]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> int: from transformers import BertModel UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCAmelCase ( self ) -> str: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[str]: from transformers import BertModel UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' ) @require_tf @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[Any]: from transformers import TFBertModel UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
658
0
'''simple docstring''' import argparse import re from pathlib import Path import requests import torch from PIL import Image from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor from transformers import ( EfficientFormerConfig, EfficientFormerForImageClassificationWithTeacher, EfficientFormerImageProcessor, ) from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def lowercase_ ( __A : List[str] , __A : List[Any] ) -> int: """simple docstring""" lowercase : Tuple =old_name if "patch_embed" in old_name: lowercase , lowercase , lowercase : List[Any] =old_name.split('''.''' ) if layer == "0": lowercase : int =old_name.replace('''0''' , '''convolution1''' ) elif layer == "1": lowercase : List[Any] =old_name.replace('''1''' , '''batchnorm_before''' ) elif layer == "3": lowercase : Union[str, Any] =old_name.replace('''3''' , '''convolution2''' ) else: lowercase : Tuple =old_name.replace('''4''' , '''batchnorm_after''' ) if "network" in old_name and re.search(R'''\d\.\d''' , __A ): lowercase : int =R'''\b\d{2}\b''' if bool(re.search(__A , __A ) ): lowercase : int =re.search(R'''\d\.\d\d.''' , __A ).group() else: lowercase : Union[str, Any] =re.search(R'''\d\.\d.''' , __A ).group() if int(match[0] ) < 6: lowercase : Tuple =old_name.replace(__A , '''''' ) lowercase : str =trimmed_name.replace('''network''' , match[0] + '''.meta4D_layers.blocks.''' + match[2:-1] ) lowercase : Dict ='''intermediate_stages.''' + trimmed_name else: lowercase : int =old_name.replace(__A , '''''' ) if int(match[2] ) < num_meta4D_last_stage: lowercase : Tuple =trimmed_name.replace('''network''' , '''meta4D_layers.blocks.''' + match[2] ) else: lowercase : Optional[Any] =str(int(match[2] ) - num_meta4D_last_stage ) lowercase : List[str] =trimmed_name.replace('''network''' , '''meta3D_layers.blocks.''' + layer_index ) if "norm1" in old_name: lowercase : Union[str, Any] =trimmed_name.replace('''norm1''' , '''layernorm1''' ) elif "norm2" in old_name: lowercase : Union[str, Any] =trimmed_name.replace('''norm2''' , '''layernorm2''' ) elif "fc1" in old_name: lowercase : List[Any] =trimmed_name.replace('''fc1''' , '''linear_in''' ) elif "fc2" in old_name: lowercase : Dict =trimmed_name.replace('''fc2''' , '''linear_out''' ) lowercase : List[Any] ='''last_stage.''' + trimmed_name elif "network" in old_name and re.search(R'''.\d.''' , __A ): lowercase : Dict =old_name.replace('''network''' , '''intermediate_stages''' ) if "fc" in new_name: lowercase : Union[str, Any] =new_name.replace('''fc''' , '''convolution''' ) elif ("norm1" in new_name) and ("layernorm1" not in new_name): lowercase : Optional[int] =new_name.replace('''norm1''' , '''batchnorm_before''' ) elif ("norm2" in new_name) and ("layernorm2" not in new_name): lowercase : str =new_name.replace('''norm2''' , '''batchnorm_after''' ) if "proj" in new_name: lowercase : int =new_name.replace('''proj''' , '''projection''' ) if "dist_head" in new_name: lowercase : Optional[int] =new_name.replace('''dist_head''' , '''distillation_classifier''' ) elif "head" in new_name: lowercase : List[str] =new_name.replace('''head''' , '''classifier''' ) elif "patch_embed" in new_name: lowercase : List[Any] ='''efficientformer.''' + new_name elif new_name == "norm.weight" or new_name == "norm.bias": lowercase : List[Any] =new_name.replace('''norm''' , '''layernorm''' ) lowercase : Union[str, Any] ='''efficientformer.''' + new_name else: lowercase : Any ='''efficientformer.encoder.''' + new_name return new_name def lowercase_ ( __A : Union[str, Any] , __A : int ) -> Dict: """simple docstring""" for key in checkpoint.copy().keys(): lowercase : List[Any] =checkpoint.pop(__A ) lowercase : str =val return checkpoint def lowercase_ ( ) -> int: """simple docstring""" lowercase : Dict ='''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase : Union[str, Any] =Image.open(requests.get(__A , stream=__A ).raw ) return image def lowercase_ ( __A : Path , __A : Path , __A : Path , __A : bool ) -> int: """simple docstring""" lowercase : Optional[int] =torch.load(__A , map_location='''cpu''' )['''model'''] lowercase : List[Any] =EfficientFormerConfig.from_json_file(__A ) lowercase : List[str] =EfficientFormerForImageClassificationWithTeacher(__A ) lowercase : List[str] ='''_'''.join(checkpoint_path.split('''/''' )[-1].split('''.''' )[0].split('''_''' )[:-1] ) lowercase : Optional[int] =config.depths[-1] - config.num_metaad_blocks + 1 lowercase : List[Any] =convert_torch_checkpoint(__A , __A ) model.load_state_dict(__A ) model.eval() lowercase : List[str] ={ '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } # prepare image lowercase : int =prepare_img() lowercase : List[str] =2_5_6 lowercase : int =2_2_4 lowercase : Union[str, Any] =EfficientFormerImageProcessor( size={'''shortest_edge''': image_size} , crop_size={'''height''': crop_size, '''width''': crop_size} , resample=pillow_resamplings['''bicubic'''] , ) lowercase : List[str] =processor(images=__A , return_tensors='''pt''' ).pixel_values # original processing pipeline lowercase : int =Compose( [ Resize(__A , interpolation=pillow_resamplings['''bicubic'''] ), CenterCrop(__A ), ToTensor(), Normalize(__A , __A ), ] ) lowercase : Tuple =image_transforms(__A ).unsqueeze(0 ) assert torch.allclose(__A , __A ) lowercase : Any =model(__A ) lowercase : Union[str, Any] =outputs.logits lowercase : List[Any] =(1, 1_0_0_0) if "l1" in model_name: lowercase : Optional[Any] =torch.Tensor( [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328] ) assert torch.allclose(logits[0, :1_0] , __A , atol=1E-3 ) assert logits.shape == expected_shape elif "l3" in model_name: lowercase : List[Any] =torch.Tensor( [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127] ) assert torch.allclose(logits[0, :1_0] , __A , atol=1E-3 ) assert logits.shape == expected_shape elif "l7" in model_name: lowercase : Any =torch.Tensor( [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878] ) assert logits.shape == expected_shape else: raise ValueError( F'Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7' ) # Save Checkpoints Path(__A ).mkdir(exist_ok=__A ) model.save_pretrained(__A ) print(F'Checkpoint successfuly converted. Model saved at {pytorch_dump_path}' ) processor.save_pretrained(__A ) print(F'Processor successfuly saved at {pytorch_dump_path}' ) if push_to_hub: print('''Pushing model to the hub...''' ) model.push_to_hub( repo_id=F'Bearnardd/{pytorch_dump_path}' , commit_message='''Add model''' , use_temp_dir=__A , ) processor.push_to_hub( repo_id=F'Bearnardd/{pytorch_dump_path}' , commit_message='''Add image processor''' , use_temp_dir=__A , ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to EfficientFormer pytorch checkpoint.', ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for EfficientFormer model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') parser.add_argument( '--no-push_to_hub', dest='push_to_hub', action='store_false', help='Do not push model and image processor to the hub', ) parser.set_defaults(push_to_hub=True) SCREAMING_SNAKE_CASE = parser.parse_args() convert_efficientformer_checkpoint( checkpoint_path=args.pytorch_model_path, efficientformer_config_file=args.config_file, pytorch_dump_path=args.pytorch_dump_path, push_to_hub=args.push_to_hub, )
94
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Union[str, Any] = tempfile.mkdtemp() UpperCamelCase :List[str] = 5 # Realm tok UpperCamelCase :List[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , 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] ) ) UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def UpperCAmelCase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records ) return config def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Tuple = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=SCREAMING_SNAKE_CASE_ , ) return block_records def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Optional[int] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[Any] = self.get_config() UpperCamelCase :str = self.get_dummy_retriever() UpperCamelCase :int = retriever.tokenizer UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' ) UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Tuple = tokenizer( ['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Optional[Any] = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = self.get_config() UpperCamelCase :Union[str, Any] = self.get_dummy_retriever() UpperCamelCase :Dict = retriever.tokenizer UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' ) UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Optional[Any] = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Any = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: UpperCamelCase :Tuple = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
658
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } lowerCamelCase_ = { '''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''}, '''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''}, '''tokenizer_config_file''': { '''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json''' }, } lowerCamelCase_ = {'''facebook/blenderbot-3B''': 128} class UpperCamelCase_ (__A ): __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = ['''input_ids''', '''attention_mask'''] __magic_name__ = BlenderbotTokenizer def __init__( self : List[str] , lowerCAmelCase_ : List[Any]=None , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : str=None , lowerCAmelCase_ : List[Any]="replace" , lowerCAmelCase_ : List[Any]="<s>" , lowerCAmelCase_ : Tuple="</s>" , lowerCAmelCase_ : str="</s>" , lowerCAmelCase_ : List[str]="<s>" , lowerCAmelCase_ : int="<unk>" , lowerCAmelCase_ : Any="<pad>" , lowerCAmelCase_ : str="<mask>" , lowerCAmelCase_ : Optional[int]=False , lowerCAmelCase_ : Dict=True , **lowerCAmelCase_ : Any , ) -> Dict: super().__init__( lowerCAmelCase_ , lowerCAmelCase_ , tokenizer_file=lowerCAmelCase_ , errors=lowerCAmelCase_ , bos_token=lowerCAmelCase_ , eos_token=lowerCAmelCase_ , sep_token=lowerCAmelCase_ , cls_token=lowerCAmelCase_ , unk_token=lowerCAmelCase_ , pad_token=lowerCAmelCase_ , mask_token=lowerCAmelCase_ , add_prefix_space=lowerCAmelCase_ , trim_offsets=lowerCAmelCase_ , **lowerCAmelCase_ , ) UpperCAmelCase_ : Optional[int] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCAmelCase_ ) != add_prefix_space: UpperCAmelCase_ : str = getattr(lowerCAmelCase_ , pre_tok_state.pop("type" ) ) UpperCAmelCase_ : Optional[Any] = add_prefix_space UpperCAmelCase_ : Any = pre_tok_class(**lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = add_prefix_space UpperCAmelCase_ : Union[str, Any] = "post_processor" UpperCAmelCase_ : Dict = getattr(self.backend_tokenizer , lowerCAmelCase_ , lowerCAmelCase_ ) if tokenizer_component_instance: UpperCAmelCase_ : Any = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCAmelCase_ : Optional[Any] = tuple(state["sep"] ) if "cls" in state: UpperCAmelCase_ : Union[str, Any] = tuple(state["cls"] ) UpperCAmelCase_ : str = False if state.get("add_prefix_space" , lowerCAmelCase_ ) != add_prefix_space: UpperCAmelCase_ : List[str] = add_prefix_space UpperCAmelCase_ : Union[str, Any] = True if state.get("trim_offsets" , lowerCAmelCase_ ) != trim_offsets: UpperCAmelCase_ : Any = trim_offsets UpperCAmelCase_ : Any = True if changes_to_apply: UpperCAmelCase_ : int = getattr(lowerCAmelCase_ , state.pop("type" ) ) UpperCAmelCase_ : Dict = component_class(**lowerCAmelCase_ ) setattr(self.backend_tokenizer , lowerCAmelCase_ , lowerCAmelCase_ ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase_ : Tuple ) -> Tuple: UpperCAmelCase_ : Optional[Any] = AddedToken(lowerCAmelCase_ , lstrip=lowerCAmelCase_ , rstrip=lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else value UpperCAmelCase_ : Any = value def _SCREAMING_SNAKE_CASE ( self : Optional[int] , *lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : List[str] ) -> BatchEncoding: UpperCAmelCase_ : List[Any] = kwargs.get("is_split_into_words" , lowerCAmelCase_ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , *lowerCAmelCase_ : List[str] , **lowerCAmelCase_ : Tuple ) -> BatchEncoding: UpperCAmelCase_ : Optional[int] = kwargs.get("is_split_into_words" , lowerCAmelCase_ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCAmelCase_ , **lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Optional[str] = None ) -> Tuple[str]: UpperCAmelCase_ : Union[str, Any] = self._tokenizer.model.save(lowerCAmelCase_ , name=lowerCAmelCase_ ) return tuple(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> List[int]: UpperCAmelCase_ : Dict = [self.sep_token_id] UpperCAmelCase_ : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase_ : List[int] , lowerCAmelCase_ : Optional[List[int]] = None ) -> Optional[Any]: return token_ids_a + [self.eos_token_id] def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : "Conversation" ) -> List[int]: UpperCAmelCase_ : Tuple = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(" " + text ) else: # Generated responses should contain them already. inputs.append(lowerCAmelCase_ ) UpperCAmelCase_ : Dict = " ".join(lowerCAmelCase_ ) UpperCAmelCase_ : List[str] = self.encode(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > self.model_max_length: UpperCAmelCase_ : Optional[int] = input_ids[-self.model_max_length :] logger.warning(f"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
95
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]: UpperCamelCase :int = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[int] = max_length UpperCamelCase :Union[str, Any] = num_mel_bins UpperCamelCase :Optional[int] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :Dict = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :str = num_attention_heads UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :str = type_sequence_label_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = scope UpperCamelCase :List[Any] = frequency_stride UpperCamelCase :Tuple = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension UpperCamelCase :Optional[int] = num_patches + 2 def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :str = self.get_config() return config, input_values, labels def UpperCAmelCase ( self ) -> List[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :List[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) UpperCamelCase_ : Any =( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[Any] =False UpperCamelCase_ : Dict =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = ASTModelTester(self ) UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> str: pass def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Any = [*signature.parameters.keys()] UpperCamelCase :Optional[int] = ['''input_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Optional[int]: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Any = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase ( self ) -> Tuple: return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.default_feature_extractor UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = self.default_feature_extractor UpperCamelCase , UpperCamelCase :Dict = prepare_audio() UpperCamelCase :Dict = audio.squeeze().numpy() UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase :List[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
"""simple docstring""" from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def a ( __UpperCAmelCase : str ) -> None: __magic_name__, __magic_name__: Union[str, Any] = analyze_text(__UpperCAmelCase ) __magic_name__: int = list(""" """ + ascii_lowercase ) # what is our total sum of probabilities. __magic_name__: Optional[int] = sum(single_char_strings.values() ) # one length string __magic_name__: List[Any] = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: __magic_name__: List[Any] = single_char_strings[ch] __magic_name__: str = my_str / all_sum my_fir_sum += prob * math.loga(__UpperCAmelCase ) # entropy formula. # print entropy print(f'{round(-1 * my_fir_sum ):.1f}' ) # two len string __magic_name__: Tuple = sum(two_char_strings.values() ) __magic_name__: List[Any] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: __magic_name__: Dict = cha + cha if sequence in two_char_strings: __magic_name__: Optional[int] = two_char_strings[sequence] __magic_name__: Dict = int(__UpperCAmelCase ) / all_sum my_sec_sum += prob * math.loga(__UpperCAmelCase ) # print second entropy print(f'{round(-1 * my_sec_sum ):.1f}' ) # print the difference between them print(f'{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}' ) def a ( __UpperCAmelCase : str ) -> tuple[dict, dict]: __magic_name__: Dict = Counter() # type: ignore __magic_name__: str = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(__UpperCAmelCase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def a ( ) -> Dict: import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
96
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): UpperCamelCase :Dict = [image] if isinstance(image[0] , PIL.Image.Image ): UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0 UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 ) UpperCamelCase :Tuple = 2.0 * image - 1.0 UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ): if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): UpperCamelCase :int = True UpperCamelCase :Dict = va.device UpperCamelCase :List[Any] = va.cpu().numpy() UpperCamelCase :str = va.cpu().numpy() UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: UpperCamelCase :Any = (1 - t) * va + t * va else: UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = theta_a * t UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a UpperCamelCase :Union[str, Any] = sa * va + sa * va if inputs_are_torch: UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ): for param in model.parameters(): UpperCamelCase :Any = value class UpperCAmelCase_ ( lowercase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str: super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = ( feature_extractor.size if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ ) else feature_extractor.size['''shortest_edge'''] ) UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ ) set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: # get the original timestep using init_timestep UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int: if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ ) ] UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) else: UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[str] = 0.1_8215 * init_latents UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) # get latents UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = init_latents return latents def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: UpperCamelCase :List[str] = latents.detach().requires_grad_() UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep] UpperCamelCase :Optional[int] = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = self.scheduler.sigmas[index] UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :int = 1 / 0.1_8215 * sample UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype ) UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = latents.detach() + grads * (sigma**2) UpperCamelCase :Optional[Any] = noise_pred_original else: UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1: UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1) UpperCamelCase :Tuple = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]] UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ ) if style_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ ) # get prompt text embeddings for content and style UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # duplicate text embeddings for each generation per prompt UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # set timesteps UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) UpperCamelCase :List[str] = {} if accepts_offset: UpperCamelCase :Tuple = 1 self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ ) # Preprocess image UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if clip_guidance_scale > 0: UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = slerp( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase :Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase :Any = content_text_input.input_ids.shape[-1] UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase :int = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase :int = 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}''' ) UpperCamelCase :str = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase :Dict = {} if accepts_eta: UpperCamelCase :int = eta # check if the scheduler accepts generator UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: UpperCamelCase :List[str] = generator with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ): for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # expand the latents if we are doing classifier free guidance UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform classifier free guidance if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 ) UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: UpperCamelCase :int = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) UpperCamelCase , UpperCamelCase :str = self.cond_fn( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
658
0
import random from typing import Any def a ( snake_case__: list ): '''simple docstring''' for _ in range(len(snake_case__ ) ): lowercase_ = random.randint(0 , len(snake_case__ ) - 1 ) lowercase_ = random.randint(0 , len(snake_case__ ) - 1 ) lowercase_ , lowercase_ = data[b], data[a] return data if __name__ == "__main__": __a = [0, 1, 2, 3, 4, 5, 6, 7] __a = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
97
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :list[list[int]] = [] UpperCamelCase :list[int] = [] UpperCamelCase :List[str] = 0 UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) __snake_case = [3, 34, 4, 12, 5, 2] __snake_case = 9 __snake_case = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
658
0
'''simple docstring''' import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline lowercase__ : Dict = datasets.utils.logging.get_logger(__name__) @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): """simple docstring""" _snake_case : Optional[datasets.Features] = None _snake_case : str = "utf-8" _snake_case : Optional[str] = None _snake_case : Optional[str] = None _snake_case : bool = True # deprecated _snake_case : Optional[int] = None # deprecated _snake_case : int = 1_0 << 2_0 # 10MB _snake_case : Optional[bool] = None class __lowerCAmelCase ( datasets.ArrowBasedBuilder ): """simple docstring""" _snake_case : int = JsonConfig def snake_case__ ( self : str ) -> List[str]: '''simple docstring''' if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) _UpperCamelCase = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def snake_case__ ( self : Tuple , lowerCAmelCase__ : Optional[int] ) -> List[str]: '''simple docstring''' if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) _UpperCamelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(lowerCAmelCase__ , (str, list, tuple) ): _UpperCamelCase = data_files if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCamelCase = [files] _UpperCamelCase = [dl_manager.iter_files(lowerCAmelCase__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] _UpperCamelCase = [] for split_name, files in data_files.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): _UpperCamelCase = [files] _UpperCamelCase = [dl_manager.iter_files(lowerCAmelCase__ ) for file in files] splits.append(datasets.SplitGenerator(name=lowerCAmelCase__ , gen_kwargs={'''files''': files} ) ) return splits def snake_case__ ( self : Any , lowerCAmelCase__ : pa.Table ) -> pa.Table: '''simple docstring''' if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): _UpperCamelCase = self.config.features.arrow_schema.field(lowerCAmelCase__ ).type _UpperCamelCase = pa_table.append_column(lowerCAmelCase__ , pa.array([None] * len(lowerCAmelCase__ ) , type=lowerCAmelCase__ ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example _UpperCamelCase = table_cast(lowerCAmelCase__ , self.config.features.arrow_schema ) return pa_table def snake_case__ ( self : List[Any] , lowerCAmelCase__ : int ) -> List[str]: '''simple docstring''' for file_idx, file in enumerate(itertools.chain.from_iterable(lowerCAmelCase__ ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(lowerCAmelCase__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCamelCase = json.load(lowerCAmelCase__ ) # We keep only the field we are interested in _UpperCamelCase = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(lowerCAmelCase__ , (list, tuple) ): _UpperCamelCase = set().union(*[row.keys() for row in dataset] ) _UpperCamelCase = {col: [row.get(lowerCAmelCase__ ) for row in dataset] for col in keys} else: _UpperCamelCase = dataset _UpperCamelCase = pa.Table.from_pydict(lowerCAmelCase__ ) yield file_idx, self._cast_table(lowerCAmelCase__ ) # If the file has one json object per line else: with open(lowerCAmelCase__ , '''rb''' ) as f: _UpperCamelCase = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small _UpperCamelCase = max(self.config.chunksize // 32 , 16 << 10 ) _UpperCamelCase = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: _UpperCamelCase = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(lowerCAmelCase__ ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": _UpperCamelCase = batch.decode(self.config.encoding , errors=lowerCAmelCase__ ).encode('''utf-8''' ) try: while True: try: _UpperCamelCase = paj.read_json( io.BytesIO(lowerCAmelCase__ ) , read_options=paj.ReadOptions(block_size=lowerCAmelCase__ ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(lowerCAmelCase__ , pa.ArrowInvalid ) and "straddling" not in str(lowerCAmelCase__ ) or block_size > len(lowerCAmelCase__ ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f"""Batch of {len(lowerCAmelCase__ )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.""" ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( lowerCAmelCase__ , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCamelCase = json.load(lowerCAmelCase__ ) except json.JSONDecodeError: logger.error(f"""Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}""" ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): # list is the only sequence type supported in JSON try: _UpperCamelCase = set().union(*[row.keys() for row in dataset] ) _UpperCamelCase = {col: [row.get(lowerCAmelCase__ ) for row in dataset] for col in keys} _UpperCamelCase = pa.Table.from_pydict(lowerCAmelCase__ ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f"""Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}""" ) raise ValueError(f"""Not able to read records in the JSON file at {file}.""" ) from None yield file_idx, self._cast_table(lowerCAmelCase__ ) break else: logger.error(f"""Failed to read file '{file}' with error {type(lowerCAmelCase__ )}: {e}""" ) raise ValueError( f"""Not able to read records in the JSON file at {file}. """ f"""You should probably indicate the field of the JSON file containing your records. """ f"""This JSON file contain the following fields: {str(list(dataset.keys() ) )}. """ f"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """ ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(lowerCAmelCase__ ) batch_idx += 1
98
def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''check_bouncy() accepts only integer arguments''' ) UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ): if not 0 < percent < 100: raise ValueError('''solution() only accepts values from 0 to 100''' ) UpperCamelCase :Tuple = 0 UpperCamelCase :str = 1 while True: if check_bouncy(SCREAMING_SNAKE_CASE__ ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(99)}''')
658
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = torch.device('cpu') def a (): __a = """http://images.cocodataset.org/val2017/000000039769.jpg""" __a = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im def a (lowerCAmelCase__ ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3E0_0, 2.1_1_0_7E0_0, -2.0_8_1_1E0_0, 8.8_6_8_5E-0_1, 2.4_3_6_0E-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6E-0_1, 2.3_4_7_8E-0_1, -1.6_9_6_3E0_0, -1.7_3_8_1E0_0, -8.6_3_3_7E-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8E-0_1, -4.7_4_2_9E-0_1, -1.0_8_9_7E0_0, -1.0_2_4_8E0_0, 3.5_5_2_3E-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0E-0_1, 2.4_2_1_1E-0_1, -6.0_1_8_5E-0_1, -8.2_7_8_9E-0_1, -6.0_4_4_6E-0_2] ) def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): __a = dct.pop(lowerCAmelCase__ ) __a = val def a (lowerCAmelCase__ ): __a = [] for k in state_dict.keys(): __a = k if ".pwconv" in k: __a = k_new.replace(""".pwconv""" , """.point_wise_conv""" ) if ".dwconv" in k: __a = k_new.replace(""".dwconv""" , """.depth_wise_conv""" ) if ".Proj." in k: __a = k_new.replace(""".Proj.""" , """.proj.""" ) if "patch_embed" in k_new: __a = k_new.replace("""patch_embed""" , """swiftformer.patch_embed.patch_embedding""" ) if "network" in k_new: __a = k_new.split(""".""" ) if ls[2].isdigit(): __a = """swiftformer.encoder.network.""" + ls[1] + """.blocks.""" + ls[2] + """.""" + """.""".join(ls[3:] ) else: __a = k_new.replace("""network""" , """swiftformer.encoder.network""" ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def a (lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): __a = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __a = 1_000 __a = """huggingface/label-files""" __a = """imagenet-1k-id2label.json""" __a = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) __a = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __a = [3, 3, 6, 4] __a = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __a = [3, 3, 9, 6] __a = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __a = [4, 3, 10, 5] __a = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __a = [4, 4, 12, 6] __a = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith("""https""" ): __a = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location="""cpu""" , check_hash=lowerCAmelCase__ ) else: __a = torch.load(lowerCAmelCase__ , map_location="""cpu""" ) __a = checkpoint __a = create_rename_keys(lowerCAmelCase__ ) for rename_key_src, rename_key_dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # load HuggingFace model __a = SwiftFormerForImageClassification(lowerCAmelCase__ ).eval() hf_model.load_state_dict(lowerCAmelCase__ ) # prepare test inputs __a = prepare_img() __a = ViTImageProcessor.from_pretrained("""preprocessor_config""" ) __a = processor(images=lowerCAmelCase__ , return_tensors="""pt""" ) # compare outputs from both models __a = get_expected_output(lowerCAmelCase__ ) __a = hf_model(inputs["""pixel_values"""] ).logits assert hf_logits.shape == torch.Size([1, 1_000] ) assert torch.allclose(hf_logits[0, 0:5] , lowerCAmelCase__ , atol=1E-3 ) Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(f'''Saving model {swiftformer_name} to {pytorch_dump_folder_path}''' ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swiftformer_name', default='swiftformer_xs', choices=['swiftformer_xs', 'swiftformer_s', 'swiftformer_l1', 'swiftformer_l3'], type=str, help='Name of the SwiftFormer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='./converted_outputs/', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--original_ckpt', default=None, type=str, help='Path to the original model checkpoint.') SCREAMING_SNAKE_CASE = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
99
def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Union[str, Any] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) UpperCamelCase :str = hex_num[0] == '''-''' if is_negative: UpperCamelCase :Union[str, Any] = hex_num[1:] try: UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) UpperCamelCase :Dict = '''''' while int_num > 0: UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
def __snake_case ( lowerCAmelCase_ = 1_0_0_0 ) -> int: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1, 1 SCREAMING_SNAKE_CASE__ = [] for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ = prev_numerator + 2 * prev_denominator SCREAMING_SNAKE_CASE__ = prev_numerator + prev_denominator if len(str(lowerCAmelCase_ ) ) > len(str(lowerCAmelCase_ ) ): result.append(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE__ = numerator SCREAMING_SNAKE_CASE__ = denominator return len(lowerCAmelCase_ ) if __name__ == "__main__": print(F'{solution() = }')
100
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase , UpperCamelCase :List[Any] = position UpperCamelCase :Any = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] UpperCamelCase :Dict = [] for position in positions: UpperCamelCase , UpperCamelCase :str = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(SCREAMING_SNAKE_CASE__ ) return permissible_positions def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): if is_complete(SCREAMING_SNAKE_CASE__ ): return True for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): UpperCamelCase , UpperCamelCase :Optional[int] = position if board[y][x] == 0: UpperCamelCase :Any = curr + 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ): return True UpperCamelCase :Union[str, Any] = 0 return False def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Tuple = 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ): return board UpperCamelCase :str = 0 UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ : Tuple =[ 'word_embeddings_layernorm.weight', 'word_embeddings_layernorm.bias', 'input_layernorm.weight', 'input_layernorm.bias', 'post_attention_layernorm.weight', 'post_attention_layernorm.bias', 'self_attention.dense.bias', 'mlp.dense_4h_to_h.bias', 'ln_f.weight', 'ln_f.bias', ] lowerCAmelCase__ : Optional[Any] =[ 'mlp.dense_4h_to_h.weight', 'self_attention.dense.weight', ] def a__ ( A__, A__ ): SCREAMING_SNAKE_CASE_ : str = { 'word_embeddings.weight': 'word_embeddings.weight', 'word_embeddings.norm.weight': 'word_embeddings_layernorm.weight', 'word_embeddings.norm.bias': 'word_embeddings_layernorm.bias', 'weight': 'ln_f.weight', 'bias': 'ln_f.bias', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks SCREAMING_SNAKE_CASE_ : Optional[Any] = int(re.match(r'.*layer_(\d*).*', A__ )[1] ) layer_number -= 3 return F'''h.{layer_number}.''' + key def a__ ( A__ ): if dtype == torch.bool: return 1 / 8 SCREAMING_SNAKE_CASE_ : str = re.search(r'[^\d](\d+)$', str(A__ ) ) if bit_search is None: raise ValueError(F'''`dtype` is not a valid dtype: {dtype}.''' ) SCREAMING_SNAKE_CASE_ : Dict = int(bit_search.groups()[0] ) return bit_size // 8 def a__ ( A__, A__, A__, A__, A__ ): # Construct model if bloom_config_file == "": SCREAMING_SNAKE_CASE_ : Optional[int] = BloomConfig() else: SCREAMING_SNAKE_CASE_ : Optional[Any] = BloomConfig.from_json_file(A__ ) if shard_model: SCREAMING_SNAKE_CASE_ : str = os.listdir(A__ ) SCREAMING_SNAKE_CASE_ : str = sorted(filter(lambda A__ : s.startswith('layer' ) and "model_00" in s, A__ ) ) SCREAMING_SNAKE_CASE_ : Tuple = {'weight_map': {}, 'metadata': {}} SCREAMING_SNAKE_CASE_ : int = 0 SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Union[str, Any] = BloomConfig() for j, file in enumerate(A__ ): print('Processing file: {}'.format(A__ ) ) SCREAMING_SNAKE_CASE_ : Dict = None for i in range(A__ ): # load all TP files SCREAMING_SNAKE_CASE_ : Optional[Any] = file.replace('model_00', F'''model_0{i}''' ) SCREAMING_SNAKE_CASE_ : List[Any] = torch.load(os.path.join(A__, A__ ), map_location='cpu' ) # Rename keys in the transformers names SCREAMING_SNAKE_CASE_ : Dict = list(temp.keys() ) for key in keys: SCREAMING_SNAKE_CASE_ : Optional[Any] = temp.pop(A__ ) if tensors is None: SCREAMING_SNAKE_CASE_ : Tuple = temp else: for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel SCREAMING_SNAKE_CASE_ : int = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks SCREAMING_SNAKE_CASE_ : Optional[int] = torch.cat([tensors[key], temp[key]], dim=A__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): SCREAMING_SNAKE_CASE_ : Optional[int] = tensors[key] / pretraining_tp torch.save( A__, os.path.join( A__, 'pytorch_model_{}-of-{}.bin'.format(str(j + 1 ).zfill(5 ), str(len(A__ ) ).zfill(5 ) ), ), ) for key in tensors.keys(): SCREAMING_SNAKE_CASE_ : str = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: SCREAMING_SNAKE_CASE_ : List[Any] = 'pytorch_model_{}-of-{}.bin'.format( str(j + 1 ).zfill(5 ), str(len(A__ ) ).zfill(5 ) ) SCREAMING_SNAKE_CASE_ : Any = BloomConfig() SCREAMING_SNAKE_CASE_ : str = pytorch_dump_folder_path + '/' + CONFIG_NAME SCREAMING_SNAKE_CASE_ : Union[str, Any] = total_size with open(A__, 'w', encoding='utf-8' ) as f: f.write(config.to_json_string() ) with open(os.path.join(A__, WEIGHTS_NAME + '.index.json' ), 'w', encoding='utf-8' ) as f: SCREAMING_SNAKE_CASE_ : Dict = json.dumps(A__, indent=2, sort_keys=A__ ) + '\n' f.write(A__ ) else: SCREAMING_SNAKE_CASE_ : Tuple = BloomModel(A__ ) SCREAMING_SNAKE_CASE_ : int = os.listdir(A__ ) SCREAMING_SNAKE_CASE_ : Tuple = sorted(filter(lambda A__ : s.startswith('layer' ) and "model_00" in s, A__ ) ) SCREAMING_SNAKE_CASE_ : Tuple = None for i, file in enumerate(A__ ): SCREAMING_SNAKE_CASE_ : Dict = None for i in range(A__ ): # load all TP files SCREAMING_SNAKE_CASE_ : Dict = file.replace('model_00', F'''model_0{i}''' ) SCREAMING_SNAKE_CASE_ : Tuple = torch.load(os.path.join(A__, A__ ), map_location='cpu' ) # Rename keys in the transformers names SCREAMING_SNAKE_CASE_ : str = list(temp.keys() ) for key in keys: SCREAMING_SNAKE_CASE_ : int = temp.pop(A__ ) if tensors is None: SCREAMING_SNAKE_CASE_ : List[Any] = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel SCREAMING_SNAKE_CASE_ : Dict = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.cat([tensors[key], temp[key]], dim=A__ ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(A__ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): SCREAMING_SNAKE_CASE_ : Any = tensors[key] / pretraining_tp SCREAMING_SNAKE_CASE_ : Any = model.load_state_dict(A__, strict=A__ ) assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected''' if missing_keys is None: SCREAMING_SNAKE_CASE_ : Tuple = set(other_keys.missing_keys ) else: SCREAMING_SNAKE_CASE_ : str = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F'''The keys {missing_keys} are missing''' # Save pytorch-model os.makedirs(A__, exist_ok=A__ ) SCREAMING_SNAKE_CASE_ : Any = pytorch_dump_folder_path + '/' + WEIGHTS_NAME SCREAMING_SNAKE_CASE_ : List[str] = pytorch_dump_folder_path + '/' + CONFIG_NAME print(F'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}''' ) if config.torch_dtype is not None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = model.to(config.torch_dtype ) torch.save(model.state_dict(), A__ ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(A__, 'w', encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": lowerCAmelCase__ : Optional[Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '--bloom_checkpoint_path', default=None, type=str, required=True, help='Path to the Megatron-LM checkpoint path.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--bloom_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--shard_model', action='store_true', help='An optional setting to shard the output model \nThis enables sharding the converted checkpoint', ) parser.add_argument( '--pretraining_tp', default=4, type=int, help='Pretraining TP rank that has been used when training the model in Megatron-LM \n', ) lowerCAmelCase__ : List[str] =parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
101
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('''foo.json''',)] ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :int = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = GenerationConfig() UpperCamelCase :List[str] = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = GenerationConfig() UpperCamelCase :Tuple = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Dict = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) UpperCamelCase :Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase ( cls ) -> Optional[Any]: UpperCamelCase :List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase ( cls ) -> Union[str, Any]: try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
658
0
"""simple docstring""" # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def UpperCamelCase (*SCREAMING_SNAKE_CASE ): with open(SCREAMING_SNAKE_CASE , """r""" ) as fh: fcntl.flock(SCREAMING_SNAKE_CASE , fcntl.LOCK_EX ) try: print(*SCREAMING_SNAKE_CASE ) finally: fcntl.flock(SCREAMING_SNAKE_CASE , fcntl.LOCK_UN ) __magic_name__ : str = int(os.environ["""LOCAL_RANK"""]) torch.cuda.set_device(local_rank) __magic_name__ : Optional[int] = torch.device("""cuda""", local_rank) __magic_name__ : List[Any] = socket.gethostname() __magic_name__ : Dict = f'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group("""nccl""") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __magic_name__ : Any = dist.get_rank() __magic_name__ : Optional[Any] = dist.get_world_size() printflock(f'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(f'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(f'''{gpu} is broken''') raise
102
def _A ( SCREAMING_SNAKE_CASE__ : int ): if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
658
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case = logging.get_logger(__name__) snake_case = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } snake_case = { '''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''}, '''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''}, '''tokenizer_config_file''': { '''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json''' }, } snake_case = {'''facebook/blenderbot-3B''': 1_2_8} class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): A__ : Dict = VOCAB_FILES_NAMES A__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP A__ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : int = ['''input_ids''', '''attention_mask'''] A__ : int = BlenderbotTokenizer def __init__( self : Union[str, Any] , __lowerCamelCase : Tuple=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : List[str]="replace" , __lowerCamelCase : Dict="<s>" , __lowerCamelCase : Optional[Any]="</s>" , __lowerCamelCase : Dict="</s>" , __lowerCamelCase : Any="<s>" , __lowerCamelCase : int="<unk>" , __lowerCamelCase : str="<pad>" , __lowerCamelCase : str="<mask>" , __lowerCamelCase : Union[str, Any]=False , __lowerCamelCase : Optional[int]=True , **__lowerCamelCase : List[Any] , ): """simple docstring""" super().__init__( __lowerCamelCase , __lowerCamelCase , tokenizer_file=__lowerCamelCase , errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase , **__lowerCamelCase , ) _snake_case = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __lowerCamelCase ) != add_prefix_space: _snake_case = getattr(__lowerCamelCase , pre_tok_state.pop('''type''' ) ) _snake_case = add_prefix_space _snake_case = pre_tok_class(**__lowerCamelCase ) _snake_case = add_prefix_space _snake_case = '''post_processor''' _snake_case = getattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) if tokenizer_component_instance: _snake_case = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: _snake_case = tuple(state['''sep'''] ) if "cls" in state: _snake_case = tuple(state['''cls'''] ) _snake_case = False if state.get('''add_prefix_space''' , __lowerCamelCase ) != add_prefix_space: _snake_case = add_prefix_space _snake_case = True if state.get('''trim_offsets''' , __lowerCamelCase ) != trim_offsets: _snake_case = trim_offsets _snake_case = True if changes_to_apply: _snake_case = getattr(__lowerCamelCase , state.pop('''type''' ) ) _snake_case = component_class(**__lowerCamelCase ) setattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : Any ): """simple docstring""" _snake_case = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else value _snake_case = value def __UpperCAmelCase ( self : Optional[int] , *__lowerCamelCase : Optional[int] , **__lowerCamelCase : Optional[Any] ): """simple docstring""" _snake_case = kwargs.get('''is_split_into_words''' , __lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def __UpperCAmelCase ( self : int , *__lowerCamelCase : Optional[Any] , **__lowerCamelCase : Optional[int] ): """simple docstring""" _snake_case = kwargs.get('''is_split_into_words''' , __lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): """simple docstring""" _snake_case = self._tokenizer.model.save(__lowerCamelCase , name=__lowerCamelCase ) return tuple(__lowerCamelCase ) def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): """simple docstring""" _snake_case = [self.sep_token_id] _snake_case = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): """simple docstring""" return token_ids_a + [self.eos_token_id] def __UpperCAmelCase ( self : str , __lowerCamelCase : "Conversation" ): """simple docstring""" _snake_case = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(__lowerCamelCase ) _snake_case = ''' '''.join(__lowerCamelCase ) _snake_case = self.encode(__lowerCamelCase ) if len(__lowerCamelCase ) > self.model_max_length: _snake_case = input_ids[-self.model_max_length :] logger.warning(f"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
103
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __snake_case = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M' UpperCamelCase_ : Optional[Any] =( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) UpperCamelCase_ : Dict ='translator' UpperCamelCase_ : Any =AutoTokenizer UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM UpperCamelCase_ : List[Any] =LANGUAGE_CODES UpperCamelCase_ : int =['text', 'text', 'text'] UpperCamelCase_ : Union[str, Any] =['text'] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: if src_lang not in self.lang_to_code: raise ValueError(F'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'''{tgt_lang} is not a supported language.''' ) UpperCamelCase :Optional[int] = self.lang_to_code[src_lang] UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
658
0
"""simple docstring""" import numpy as np from transformers import Pipeline def _lowerCamelCase ( UpperCAmelCase_ : List[Any] ) -> Union[str, Any]: """simple docstring""" A__ = np.max(UpperCAmelCase_, axis=-1, keepdims=UpperCAmelCase_ ) A__ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1, keepdims=UpperCAmelCase_ ) class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" def snake_case__ ( self , **SCREAMING_SNAKE_CASE__ ) -> str: A__ = {} if "second_text" in kwargs: A__ = kwargs["second_text"] return preprocess_kwargs, {}, {} def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Optional[Any]: return self.tokenizer(SCREAMING_SNAKE_CASE__ , text_pair=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) def snake_case__ ( self , SCREAMING_SNAKE_CASE__ ) -> int: return self.model(**SCREAMING_SNAKE_CASE__ ) def snake_case__ ( self , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: A__ = model_outputs.logits[0].numpy() A__ = softmax(SCREAMING_SNAKE_CASE__ ) A__ = np.argmax(SCREAMING_SNAKE_CASE__ ) A__ = self.model.config.idalabel[best_class] A__ = probabilities[best_class].item() A__ = logits.tolist() return {"label": label, "score": score, "logits": logits}
104
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __snake_case = 10 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if array[i] == target: return i return -1 def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Tuple = 0 UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1 UpperCamelCase :str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase :int = one_third - 1 elif array[two_third] < target: UpperCamelCase :Any = two_third + 1 else: UpperCamelCase :Any = one_third + 1 UpperCamelCase :int = two_third - 1 else: return -1 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = (left + right) // 3 + 1 UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __snake_case = input("""Enter numbers separated by comma:\n""").strip() __snake_case = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __snake_case = int(input("""Enter the number to be found in the list:\n""").strip()) __snake_case = ite_ternary_search(collection, target) __snake_case = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
658
0
import inspect import unittest class lowerCAmelCase_ ( unittest.TestCase ): def snake_case ( self ): try: import diffusers # noqa: F401 except ImportError: assert False def snake_case ( self ): import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE_ : List[str] = inspect.getmembers(snake_case__ ,inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE_ : int = 'k-diffusion' elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE_ : Union[str, Any] = 'invisible-watermark' assert backend in deps, F'{backend} is not in the deps table!'
105
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 UpperCamelCase :Union[str, Any] = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Dict = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :str = max_revenue return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )] UpperCamelCase :Dict = 0 for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Tuple = max_revenue_i return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): if n < 0: UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :str = 36 UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
658
0
from math import sqrt def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> bool: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' must been an int and positive" A = True # 0 and 1 are none primes. if number <= 1: A = False for divisor in range(2 , int(round(sqrt(lowerCAmelCase__ ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: A = False break # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'status' must been from type bool" return status def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> str: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N A = list(range(2 , n + 1 ) ) A = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(lowerCAmelCase__ ) ): for j in range(i + 1 , len(lowerCAmelCase__ ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): A = 0 # filters actual prime numbers. A = [x for x in begin_list if x != 0] # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : str ) -> Dict: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n > 2), "'N' must been an int and > 2" A = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(lowerCAmelCase__ ): ans.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Dict: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and number >= 0, "'number' must been an int and >= 0" A = [] # this list will be returns of the function. # potential prime number factors. A = 2 A = number if number == 0 or number == 1: ans.append(lowerCAmelCase__ ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(lowerCAmelCase__ ): while quotient != 1: if is_prime(lowerCAmelCase__ ) and (quotient % factor == 0): ans.append(lowerCAmelCase__ ) quotient /= factor else: factor += 1 else: ans.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type list" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Tuple: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" A = 0 # prime factorization of 'number' A = prime_factorization(lowerCAmelCase__ ) A = max(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : int ) -> List[Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number >= 0 ), "'number' bust been an int and >= 0" A = 0 # prime factorization of 'number' A = prime_factorization(lowerCAmelCase__ ) A = min(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'ans' must been from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> Optional[int]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int" assert isinstance(number % 2 == 0 , lowerCAmelCase__ ), "compare bust been from type bool" return number % 2 == 0 def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ), "'number' must been an int" assert isinstance(number % 2 != 0 , lowerCAmelCase__ ), "compare bust been from type bool" return number % 2 != 0 def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> int: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (number > 2) and is_even(lowerCAmelCase__ ) ), "'number' must been an int, even and > 2" A = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' A = get_prime_numbers(lowerCAmelCase__ ) A = len(lowerCAmelCase__ ) # run variable for while-loops. A = 0 A = None # exit variable. for break up the loops A = True while i < len_pn and loop: A = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: A = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (len(lowerCAmelCase__ ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] ) -> List[Any]: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." A = 0 while numbera != 0: A = numbera % numbera A = numbera A = rest # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." A = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' A = prime_factorization(lowerCAmelCase__ ) A = prime_factorization(lowerCAmelCase__ ) elif numbera == 1 or numbera == 1: A = [] A = [] A = max(lowerCAmelCase__ , lowerCAmelCase__ ) A = 0 A = 0 A = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: A = prime_fac_a.count(lowerCAmelCase__ ) A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(max(lowerCAmelCase__ , lowerCAmelCase__ ) ): ans *= n else: A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(lowerCAmelCase__ ): ans *= n done.append(lowerCAmelCase__ ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: A = prime_fac_a.count(lowerCAmelCase__ ) for _ in range(lowerCAmelCase__ ): ans *= n done.append(lowerCAmelCase__ ) # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Tuple ) -> Any: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'number' must been a positive int" A = 0 A = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(lowerCAmelCase__ ): ans += 1 # precondition assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and is_prime( lowerCAmelCase__ ), "'ans' must been a prime number and from type int" return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str ) -> Optional[int]: '''simple docstring''' assert ( is_prime(lowerCAmelCase__ ) and is_prime(lowerCAmelCase__ ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" A = p_number_a + 1 # jump to the next number A = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(lowerCAmelCase__ ): number += 1 while number < p_number_a: ans.append(lowerCAmelCase__ ) number += 1 # fetch the next prime number. while not is_prime(lowerCAmelCase__ ): number += 1 # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ans[0] != p_number_a and ans[len(lowerCAmelCase__ ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[Any] ) -> List[str]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 1), "'n' must been int and >= 1" A = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(lowerCAmelCase__ ) # precondition assert ans[0] == 1 and ans[len(lowerCAmelCase__ ) - 1] == n, "Error in function getDivisiors(...)" return ans def lowerCamelCase_ ( lowerCAmelCase__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and ( number > 1 ), "'number' must been an int and >= 1" A = get_divisors(lowerCAmelCase__ ) # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (divisors[0] == 1) and (divisors[len(lowerCAmelCase__ ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def lowerCamelCase_ ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] ) -> str: '''simple docstring''' assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. A = gcd(abs(lowerCAmelCase__ ) , abs(lowerCAmelCase__ ) ) # precondition assert ( isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def lowerCamelCase_ ( lowerCAmelCase__ : Dict ) -> int: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been a int and >= 0" A = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def lowerCamelCase_ ( lowerCAmelCase__ : List[str] ) -> Union[str, Any]: '''simple docstring''' assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and (n >= 0), "'n' must been an int and >= 0" A = 0 A = 1 A = 1 # this will be return for _ in range(n - 1 ): A = ans ans += fiba A = tmp return ans
106
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase, lowercase ): """simple docstring""" UpperCamelCase_ : int ='focalnet' def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = image_size UpperCamelCase :Dict = patch_size UpperCamelCase :Tuple = num_channels UpperCamelCase :int = embed_dim UpperCamelCase :Optional[Any] = use_conv_embed UpperCamelCase :str = hidden_sizes UpperCamelCase :str = depths UpperCamelCase :Optional[int] = focal_levels UpperCamelCase :Tuple = focal_windows UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Optional[int] = mlp_ratio UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :int = drop_path_rate UpperCamelCase :Dict = use_layerscale UpperCamelCase :List[str] = layerscale_value UpperCamelCase :Tuple = use_post_layernorm UpperCamelCase :int = use_post_layernorm_in_modulation UpperCamelCase :str = normalize_modulator UpperCamelCase :Any = initializer_range UpperCamelCase :Optional[Any] = layer_norm_eps UpperCamelCase :Dict = encoder_stride UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
658
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer _UpperCAmelCase : List[Any] = logging.get_logger(__name__) _UpperCAmelCase : Dict = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _UpperCAmelCase : List[str] = { '''vocab_file''': { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt''' ), } } _UpperCAmelCase : Optional[int] = { '''junnyu/roformer_chinese_small''': 15_36, '''junnyu/roformer_chinese_base''': 15_36, '''junnyu/roformer_chinese_char_small''': 5_12, '''junnyu/roformer_chinese_char_base''': 5_12, '''junnyu/roformer_small_discriminator''': 1_28, '''junnyu/roformer_small_generator''': 1_28, } _UpperCAmelCase : Any = { '''junnyu/roformer_chinese_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_base''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_base''': {'''do_lower_case''': True}, '''junnyu/roformer_small_discriminator''': {'''do_lower_case''': True}, '''junnyu/roformer_small_generator''': {'''do_lower_case''': True}, } class lowercase_ ( _UpperCamelCase ): """simple docstring""" __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = PRETRAINED_INIT_CONFIGURATION __lowerCAmelCase = RoFormerTokenizer def __init__( self : Dict, UpperCamelCase__ : Dict=None, UpperCamelCase__ : List[Any]=None, UpperCamelCase__ : str=True, UpperCamelCase__ : Dict="[UNK]", UpperCamelCase__ : Dict="[SEP]", UpperCamelCase__ : Optional[Any]="[PAD]", UpperCamelCase__ : Union[str, Any]="[CLS]", UpperCamelCase__ : Any="[MASK]", UpperCamelCase__ : List[Any]=True, UpperCamelCase__ : str=None, **UpperCamelCase__ : str, ) -> Optional[int]: super().__init__( UpperCamelCase__, tokenizer_file=UpperCamelCase__, do_lower_case=UpperCamelCase__, unk_token=UpperCamelCase__, sep_token=UpperCamelCase__, pad_token=UpperCamelCase__, cls_token=UpperCamelCase__, mask_token=UpperCamelCase__, tokenize_chinese_chars=UpperCamelCase__, strip_accents=UpperCamelCase__, **UpperCamelCase__, ) _A = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get('lowercase', UpperCamelCase__ ) != do_lower_case or pre_tok_state.get('strip_accents', UpperCamelCase__ ) != strip_accents ): _A = getattr(UpperCamelCase__, pre_tok_state.pop('type' ) ) _A = do_lower_case _A = strip_accents _A = pre_tok_class(**UpperCamelCase__ ) _A = do_lower_case def __getstate__( self : Any ) -> List[str]: _A = self.__dict__.copy() _A = BertPreTokenizer() return state def __setstate__( self : List[str], UpperCamelCase__ : int ) -> int: _A = d _A = self.__dict__['_tokenizer'].get_vocab() _A = PreTokenizer.custom(JiebaPreTokenizer(UpperCamelCase__ ) ) def __UpperCAmelCase ( self : List[Any], UpperCamelCase__ : List[str], UpperCamelCase__ : int=None ) -> int: _A = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCAmelCase ( self : List[str], UpperCamelCase__ : List[int], UpperCamelCase__ : Optional[List[int]] = None ) -> List[int]: _A = [self.sep_token_id] _A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCAmelCase ( self : Tuple, UpperCamelCase__ : str, UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: _A = self._tokenizer.model.save(UpperCamelCase__, name=UpperCamelCase__ ) return tuple(UpperCamelCase__ ) def __UpperCAmelCase ( self : int, UpperCamelCase__ : int, UpperCamelCase__ : Dict=None, UpperCamelCase__ : Dict=None, UpperCamelCase__ : Tuple=False, **UpperCamelCase__ : Optional[Any], ) -> Any: _A = BertPreTokenizer() return super().save_pretrained(UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__, **UpperCamelCase__ )
107
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :Union[str, Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Any = patch_size UpperCamelCase :List[str] = num_channels UpperCamelCase :int = is_training UpperCamelCase :str = use_labels UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = backbone_out_indices UpperCamelCase :str = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :int = backbone_featmap_shape UpperCamelCase :Any = scope UpperCamelCase :int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Dict = (image_size // patch_size) ** 2 UpperCamelCase :List[str] = num_patches + 1 def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Tuple =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Tuple =False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Union[str, Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Any = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = False UpperCamelCase :List[Any] = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Any: pass @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = prepare_img() UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :int = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer __a: Union[str, Any] = logging.get_logger(__name__) __a: str = { '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } __a: Dict = { '''vocab_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json''' }, '''merges_file''': { '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt''' }, '''tokenizer_config_file''': { '''facebook/blenderbot_small-90M''': ( '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json''' ) }, } __a: Union[str, Any] = { '''facebook/blenderbot_small-90M''': 512, } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _lowerCamelCase = VOCAB_FILES_NAMES _lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase = BlenderbotSmallTokenizer def __init__( self : List[str] , lowerCamelCase : List[str]=None , lowerCamelCase : str=None , lowerCamelCase : Optional[Any]="<|endoftext|>" , lowerCamelCase : Dict="<|endoftext|>" , lowerCamelCase : str="<|endoftext|>" , lowerCamelCase : str=False , lowerCamelCase : Tuple=True , **lowerCamelCase : List[str] , ) -> List[Any]: """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=lowerCamelCase , merges=lowerCamelCase , add_prefix_space=lowerCamelCase , trim_offsets=lowerCamelCase , ) , bos_token=lowerCamelCase , eos_token=lowerCamelCase , unk_token=lowerCamelCase , **lowerCamelCase , ) _UpperCAmelCase = add_prefix_space def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : str , lowerCamelCase : Union[str, Any]=None ) -> str: """simple docstring""" _UpperCAmelCase = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCamelCase ( self : Any , lowerCamelCase : List[int] , lowerCamelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
108
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Union[str, Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: UpperCamelCase :Any = 128 elif "12-12" in model_name: UpperCamelCase :Union[str, Any] = 12 UpperCamelCase :Any = 12 elif "14-14" in model_name: UpperCamelCase :Optional[int] = 14 UpperCamelCase :List[str] = 14 elif "16-16" in model_name: UpperCamelCase :List[Any] = 16 UpperCamelCase :Optional[Any] = 16 else: raise ValueError('''Model not supported''' ) UpperCamelCase :Tuple = '''huggingface/label-files''' if "speech-commands" in model_name: UpperCamelCase :Optional[Any] = 35 UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json''' else: UpperCamelCase :Optional[int] = 527 UpperCamelCase :List[Any] = '''audioset-id2label.json''' UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): if "module.v" in name: UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ): for key in orig_state_dict.copy().keys(): UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: UpperCamelCase :Any = key.split('''.''' ) UpperCamelCase :str = int(key_split[3] ) UpperCamelCase :Union[str, Any] = config.hidden_size if "weight" in key: UpperCamelCase :List[str] = val[:dim, :] UpperCamelCase :Optional[Any] = val[dim : dim * 2, :] UpperCamelCase :Optional[Any] = val[-dim:, :] else: UpperCamelCase :Dict = val[:dim] UpperCamelCase :Optional[int] = val[dim : dim * 2] UpperCamelCase :List[Any] = val[-dim:] else: UpperCamelCase :Union[str, Any] = val return orig_state_dict def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[str] = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ): UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict UpperCamelCase :Optional[int] = model_name_to_url[model_name] UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE__ ) # rename some keys UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load 🤗 model UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78 UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26 UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128 UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) if "speech-commands" in model_name: UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array'''] else: UpperCamelCase :List[Any] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = waveform.squeeze().numpy() UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' ) # forward pass UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] ) elif model_name == "ast-finetuned-speech-commands-v2": UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
658
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a = logging.get_logger(__name__) a = { "microsoft/git-base": "https://huggingface.co/microsoft/git-base/resolve/main/config.json", } class __a ( _snake_case ): __UpperCamelCase : int = 'git_vision_model' def __init__( self : int ,lowerCamelCase : Optional[int]=768 ,lowerCamelCase : Dict=3072 ,lowerCamelCase : List[str]=12 ,lowerCamelCase : List[Any]=12 ,lowerCamelCase : int=3 ,lowerCamelCase : Tuple=224 ,lowerCamelCase : str=16 ,lowerCamelCase : int="quick_gelu" ,lowerCamelCase : List[Any]=1E-5 ,lowerCamelCase : Dict=0.0 ,lowerCamelCase : Union[str, Any]=0.02 ,**lowerCamelCase : Union[str, Any] ,): '''simple docstring''' super().__init__(**lowerCamelCase ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = hidden_act @classmethod def UpperCAmelCase__ ( cls : Optional[Any] ,lowerCamelCase : Union[str, os.PathLike] ,**lowerCamelCase : Tuple ): '''simple docstring''' cls._set_token_in_kwargs(lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(lowerCamelCase ,**lowerCamelCase ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": __SCREAMING_SNAKE_CASE = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls ,"""model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(lowerCamelCase ,**lowerCamelCase ) class __a ( _snake_case ): __UpperCamelCase : str = 'git' def __init__( self : Any ,lowerCamelCase : Optional[int]=None ,lowerCamelCase : List[str]=3_0522 ,lowerCamelCase : Any=768 ,lowerCamelCase : int=6 ,lowerCamelCase : Tuple=12 ,lowerCamelCase : List[Any]=3072 ,lowerCamelCase : int="gelu" ,lowerCamelCase : Optional[Any]=0.1 ,lowerCamelCase : Optional[int]=0.1 ,lowerCamelCase : int=1024 ,lowerCamelCase : str=0.02 ,lowerCamelCase : Union[str, Any]=1E-1_2 ,lowerCamelCase : Any=0 ,lowerCamelCase : str="absolute" ,lowerCamelCase : Dict=True ,lowerCamelCase : List[Any]=False ,lowerCamelCase : List[Any]=101 ,lowerCamelCase : Tuple=102 ,lowerCamelCase : List[str]=None ,**lowerCamelCase : Any ,): '''simple docstring''' super().__init__(bos_token_id=lowerCamelCase ,eos_token_id=lowerCamelCase ,pad_token_id=lowerCamelCase ,**lowerCamelCase ) if vision_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) __SCREAMING_SNAKE_CASE = GitVisionConfig(**lowerCamelCase ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = tie_word_embeddings __SCREAMING_SNAKE_CASE = num_image_with_embedding __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
109
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
__UpperCamelCase : int = frozenset( [ 'prompt', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) __UpperCamelCase : List[str] = frozenset(['prompt', 'negative_prompt']) __UpperCamelCase : str = frozenset([]) __UpperCamelCase : Union[str, Any] = frozenset(['image']) __UpperCamelCase : str = frozenset( [ 'image', 'height', 'width', 'guidance_scale', ] ) __UpperCamelCase : str = frozenset(['image']) __UpperCamelCase : int = frozenset( [ 'prompt', 'image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) __UpperCamelCase : Tuple = frozenset(['prompt', 'image', 'negative_prompt']) __UpperCamelCase : Dict = frozenset( [ # Text guided image variation with an image mask 'prompt', 'image', 'mask_image', 'height', 'width', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', ] ) __UpperCamelCase : Union[str, Any] = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt']) __UpperCamelCase : Dict = frozenset( [ # image variation with an image mask 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) __UpperCamelCase : int = frozenset(['image', 'mask_image']) __UpperCamelCase : List[Any] = frozenset( [ 'example_image', 'image', 'mask_image', 'height', 'width', 'guidance_scale', ] ) __UpperCamelCase : Dict = frozenset(['example_image', 'image', 'mask_image']) __UpperCamelCase : int = frozenset(['class_labels']) __UpperCamelCase : Any = frozenset(['class_labels']) __UpperCamelCase : str = frozenset(['batch_size']) __UpperCamelCase : Tuple = frozenset([]) __UpperCamelCase : List[str] = frozenset(['batch_size']) __UpperCamelCase : Any = frozenset([]) __UpperCamelCase : Dict = frozenset( [ 'prompt', 'audio_length_in_s', 'guidance_scale', 'negative_prompt', 'prompt_embeds', 'negative_prompt_embeds', 'cross_attention_kwargs', ] ) __UpperCamelCase : Optional[Any] = frozenset(['prompt', 'negative_prompt']) __UpperCamelCase : Optional[int] = frozenset(['input_tokens']) __UpperCamelCase : Optional[Any] = frozenset(['input_tokens'])
248
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = """\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ __snake_case = """\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ __snake_case = R""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Tuple = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0 UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ ) return { "accuracy": accuracy, }
658
0
def __UpperCamelCase ( ): return [list(range(1_0_0_0 - i , -1_0_0_0 - i , -1 ) ) for i in range(1_0_0_0 )] lowercase__ =generate_large_matrix() lowercase__ =( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def __UpperCamelCase ( lowerCAmelCase__ : list[list[int]] ): assert all(row == sorted(SCREAMING_SNAKE_CASE__ , reverse=SCREAMING_SNAKE_CASE__ ) for row in grid ) assert all(list(SCREAMING_SNAKE_CASE__ ) == sorted(SCREAMING_SNAKE_CASE__ , reverse=SCREAMING_SNAKE_CASE__ ) for col in zip(*SCREAMING_SNAKE_CASE__ ) ) def __UpperCamelCase ( lowerCAmelCase__ : list[int] ): __a : Any = 0 __a : List[str] = len(SCREAMING_SNAKE_CASE__ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: __a : List[Any] = (left + right) // 2 __a : List[str] = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: __a : Union[str, Any] = mid + 1 else: __a : Tuple = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(SCREAMING_SNAKE_CASE__ ) def __UpperCamelCase ( lowerCAmelCase__ : list[list[int]] ): __a : Dict = 0 __a : Optional[Any] = len(grid[0] ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): __a : Any = find_negative_index(grid[i][:bound] ) total += bound return (len(SCREAMING_SNAKE_CASE__ ) * len(grid[0] )) - total def __UpperCamelCase ( lowerCAmelCase__ : list[list[int]] ): return len([number for row in grid for number in row if number < 0] ) def __UpperCamelCase ( lowerCAmelCase__ : list[list[int]] ): __a : Union[str, Any] = 0 for row in grid: for i, number in enumerate(SCREAMING_SNAKE_CASE__ ): if number < 0: total += len(SCREAMING_SNAKE_CASE__ ) - i break return total def __UpperCamelCase ( ): from timeit import timeit print('''Running benchmarks''' ) __a : List[str] = ( '''from __main__ import count_negatives_binary_search, ''' '''count_negatives_brute_force, count_negatives_brute_force_with_break, grid''' ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): __a : List[str] = timeit(f"{func}(grid=grid)" , setup=SCREAMING_SNAKE_CASE__ , number=5_0_0 ) print(f"{func}() took {time:0.4f} seconds" ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
521
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def _A ( ): UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase :Dict = parser.parse_args() return args.f def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ): UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) raise ValueError(F'''can\'t find {path}''' ) __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = self.get_auto_remove_tmp_dir() UpperCamelCase :Any = F''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :List[str] = F''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :int = F''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def UpperCAmelCase ( self ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2 UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[int] = F''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :Dict = F''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
658
0
"""simple docstring""" UpperCAmelCase = {"""a""": ["""c""", """b"""], """b""": ["""d""", """e"""], """c""": [], """d""": [], """e""": []} UpperCAmelCase = ["""a""", """b""", """c""", """d""", """e"""] def __magic_name__ ( _lowerCamelCase: Optional[Any], _lowerCamelCase: List[Any], _lowerCamelCase: int ) -> Dict: '''simple docstring''' lowerCAmelCase = start # add current to visited visited.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowerCAmelCase = topological_sort(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # if all neighbors visited add current to sort sort.append(SCREAMING_SNAKE_CASE__ ) # if all vertices haven't been visited select a new one to visit if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): for vertice in vertices: if vertice not in visited: lowerCAmelCase = topological_sort(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # return sort return sort if __name__ == "__main__": UpperCAmelCase = topological_sort("""a""", [], []) print(sort)
535
from __future__ import annotations from collections.abc import Callable def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ): UpperCamelCase :Optional[Any] = x_start UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCamelCase :Any = (x_end - x_start) / steps + xa UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCamelCase :Optional[int] = xa UpperCamelCase :List[str] = fxa return area if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE__ : int ): return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 10_00_00: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
658
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor lowerCAmelCase: List[Any] =logging.get_logger(__name__) class lowerCamelCase__ ( __UpperCamelCase ): def __init__( self , *snake_case , **snake_case ) -> None: """simple docstring""" warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" , SCREAMING_SNAKE_CASE_ , ) super().__init__(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
607
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :str = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = 10 UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps[0] UpperCamelCase :Union[str, Any] = scheduler.timesteps[1] UpperCamelCase :str = self.dummy_sample UpperCamelCase :List[str] = 0.1 * sample UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase ( self ) -> List[str]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # 1. scale model input UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :Tuple = pred_prev_sample UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = scheduler.timesteps UpperCamelCase :int = torch.manual_seed(0 ) UpperCamelCase :str = self.dummy_model() UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :int = pred_prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :Tuple = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = [39, 30, 12, 1, 0] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[int] = self.scheduler_classes[0] UpperCamelCase :List[str] = self.get_scheduler_config() UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
658
0
from __future__ import annotations def UpperCamelCase_ ( __a ) -> Dict: return [ord(SCREAMING_SNAKE_CASE__ ) - 96 for elem in plain] def UpperCamelCase_ ( __a ) -> Dict: return "".join(chr(elem + 96 ) for elem in encoded ) def UpperCamelCase_ ( ) -> int: a__ : Tuple = encode(input("-> " ).strip().lower() ) print("Encoded: " , SCREAMING_SNAKE_CASE__ ) print("Decoded:" , decode(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": main()
37
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
def A__ (snake_case : Optional[Any] , snake_case : Tuple ) -> Dict: __UpperCamelCase : Any = 0 __UpperCamelCase : List[str] = len(SCREAMING_SNAKE_CASE__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __UpperCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(SCREAMING_SNAKE_CASE__ ): return None __UpperCamelCase : List[Any] = sorted_collection[point] if current_item == item: return point else: if point < left: __UpperCamelCase : List[Any] = left __UpperCamelCase : Optional[Any] = point elif point > right: __UpperCamelCase : Optional[int] = right __UpperCamelCase : Any = point else: if item < current_item: __UpperCamelCase : List[str] = point - 1 else: __UpperCamelCase : Dict = point + 1 return None def A__ (snake_case : List[Any] , snake_case : List[Any] , snake_case : Any , snake_case : Optional[int] ) -> List[str]: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __UpperCamelCase : Dict = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(SCREAMING_SNAKE_CASE__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif point > right: return interpolation_search_by_recursion(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , point - 1 ) else: return interpolation_search_by_recursion( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , point + 1 , SCREAMING_SNAKE_CASE__ ) def A__ (snake_case : str ) -> int: if collection != sorted(SCREAMING_SNAKE_CASE__ ): raise ValueError("""Collection must be ascending sorted""" ) return True if __name__ == "__main__": import sys a__ = 0 if debug == 1: a__ = [10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit('''Sequence must be ascending sorted to apply interpolation search''') a__ = 67 a__ = interpolation_search(collection, target) if result is not None: print(f"{target} found at positions: {result}") else: print('''Not found''')
279
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: return None class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: return None class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =[ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[int]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> int: from transformers import BertModel UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCAmelCase ( self ) -> str: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[str]: from transformers import BertModel UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' ) @require_tf @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[Any]: from transformers import TFBertModel UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
658
0
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class lowerCamelCase__ : """simple docstring""" def __init__(self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=50 , __a=0.02 , __a=True , __a=None , ): '''simple docstring''' lowerCamelCase = parent lowerCamelCase = batch_size lowerCamelCase = seq_length lowerCamelCase = is_training lowerCamelCase = use_input_mask lowerCamelCase = vocab_size lowerCamelCase = hidden_size lowerCamelCase = num_hidden_layers lowerCamelCase = num_attention_heads lowerCamelCase = intermediate_size lowerCamelCase = hidden_act lowerCamelCase = hidden_dropout_prob lowerCamelCase = attention_probs_dropout_prob lowerCamelCase = max_position_embeddings lowerCamelCase = initializer_range lowerCamelCase = use_labels lowerCamelCase = scope def _a (self ): '''simple docstring''' lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase = None if self.use_input_mask: lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase = self.get_config() return config, input_ids, input_mask, token_labels def _a (self ): '''simple docstring''' return BertGenerationConfig( 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 , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , ) def _a (self ): '''simple docstring''' ( lowerCamelCase ) = self.prepare_config_and_inputs() lowerCamelCase = True lowerCamelCase = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def _a (self , __a , __a , __a , __a , **__a , ): '''simple docstring''' lowerCamelCase = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ ) lowerCamelCase = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a (self , __a , __a , __a , __a , __a , __a , **__a , ): '''simple docstring''' lowerCamelCase = True lowerCamelCase = BertGenerationEncoder(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a (self , __a , __a , __a , __a , __a , __a , **__a , ): '''simple docstring''' lowerCamelCase = True lowerCamelCase = True lowerCamelCase = BertGenerationDecoder(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() # first forward pass lowerCamelCase = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , use_cache=SCREAMING_SNAKE_CASE_ , ) lowerCamelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCamelCase = torch.cat([input_mask, next_mask] , dim=-1 ) lowerCamelCase = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , )['''hidden_states'''][0] lowerCamelCase = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , encoder_attention_mask=SCREAMING_SNAKE_CASE_ , past_key_values=SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ , )['''hidden_states'''][0] # select random slice lowerCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCamelCase = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1E-3 ) ) def _a (self , __a , __a , __a , __a , *__a , ): '''simple docstring''' lowerCamelCase = BertGenerationDecoder(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() lowerCamelCase = 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 _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() lowerCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCamelCase__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase): """simple docstring""" _A = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () _A = (BertGenerationDecoder,) if is_torch_available() else () _A = ( {'feature-extraction': BertGenerationEncoder, 'text-generation': BertGenerationDecoder} if is_torch_available() else {} ) def _a (self ): '''simple docstring''' lowerCamelCase = BertGenerationEncoderTester(self ) lowerCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def _a (self ): '''simple docstring''' self.config_tester.run_common_tests() def _a (self ): '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def _a (self ): '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() lowerCamelCase = '''bert''' self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a (self ): '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*SCREAMING_SNAKE_CASE_ ) def _a (self ): '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*SCREAMING_SNAKE_CASE_ ) def _a (self ): '''simple docstring''' ( lowerCamelCase ) = self.model_tester.prepare_config_and_inputs_for_decoder() lowerCamelCase = None self.model_tester.create_and_check_model_as_decoder( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) def _a (self ): '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE_ ) @slow def _a (self ): '''simple docstring''' lowerCamelCase = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" @slow def _a (self ): '''simple docstring''' lowerCamelCase = BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) lowerCamelCase = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] ) with torch.no_grad(): lowerCamelCase = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase = torch.Size([1, 8, 10_24] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) ) @require_torch class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" @slow def _a (self ): '''simple docstring''' lowerCamelCase = BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder" ) lowerCamelCase = torch.tensor([[1_01, 75_92, 10_10, 20_26, 38_99, 20_03, 1_01_40, 1_02]] ) with torch.no_grad(): lowerCamelCase = model(SCREAMING_SNAKE_CASE_ )[0] lowerCamelCase = torch.Size([1, 8, 5_03_58] ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) lowerCamelCase = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) )
623
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Union[str, Any] = tempfile.mkdtemp() UpperCamelCase :List[str] = 5 # Realm tok UpperCamelCase :List[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , 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] ) ) UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def UpperCAmelCase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records ) return config def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Tuple = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=SCREAMING_SNAKE_CASE_ , ) return block_records def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Optional[int] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[Any] = self.get_config() UpperCamelCase :str = self.get_dummy_retriever() UpperCamelCase :int = retriever.tokenizer UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' ) UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Tuple = tokenizer( ['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Optional[Any] = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = self.get_config() UpperCamelCase :Union[str, Any] = self.get_dummy_retriever() UpperCamelCase :Dict = retriever.tokenizer UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' ) UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Optional[Any] = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Any = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: UpperCamelCase :Tuple = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
658
0
'''simple docstring''' from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int, SCREAMING_SNAKE_CASE__: Tuple ) -> Tuple: """simple docstring""" __a = [] for part_id in partition_order: __a = df.where(f"""SPARK_PARTITION_ID() = {part_id}""" ).collect() for row_idx, row in enumerate(SCREAMING_SNAKE_CASE__ ): expected_row_ids_and_row_dicts.append((f"""{part_id}_{row_idx}""", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Optional[int]: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(100 ).repartition(1 ) __a = Spark(SCREAMING_SNAKE_CASE__ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Optional[Any]: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(10 ).repartition(2 ) __a = [1, 0] __a = _generate_iterable_examples(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Reverse the partitions. __a = _get_expected_row_ids_and_row_dicts_for_partition_order(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): __a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> List[str]: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(10 ).repartition(1 ) __a = SparkExamplesIterable(SCREAMING_SNAKE_CASE__ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(SCREAMING_SNAKE_CASE__ ): assert row_id == f"""0_{i}""" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Dict: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('numpy.random.Generator' ) as generator_mock: __a = lambda SCREAMING_SNAKE_CASE__ : x.reverse() __a = _get_expected_row_ids_and_row_dicts_for_partition_order(SCREAMING_SNAKE_CASE__, [2, 1, 0] ) __a = SparkExamplesIterable(SCREAMING_SNAKE_CASE__ ).shuffle_data_sources(SCREAMING_SNAKE_CASE__ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(SCREAMING_SNAKE_CASE__ ): __a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Any: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 __a = SparkExamplesIterable(SCREAMING_SNAKE_CASE__ ).shard_data_sources(worker_id=0, num_workers=2 ) assert shard_it_a.n_shards == 2 __a = _get_expected_row_ids_and_row_dicts_for_partition_order(SCREAMING_SNAKE_CASE__, [0, 2] ) for i, (row_id, row_dict) in enumerate(SCREAMING_SNAKE_CASE__ ): __a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 __a = SparkExamplesIterable(SCREAMING_SNAKE_CASE__ ).shard_data_sources(worker_id=1, num_workers=2 ) assert shard_it_a.n_shards == 2 __a = _get_expected_row_ids_and_row_dicts_for_partition_order(SCREAMING_SNAKE_CASE__, [1, 3] ) for i, (row_id, row_dict) in enumerate(SCREAMING_SNAKE_CASE__ ): __a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __UpperCAmelCase ( ) -> Dict: """simple docstring""" __a = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() __a = spark.range(100 ).repartition(1 ) __a = Spark(SCREAMING_SNAKE_CASE__ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
448
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]: UpperCamelCase :int = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[int] = max_length UpperCamelCase :Union[str, Any] = num_mel_bins UpperCamelCase :Optional[int] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :Dict = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :str = num_attention_heads UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :str = type_sequence_label_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = scope UpperCamelCase :List[Any] = frequency_stride UpperCamelCase :Tuple = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension UpperCamelCase :Optional[int] = num_patches + 2 def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :str = self.get_config() return config, input_values, labels def UpperCAmelCase ( self ) -> List[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :List[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) UpperCamelCase_ : Any =( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[Any] =False UpperCamelCase_ : Dict =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = ASTModelTester(self ) UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> str: pass def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Any = [*signature.parameters.keys()] UpperCamelCase :Optional[int] = ['''input_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Optional[int]: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Any = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase ( self ) -> Tuple: return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.default_feature_extractor UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = self.default_feature_extractor UpperCamelCase , UpperCamelCase :Dict = prepare_audio() UpperCamelCase :Dict = audio.squeeze().numpy() UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase :List[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _A ( UpperCAmelCase_ ): lowercase_ : Any = 'vit_msn' def __init__( self : Optional[int] , lowerCamelCase__ : int=7_68 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : Optional[Any]=30_72 , lowerCamelCase__ : str="gelu" , lowerCamelCase__ : List[Any]=0.0 , lowerCamelCase__ : Optional[Any]=0.0 , lowerCamelCase__ : Optional[Any]=0.02 , lowerCamelCase__ : Any=1e-06 , lowerCamelCase__ : List[str]=2_24 , lowerCamelCase__ : str=16 , lowerCamelCase__ : str=3 , lowerCamelCase__ : Union[str, Any]=True , **lowerCamelCase__ : Optional[int] , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) __UpperCamelCase : Tuple = hidden_size __UpperCamelCase : int = num_hidden_layers __UpperCamelCase : Optional[Any] = num_attention_heads __UpperCamelCase : Tuple = intermediate_size __UpperCamelCase : str = hidden_act __UpperCamelCase : int = hidden_dropout_prob __UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob __UpperCamelCase : int = initializer_range __UpperCamelCase : int = layer_norm_eps __UpperCamelCase : Optional[Any] = image_size __UpperCamelCase : Tuple = patch_size __UpperCamelCase : Optional[Any] = num_channels __UpperCamelCase : Union[str, Any] = qkv_bias
269
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): UpperCamelCase :Dict = [image] if isinstance(image[0] , PIL.Image.Image ): UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0 UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 ) UpperCamelCase :Tuple = 2.0 * image - 1.0 UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ): if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): UpperCamelCase :int = True UpperCamelCase :Dict = va.device UpperCamelCase :List[Any] = va.cpu().numpy() UpperCamelCase :str = va.cpu().numpy() UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: UpperCamelCase :Any = (1 - t) * va + t * va else: UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = theta_a * t UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a UpperCamelCase :Union[str, Any] = sa * va + sa * va if inputs_are_torch: UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ): for param in model.parameters(): UpperCamelCase :Any = value class UpperCAmelCase_ ( lowercase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str: super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = ( feature_extractor.size if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ ) else feature_extractor.size['''shortest_edge'''] ) UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ ) set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: # get the original timestep using init_timestep UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int: if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ ) ] UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) else: UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[str] = 0.1_8215 * init_latents UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) # get latents UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = init_latents return latents def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: UpperCamelCase :List[str] = latents.detach().requires_grad_() UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep] UpperCamelCase :Optional[int] = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = self.scheduler.sigmas[index] UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :int = 1 / 0.1_8215 * sample UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype ) UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = latents.detach() + grads * (sigma**2) UpperCamelCase :Optional[Any] = noise_pred_original else: UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1: UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1) UpperCamelCase :Tuple = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]] UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ ) if style_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ ) # get prompt text embeddings for content and style UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # duplicate text embeddings for each generation per prompt UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # set timesteps UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) UpperCamelCase :List[str] = {} if accepts_offset: UpperCamelCase :Tuple = 1 self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ ) # Preprocess image UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if clip_guidance_scale > 0: UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = slerp( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase :Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase :Any = content_text_input.input_ids.shape[-1] UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase :int = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase :int = 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}''' ) UpperCamelCase :str = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase :Dict = {} if accepts_eta: UpperCamelCase :int = eta # check if the scheduler accepts generator UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: UpperCamelCase :List[str] = generator with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ): for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # expand the latents if we are doing classifier free guidance UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform classifier free guidance if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 ) UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: UpperCamelCase :int = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) UpperCamelCase , UpperCamelCase :str = self.cond_fn( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
658
0
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class _A ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=True , ): _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size_divisor _UpperCAmelCase = do_rescale def UpperCAmelCase ( self ): return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class _A ( __lowercase , unittest.TestCase ): __a = GLPNImageProcessor if is_vision_available() else None def UpperCAmelCase ( self ): _UpperCAmelCase = GLPNImageProcessingTester(self ) @property def UpperCAmelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase ( self ): _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_resize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """size_divisor""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """resample""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , """do_rescale""" ) ) def UpperCAmelCase ( self ): pass def UpperCAmelCase ( self ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCAmelCase ( self ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def UpperCAmelCase ( self ): # Initialize image_processing _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
518
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :list[list[int]] = [] UpperCamelCase :list[int] = [] UpperCamelCase :List[str] = 0 UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) __snake_case = [3, 34, 4, 12, 5, 2] __snake_case = 9 __snake_case = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
658
0
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class lowercase_ : '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple=2 , __UpperCAmelCase : Dict=True , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : Optional[Any]=10 , __UpperCAmelCase : List[Any]=3 , __UpperCAmelCase : Tuple=32 * 4 , __UpperCAmelCase : List[Any]=32 * 6 , __UpperCAmelCase : Optional[Any]=4 , __UpperCAmelCase : List[Any]=32 , ) ->List[Any]: """simple docstring""" a = parent a = batch_size a = is_training a = use_auxiliary_loss a = num_queries a = num_channels a = min_size a = max_size a = num_labels a = mask_feature_size def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" a = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( SCREAMING_SNAKE_CASE_ ) a = torch.ones([self.batch_size, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) a = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=SCREAMING_SNAKE_CASE_ ) > 0.5 ).float() a = (torch.rand((self.batch_size, self.num_labels) , device=SCREAMING_SNAKE_CASE_ ) > 0.5).long() a = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = self.prepare_config_and_inputs() a = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def __lowerCAmelCase ( self : str , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Any ) ->Dict: """simple docstring""" a = output.encoder_hidden_states a = output.pixel_decoder_hidden_states a = output.transformer_decoder_hidden_states self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(SCREAMING_SNAKE_CASE_ ) , config.decoder_config.decoder_layers ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : str , __UpperCAmelCase : Any=False ) ->Tuple: """simple docstring""" with torch.no_grad(): a = MaskFormerModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() a = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) a = model(SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : str ) ->Any: """simple docstring""" a = MaskFormerForInstanceSegmentation(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() def comm_check_on_output(__UpperCAmelCase : Optional[int] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): a = model(pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ ) a = model(SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) a = model( pixel_values=SCREAMING_SNAKE_CASE_ , pixel_mask=SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) comm_check_on_output(SCREAMING_SNAKE_CASE_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () __snake_case = ( {'feature-extraction': MaskFormerModel, 'image-segmentation': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : int ) ->str: """simple docstring""" a = MaskFormerModelTester(self ) a = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Dict: """simple docstring""" pass def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(SCREAMING_SNAKE_CASE_ ) a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) @slow def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: a = MaskFormerModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = (self.model_tester.min_size,) * 2 a = { '''pixel_values''': torch.randn((2, 3, *size) , device=SCREAMING_SNAKE_CASE_ ), '''mask_labels''': torch.randn((2, 10, *size) , device=SCREAMING_SNAKE_CASE_ ), '''class_labels''': torch.zeros(2 , 10 , device=SCREAMING_SNAKE_CASE_ ).long(), } a = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(SCREAMING_SNAKE_CASE_ ) a = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None ) def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , output_hidden_states=SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) a = model(**SCREAMING_SNAKE_CASE_ , output_attentions=SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.attentions is not None ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss a = self.all_model_classes[1] a = self.model_tester.prepare_config_and_inputs() a = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() a = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ).loss loss.backward() def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" a = self.all_model_classes[1] a = self.model_tester.prepare_config_and_inputs() a = True a = True a = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() a = model(SCREAMING_SNAKE_CASE_ , mask_labels=SCREAMING_SNAKE_CASE_ , class_labels=SCREAMING_SNAKE_CASE_ ) a = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() a = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't a = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() a = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) UpperCAmelCase__ = 1E-4 def _a ( ) -> List[Any]: a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class lowercase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(SCREAMING_SNAKE_CASE_ ) a = self.default_image_processor a = prepare_img() a = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) a = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 800, 1_088) ) with torch.no_grad(): a = model(**SCREAMING_SNAKE_CASE_ ) a = torch.tensor( [[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) a = torch.tensor( [[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) a = torch.tensor( [[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(SCREAMING_SNAKE_CASE_ ) .eval() ) a = self.default_image_processor a = prepare_img() a = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) a = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 800, 1_088) ) with torch.no_grad(): a = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits a = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) a = [ [-1.3737124, -1.7724937, -1.9364233], [-1.5977281, -1.9867939, -2.1523695], [-1.5795398, -1.9269832, -2.093942], ] a = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits a = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) a = torch.tensor( [ [1.6_5_1_2e0_0, -5.2_5_7_2e0_0, -3.3_5_1_9e0_0], [3.6_1_6_9e-0_2, -5.9_0_2_5e0_0, -2.9_3_1_3e0_0], [1.0_7_6_6e-0_4, -7.7_6_3_0e0_0, -5.1_2_6_3e0_0], ] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(SCREAMING_SNAKE_CASE_ ) .eval() ) a = self.default_image_processor a = prepare_img() a = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) a = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(SCREAMING_SNAKE_CASE_ , (1, 3, 800, 1_088) ) with torch.no_grad(): a = model(**SCREAMING_SNAKE_CASE_ ) # masks_queries_logits a = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) a = [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]] a = torch.tensor(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) # class_queries_logits a = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) a = torch.tensor( [[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" a = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(SCREAMING_SNAKE_CASE_ ) .eval() ) a = self.default_image_processor a = image_processor( [np.zeros((3, 800, 1_333) ), np.zeros((3, 800, 1_333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , ) a = inputs['''pixel_values'''].to(SCREAMING_SNAKE_CASE_ ) a = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs['''mask_labels''']] a = [el.to(SCREAMING_SNAKE_CASE_ ) for el in inputs['''class_labels''']] with torch.no_grad(): a = model(**SCREAMING_SNAKE_CASE_ ) self.assertTrue(outputs.loss is not None )
117
def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''check_bouncy() accepts only integer arguments''' ) UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ): if not 0 < percent < 100: raise ValueError('''solution() only accepts values from 0 to 100''' ) UpperCamelCase :Tuple = 0 UpperCamelCase :str = 1 while True: if check_bouncy(SCREAMING_SNAKE_CASE__ ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(99)}''')
658
0
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 : List[Any] = logging.get_logger(__name__) __UpperCamelCase : List[str] = '▁' __UpperCamelCase : List[Any] = {'vocab_file': 'sentencepiece.bpe.model'} __UpperCamelCase : str = { 'vocab_file': { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model' ), } } __UpperCamelCase : int = { 'xlm-roberta-base': 512, 'xlm-roberta-large': 512, 'xlm-roberta-large-finetuned-conll02-dutch': 512, 'xlm-roberta-large-finetuned-conll02-spanish': 512, 'xlm-roberta-large-finetuned-conll03-english': 512, 'xlm-roberta-large-finetuned-conll03-german': 512, } class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = VOCAB_FILES_NAMES UpperCamelCase_ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ = ['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any]="<s>" , UpperCamelCase__ : Optional[Any]="</s>" , UpperCamelCase__ : str="</s>" , UpperCamelCase__ : Any="<s>" , UpperCamelCase__ : Dict="<unk>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Tuple="<mask>" , UpperCamelCase__ : int = None , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else mask_token SCREAMING_SNAKE_CASE : List[str] = {} 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_ , sep_token=SCREAMING_SNAKE_CASE_ , cls_token=SCREAMING_SNAKE_CASE_ , pad_token=SCREAMING_SNAKE_CASE_ , mask_token=SCREAMING_SNAKE_CASE_ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(SCREAMING_SNAKE_CASE_ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE : Union[str, Any] = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : List[str] = len(self.sp_model ) + self.fairseq_offset SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Tuple = self.sp_model.serialized_model_proto() return state def __setstate__( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): SCREAMING_SNAKE_CASE : str = {} SCREAMING_SNAKE_CASE : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __A ( self : str , UpperCamelCase__ : Tuple , UpperCamelCase__ : str = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] SCREAMING_SNAKE_CASE : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __A ( self : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] = None , UpperCamelCase__ : Tuple = False ): '''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_ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE_ )) + [1] def __A ( self : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = [self.sep_token_id] SCREAMING_SNAKE_CASE : List[str] = [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 : Tuple ): '''simple docstring''' return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = {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 __A ( self : List[str] , UpperCamelCase__ : List[str] ): '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE_ , out_type=SCREAMING_SNAKE_CASE_ ) def __A ( self : Any , UpperCamelCase__ : int ): '''simple docstring''' if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __A ( self : Dict , UpperCamelCase__ : Tuple ): '''simple docstring''' if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __A ( self : Optional[int] , UpperCamelCase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = ''''''.join(SCREAMING_SNAKE_CASE_ ).replace(SCREAMING_SNAKE_CASE_ , ''' ''' ).strip() return out_string def __A ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str = None ): '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE : int = 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: SCREAMING_SNAKE_CASE : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,)
248
def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Union[str, Any] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) UpperCamelCase :str = hex_num[0] == '''-''' if is_negative: UpperCamelCase :Union[str, Any] = hex_num[1:] try: UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) UpperCamelCase :Dict = '''''' while int_num > 0: UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
from __future__ import annotations def __UpperCamelCase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int ): __a : list[list[int]] = [] __a : list[int] = [] __a : List[str] = 0 __a : Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def __UpperCamelCase ( lowerCAmelCase__ : list[int] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : list[int] , lowerCAmelCase__ : list[list[int]] , lowerCAmelCase__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) lowercase__ =[3, 34, 4, 12, 5, 2] lowercase__ =9 lowercase__ =generate_sum_of_subsets_soln(nums, max_sum) print(*result)
521
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase , UpperCamelCase :List[Any] = position UpperCamelCase :Any = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] UpperCamelCase :Dict = [] for position in positions: UpperCamelCase , UpperCamelCase :str = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(SCREAMING_SNAKE_CASE__ ) return permissible_positions def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): if is_complete(SCREAMING_SNAKE_CASE__ ): return True for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): UpperCamelCase , UpperCamelCase :Optional[int] = position if board[y][x] == 0: UpperCamelCase :Any = curr + 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ): return True UpperCamelCase :Union[str, Any] = 0 return False def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Tuple = 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ): return board UpperCamelCase :str = 0 UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class lowercase ( lowercase__ ): lowercase = 'facebook/nllb-200-distilled-600M' lowercase = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) lowercase = 'translator' lowercase = AutoTokenizer lowercase = AutoModelForSeqaSeqLM lowercase = LANGUAGE_CODES lowercase = ['text', 'text', 'text'] lowercase = ['text'] def UpperCAmelCase (self : str ,SCREAMING_SNAKE_CASE_ : str ,SCREAMING_SNAKE_CASE_ : Dict ,SCREAMING_SNAKE_CASE_ : List[str] ) -> str: """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(F"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(F"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase = self.lang_to_code[src_lang] lowerCAmelCase = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ ,return_tensors='''pt''' ,src_lang=SCREAMING_SNAKE_CASE_ ,tgt_lang=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Optional[Any] ,SCREAMING_SNAKE_CASE_ : str ) -> Optional[Any]: """simple docstring""" return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Optional[Any] ,SCREAMING_SNAKE_CASE_ : str ) -> int: """simple docstring""" return self.post_processor.decode(outputs[0].tolist() ,skip_special_tokens=SCREAMING_SNAKE_CASE_ )
535
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('''foo.json''',)] ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :int = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = GenerationConfig() UpperCamelCase :List[str] = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = GenerationConfig() UpperCamelCase :Tuple = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Dict = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) UpperCamelCase :Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase ( cls ) -> Optional[Any]: UpperCamelCase :List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase ( cls ) -> Union[str, Any]: try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
658
0
"""simple docstring""" from __future__ import annotations from random import random class lowerCamelCase__ : def __init__( self , snake_case = None ) -> Dict: """simple docstring""" lowercase : Optional[int] = value lowercase : Optional[Any] = random() lowercase : Node | None = None lowercase : Node | None = None def __repr__( self ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return f'''\'{self.value}: {self.prior:.5}\'''' else: return pformat( {f'''{self.value}: {self.prior:.5}''': (self.left, self.right)} , indent=1 ) def __str__( self ) -> str: """simple docstring""" lowercase : Dict = str(self.value ) + ''' ''' lowercase : Optional[int] = str(self.left or """""" ) lowercase : Union[str, Any] = str(self.right or """""" ) return value + left + right def __snake_case ( __A ,__A ) -> List[str]: if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: lowercase : List[Any] = split(root.left ,SCREAMING_SNAKE_CASE__ ) return left, root else: lowercase : Optional[int] = split(root.right ,SCREAMING_SNAKE_CASE__ ) return root, right def __snake_case ( __A ,__A ) -> List[str]: if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: lowercase : Dict = merge(left.right ,SCREAMING_SNAKE_CASE__ ) return left else: lowercase : Any = merge(SCREAMING_SNAKE_CASE__ ,right.left ) return right def __snake_case ( __A ,__A ) -> Optional[Any]: lowercase : Optional[Any] = Node(SCREAMING_SNAKE_CASE__ ) lowercase : int = split(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) return merge(merge(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) ,SCREAMING_SNAKE_CASE__ ) def __snake_case ( __A ,__A ) -> Optional[Any]: lowercase : str = split(SCREAMING_SNAKE_CASE__ ,value - 1 ) lowercase : Any = split(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) return merge(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def __snake_case ( __A ) -> Dict: if not root: # None return else: inorder(root.left ) print(root.value ,end=""",""" ) inorder(root.right ) def __snake_case ( __A ,__A ) -> Optional[Any]: for arg in args.split(): if arg[0] == "+": lowercase : Union[str, Any] = insert(SCREAMING_SNAKE_CASE__ ,int(arg[1:] ) ) elif arg[0] == "-": lowercase : int = erase(SCREAMING_SNAKE_CASE__ ,int(arg[1:] ) ) else: print("""Unknown command""" ) return root def __snake_case ( ) -> Optional[Any]: lowercase : List[Any] = None print( """enter numbers to create a tree, + value to add value into treap, """ """- value to erase all nodes with value. \'q\' to quit. """ ) lowercase : Dict = input() while args != "q": lowercase : List[str] = interact_treap(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = input() print("""good by!""" ) if __name__ == "__main__": import doctest doctest.testmod() main()
607
def _A ( SCREAMING_SNAKE_CASE__ : int ): if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
658
0
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A__ ( A__ ): """simple docstring""" _lowercase = 'ClapFeatureExtractor' _lowercase = ('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self : Union[str, Any] , lowerCamelCase__ : Any , lowerCamelCase__ : List[str] ): super().__init__(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __call__( self : Any , lowerCamelCase__ : str=None , lowerCamelCase__ : int=None , lowerCamelCase__ : str=None , **lowerCamelCase__ : List[str] ): a__ : Tuple = kwargs.pop("sampling_rate" , SCREAMING_SNAKE_CASE_ ) if text is None and audios is None: raise ValueError("You have to specify either text or audios. Both cannot be none." ) if text is not None: a__ : Union[str, Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if audios is not None: a__ : List[Any] = self.feature_extractor( SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if text is not None and audios is not None: a__ : Union[str, Any] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**SCREAMING_SNAKE_CASE_ ) , tensor_type=SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase( self : Optional[Any] , *lowerCamelCase__ : List[str] , **lowerCamelCase__ : Union[str, Any] ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase( self : Tuple , *lowerCamelCase__ : List[Any] , **lowerCamelCase__ : Union[str, Any] ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def _UpperCamelCase( self : Tuple ): a__ : Union[str, Any] = self.tokenizer.model_input_names a__ : Optional[int] = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
37
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __snake_case = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M' UpperCamelCase_ : Optional[Any] =( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) UpperCamelCase_ : Dict ='translator' UpperCamelCase_ : Any =AutoTokenizer UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM UpperCamelCase_ : List[Any] =LANGUAGE_CODES UpperCamelCase_ : int =['text', 'text', 'text'] UpperCamelCase_ : Union[str, Any] =['text'] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: if src_lang not in self.lang_to_code: raise ValueError(F'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'''{tgt_lang} is not a supported language.''' ) UpperCamelCase :Optional[int] = self.lang_to_code[src_lang] UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
658
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a__ = logging.get_logger(__name__) a__ = { '''caidas/swin2sr-classicalsr-x2-64''': ( '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ): """simple docstring""" __magic_name__ : Optional[int] = 'swin2sr' __magic_name__ : str = { 'hidden_size': 'embed_dim', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : int , lowerCAmelCase : str=64 , lowerCAmelCase : Tuple=1 , lowerCAmelCase : List[Any]=3 , lowerCAmelCase : Dict=180 , lowerCAmelCase : Optional[int]=[6, 6, 6, 6, 6, 6] , lowerCAmelCase : int=[6, 6, 6, 6, 6, 6] , lowerCAmelCase : Tuple=8 , lowerCAmelCase : str=2.0 , lowerCAmelCase : List[Any]=True , lowerCAmelCase : Union[str, Any]=0.0 , lowerCAmelCase : int=0.0 , lowerCAmelCase : Optional[Any]=0.1 , lowerCAmelCase : Tuple="gelu" , lowerCAmelCase : Dict=False , lowerCAmelCase : int=0.02 , lowerCAmelCase : Optional[Any]=1E-5 , lowerCAmelCase : Optional[Any]=2 , lowerCAmelCase : int=1.0 , lowerCAmelCase : str="1conv" , lowerCAmelCase : str="pixelshuffle" , **lowerCAmelCase : Tuple , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) __UpperCamelCase : Optional[Any] = image_size __UpperCamelCase : List[Any] = patch_size __UpperCamelCase : List[str] = num_channels __UpperCamelCase : Dict = embed_dim __UpperCamelCase : Tuple = depths __UpperCamelCase : int = len(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase : Dict = num_heads __UpperCamelCase : int = window_size __UpperCamelCase : Tuple = mlp_ratio __UpperCamelCase : Dict = qkv_bias __UpperCamelCase : Union[str, Any] = hidden_dropout_prob __UpperCamelCase : str = attention_probs_dropout_prob __UpperCamelCase : Optional[Any] = drop_path_rate __UpperCamelCase : Optional[Any] = hidden_act __UpperCamelCase : Optional[int] = use_absolute_embeddings __UpperCamelCase : Any = layer_norm_eps __UpperCamelCase : Optional[int] = initializer_range __UpperCamelCase : Union[str, Any] = upscale __UpperCamelCase : Any = img_range __UpperCamelCase : int = resi_connection __UpperCamelCase : List[str] = upsampler
279
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __snake_case = 10 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if array[i] == target: return i return -1 def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Tuple = 0 UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1 UpperCamelCase :str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase :int = one_third - 1 elif array[two_third] < target: UpperCamelCase :Any = two_third + 1 else: UpperCamelCase :Any = one_third + 1 UpperCamelCase :int = two_third - 1 else: return -1 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = (left + right) // 3 + 1 UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __snake_case = input("""Enter numbers separated by comma:\n""").strip() __snake_case = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __snake_case = int(input("""Enter the number to be found in the list:\n""").strip()) __snake_case = ite_ternary_search(collection, target) __snake_case = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
658
0
from copy import deepcopy class lowerCamelCase__ : """simple docstring""" def __init__(self , __a = None , __a = None ): '''simple docstring''' if arr is None and size is not None: lowerCamelCase = size lowerCamelCase = [0] * size elif arr is not None: self.init(SCREAMING_SNAKE_CASE_ ) else: raise ValueError("Either arr or size must be specified" ) def _a (self , __a ): '''simple docstring''' lowerCamelCase = len(SCREAMING_SNAKE_CASE_ ) lowerCamelCase = deepcopy(SCREAMING_SNAKE_CASE_ ) for i in range(1 , self.size ): lowerCamelCase = self.next_(SCREAMING_SNAKE_CASE_ ) if j < self.size: self.tree[j] += self.tree[i] def _a (self ): '''simple docstring''' lowerCamelCase = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): lowerCamelCase = self.next_(SCREAMING_SNAKE_CASE_ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def _a (__a ): '''simple docstring''' return index + (index & (-index)) @staticmethod def _a (__a ): '''simple docstring''' return index - (index & (-index)) def _a (self , __a , __a ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value lowerCamelCase = self.next_(SCREAMING_SNAKE_CASE_ ) def _a (self , __a , __a ): '''simple docstring''' self.add(SCREAMING_SNAKE_CASE_ , value - self.get(SCREAMING_SNAKE_CASE_ ) ) def _a (self , __a ): '''simple docstring''' if right == 0: return 0 lowerCamelCase = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] lowerCamelCase = self.prev(SCREAMING_SNAKE_CASE_ ) return result def _a (self , __a , __a ): '''simple docstring''' return self.prefix(SCREAMING_SNAKE_CASE_ ) - self.prefix(SCREAMING_SNAKE_CASE_ ) def _a (self , __a ): '''simple docstring''' return self.query(SCREAMING_SNAKE_CASE_ , index + 1 ) def _a (self , __a ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 lowerCamelCase = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 lowerCamelCase = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
623
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 UpperCamelCase :Union[str, Any] = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Dict = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :str = max_revenue return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )] UpperCamelCase :Dict = 0 for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Tuple = max_revenue_i return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): if n < 0: UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :str = 36 UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
658
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __UpperCamelCase : Dict = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Dict = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[Any] = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
448
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase, lowercase ): """simple docstring""" UpperCamelCase_ : int ='focalnet' def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = image_size UpperCamelCase :Dict = patch_size UpperCamelCase :Tuple = num_channels UpperCamelCase :int = embed_dim UpperCamelCase :Optional[Any] = use_conv_embed UpperCamelCase :str = hidden_sizes UpperCamelCase :str = depths UpperCamelCase :Optional[int] = focal_levels UpperCamelCase :Tuple = focal_windows UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Optional[int] = mlp_ratio UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :int = drop_path_rate UpperCamelCase :Dict = use_layerscale UpperCamelCase :List[str] = layerscale_value UpperCamelCase :Tuple = use_post_layernorm UpperCamelCase :int = use_post_layernorm_in_modulation UpperCamelCase :str = normalize_modulator UpperCamelCase :Any = initializer_range UpperCamelCase :Optional[Any] = layer_norm_eps UpperCamelCase :Dict = encoder_stride UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
658
0
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("""repo_id""" , ["""canonical_dataset_name""", """org-name/dataset-name"""] ) @pytest.mark.parametrize("""path""" , ["""filename.csv""", """filename with blanks.csv"""] ) @pytest.mark.parametrize("""revision""" , [None, """v2"""] ) def __lowerCamelCase ( __lowerCAmelCase : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any ) -> Dict: __UpperCamelCase : Union[str, Any] = hf_hub_url(repo_id=SCREAMING_SNAKE_CASE__ , path=SCREAMING_SNAKE_CASE__ , revision=SCREAMING_SNAKE_CASE__ ) assert url == f'https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(SCREAMING_SNAKE_CASE__ )}'
269
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :Union[str, Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Any = patch_size UpperCamelCase :List[str] = num_channels UpperCamelCase :int = is_training UpperCamelCase :str = use_labels UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = backbone_out_indices UpperCamelCase :str = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :int = backbone_featmap_shape UpperCamelCase :Any = scope UpperCamelCase :int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Dict = (image_size // patch_size) ** 2 UpperCamelCase :List[str] = num_patches + 1 def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Tuple =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Tuple =False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Union[str, Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Any = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = False UpperCamelCase :List[Any] = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Any: pass @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = prepare_img() UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :int = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging a = logging.get_logger(__name__) class _A ( __lowercase ): __a = ['input_features', 'attention_mask'] def __init__( self , _SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=1_6000 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=25 , _SCREAMING_SNAKE_CASE="hamming_window" , _SCREAMING_SNAKE_CASE=3_2768.0 , _SCREAMING_SNAKE_CASE=0.97 , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ): super().__init__(feature_size=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , padding_value=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = feature_size _UpperCAmelCase = sampling_rate _UpperCAmelCase = padding_value _UpperCAmelCase = hop_length _UpperCAmelCase = win_length _UpperCAmelCase = frame_signal_scale _UpperCAmelCase = preemphasis_coeff _UpperCAmelCase = mel_floor _UpperCAmelCase = normalize_means _UpperCAmelCase = normalize_vars _UpperCAmelCase = win_function _UpperCAmelCase = return_attention_mask _UpperCAmelCase = win_length * sampling_rate // 1000 _UpperCAmelCase = hop_length * sampling_rate // 1000 _UpperCAmelCase = optimal_fft_length(self.sample_size ) _UpperCAmelCase = (self.n_fft // 2) + 1 def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE ): if self.win_function == "hamming_window": _UpperCAmelCase = window_function(window_length=self.sample_size , name=self.win_function , periodic=SCREAMING_SNAKE_CASE_ ) else: _UpperCAmelCase = window_function(window_length=self.sample_size , name=self.win_function ) _UpperCAmelCase = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) _UpperCAmelCase = spectrogram( one_waveform * self.frame_signal_scale , window=SCREAMING_SNAKE_CASE_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=SCREAMING_SNAKE_CASE_ , preemphasis=self.preemphasis_coeff , mel_filters=SCREAMING_SNAKE_CASE_ , mel_floor=self.mel_floor , log_mel="""log""" , ) return msfc_features.T def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # make sure we normalize float32 arrays if self.normalize_means: _UpperCAmelCase = x[:input_length].mean(axis=0 ) _UpperCAmelCase = np.subtract(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if self.normalize_vars: _UpperCAmelCase = x[:input_length].std(axis=0 ) _UpperCAmelCase = np.divide(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if input_length < x.shape[0]: _UpperCAmelCase = padding_value # make sure array is in float32 _UpperCAmelCase = x.astype(np.floataa ) return x def UpperCAmelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ): _UpperCAmelCase = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )] def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F"The model corresponding to this feature extractor: {self} was trained using a sampling rate of" F" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with" F" {self.sampling_rate} and not {sampling_rate}." ) else: logger.warning( """It is strongly recommended to pass the ``sampling_rate`` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) _UpperCAmelCase = isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F"Only mono-channel audio is supported for input to {self}" ) _UpperCAmelCase = is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ): _UpperCAmelCase = np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _UpperCAmelCase = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _UpperCAmelCase = [raw_speech] # extract fbank features _UpperCAmelCase = [self._extract_mfsc_features(SCREAMING_SNAKE_CASE_ ) for one_waveform in raw_speech] # convert into correct format for padding _UpperCAmelCase = BatchFeature({"""input_features""": features} ) _UpperCAmelCase = self.pad( SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) # make sure list is in array format _UpperCAmelCase = padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE_ ): _UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.floataa ) for feature in input_features] _UpperCAmelCase = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: _UpperCAmelCase = [np.asarray(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: _UpperCAmelCase = ( np.array(SCREAMING_SNAKE_CASE_ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) _UpperCAmelCase = self.normalize( padded_inputs["""input_features"""] , attention_mask=SCREAMING_SNAKE_CASE_ ) if return_tensors is not None: _UpperCAmelCase = padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE_ ) return padded_inputs
518
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Union[str, Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: UpperCamelCase :Any = 128 elif "12-12" in model_name: UpperCamelCase :Union[str, Any] = 12 UpperCamelCase :Any = 12 elif "14-14" in model_name: UpperCamelCase :Optional[int] = 14 UpperCamelCase :List[str] = 14 elif "16-16" in model_name: UpperCamelCase :List[Any] = 16 UpperCamelCase :Optional[Any] = 16 else: raise ValueError('''Model not supported''' ) UpperCamelCase :Tuple = '''huggingface/label-files''' if "speech-commands" in model_name: UpperCamelCase :Optional[Any] = 35 UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json''' else: UpperCamelCase :Optional[int] = 527 UpperCamelCase :List[Any] = '''audioset-id2label.json''' UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): if "module.v" in name: UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ): for key in orig_state_dict.copy().keys(): UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: UpperCamelCase :Any = key.split('''.''' ) UpperCamelCase :str = int(key_split[3] ) UpperCamelCase :Union[str, Any] = config.hidden_size if "weight" in key: UpperCamelCase :List[str] = val[:dim, :] UpperCamelCase :Optional[Any] = val[dim : dim * 2, :] UpperCamelCase :Optional[Any] = val[-dim:, :] else: UpperCamelCase :Dict = val[:dim] UpperCamelCase :Optional[int] = val[dim : dim * 2] UpperCamelCase :List[Any] = val[-dim:] else: UpperCamelCase :Union[str, Any] = val return orig_state_dict def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[str] = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ): UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict UpperCamelCase :Optional[int] = model_name_to_url[model_name] UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE__ ) # rename some keys UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load 🤗 model UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78 UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26 UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128 UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) if "speech-commands" in model_name: UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array'''] else: UpperCamelCase :List[Any] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = waveform.squeeze().numpy() UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' ) # forward pass UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] ) elif model_name == "ast-finetuned-speech-commands-v2": UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
658
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class lowercase_ ( lowercase , lowercase ): '''simple docstring''' __snake_case = 'convnextv2' def __init__( self : int , __UpperCAmelCase : Union[str, Any]=3 , __UpperCAmelCase : Any=4 , __UpperCAmelCase : Tuple=4 , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : str="gelu" , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : Tuple=1e-1_2 , __UpperCAmelCase : Optional[Any]=0.0 , __UpperCAmelCase : int=224 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[int] , ) ->Optional[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) a = num_channels a = patch_size a = num_stages a = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes a = [3, 3, 9, 3] if depths is None else depths a = hidden_act a = initializer_range a = layer_norm_eps a = drop_path_rate a = image_size a = ['''stem'''] + [F"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] a = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
117
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip __UpperCamelCase : Optional[int] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def A ( _lowercase ): if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def A ( _lowercase , _lowercase , _lowercase ): return max(metric_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for gt in ground_truths ) def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : Union[str, Any] = [line.strip() for line in open(SCREAMING_SNAKE_CASE__ , '''r''' ).readlines()] SCREAMING_SNAKE_CASE : List[str] = [] if args.gold_data_mode == "qa": SCREAMING_SNAKE_CASE : Any = pd.read_csv(SCREAMING_SNAKE_CASE__ , sep='''\t''' , header=SCREAMING_SNAKE_CASE__ ) for answer_list in data[1]: SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(SCREAMING_SNAKE_CASE__ ) answers.append(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE : Optional[int] = [line.strip() for line in open(SCREAMING_SNAKE_CASE__ , '''r''' ).readlines()] SCREAMING_SNAKE_CASE : Any = [[reference] for reference in references] SCREAMING_SNAKE_CASE : Optional[int] = 0 for prediction, ground_truths in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): total += 1 em += metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) fa += metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE : str = 100.0 * em / total SCREAMING_SNAKE_CASE : Dict = 100.0 * fa / total logger.info(f"""F1: {fa:.2f}""" ) logger.info(f"""EM: {em:.2f}""" ) def A ( _lowercase , _lowercase , _lowercase ): SCREAMING_SNAKE_CASE : List[Any] = args.k SCREAMING_SNAKE_CASE : int = [line.strip() for line in open(SCREAMING_SNAKE_CASE__ , '''r''' ).readlines()] SCREAMING_SNAKE_CASE : Dict = [line.strip() for line in open(SCREAMING_SNAKE_CASE__ , '''r''' ).readlines()] SCREAMING_SNAKE_CASE : Optional[Any] = 0 for hypo, reference in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE : Union[str, Any] = set(hypo.split('''\t''' )[:k] ) SCREAMING_SNAKE_CASE : Optional[int] = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k SCREAMING_SNAKE_CASE : Tuple = 100.0 * em / total logger.info(f"""Precision@{k}: {em: .2f}""" ) def A ( _lowercase , _lowercase , _lowercase ): def strip_title(_lowercase ): if title.startswith('''"''' ): SCREAMING_SNAKE_CASE : Optional[int] = title[1:] if title.endswith('''"''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = title[:-1] return title SCREAMING_SNAKE_CASE : int = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , )['''input_ids'''].to(args.device ) SCREAMING_SNAKE_CASE : Tuple = rag_model.rag.question_encoder(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE : str = question_enc_outputs[0] SCREAMING_SNAKE_CASE : List[Any] = rag_model.retriever( SCREAMING_SNAKE_CASE__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='''pt''' , ) SCREAMING_SNAKE_CASE : int = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) SCREAMING_SNAKE_CASE : List[str] = [] for docs in all_docs: SCREAMING_SNAKE_CASE : str = [strip_title(SCREAMING_SNAKE_CASE__ ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(SCREAMING_SNAKE_CASE__ ) ) return provenance_strings def A ( _lowercase , _lowercase , _lowercase ): with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict.input_ids.to(args.device ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs_dict.attention_mask.to(args.device ) SCREAMING_SNAKE_CASE : List[Any] = rag_model.generate( # rag_model overwrites generate SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=SCREAMING_SNAKE_CASE__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) SCREAMING_SNAKE_CASE : Optional[int] = rag_model.retriever.generator_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) if args.print_predictions: for q, a in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): logger.info('''Q: {} - A: {}'''.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) return answers def A ( ): SCREAMING_SNAKE_CASE : Any = argparse.ArgumentParser() parser.add_argument( '''--model_type''' , choices=['''rag_sequence''', '''rag_token''', '''bart'''] , type=SCREAMING_SNAKE_CASE__ , help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ) , ) parser.add_argument( '''--index_name''' , default=SCREAMING_SNAKE_CASE__ , choices=['''exact''', '''compressed''', '''legacy'''] , type=SCREAMING_SNAKE_CASE__ , help='''RAG model retriever type''' , ) parser.add_argument( '''--index_path''' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , help='''Path to the retrieval index''' , ) parser.add_argument('''--n_docs''' , default=5 , type=SCREAMING_SNAKE_CASE__ , help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--eval_mode''' , choices=['''e2e''', '''retrieval'''] , default='''e2e''' , type=SCREAMING_SNAKE_CASE__ , help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ) , ) parser.add_argument('''--k''' , default=1 , type=SCREAMING_SNAKE_CASE__ , help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='''Path to a file containing evaluation samples''' , ) parser.add_argument( '''--gold_data_path''' , default=SCREAMING_SNAKE_CASE__ , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='''Path to a tab-separated file with gold samples''' , ) parser.add_argument( '''--gold_data_mode''' , default='''qa''' , type=SCREAMING_SNAKE_CASE__ , choices=['''qa''', '''ans'''] , help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ) , ) parser.add_argument( '''--predictions_path''' , type=SCREAMING_SNAKE_CASE__ , default='''predictions.txt''' , help='''Name of the predictions file, to be stored in the checkpoints directory''' , ) parser.add_argument( '''--eval_all_checkpoints''' , action='''store_true''' , help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''' , ) parser.add_argument( '''--eval_batch_size''' , default=8 , type=SCREAMING_SNAKE_CASE__ , help='''Batch size per GPU/CPU for evaluation.''' , ) parser.add_argument( '''--recalculate''' , help='''Recalculate predictions even if the prediction file exists''' , action='''store_true''' , ) parser.add_argument( '''--num_beams''' , default=4 , type=SCREAMING_SNAKE_CASE__ , help='''Number of beams to be used when generating answers''' , ) parser.add_argument('''--min_length''' , default=1 , type=SCREAMING_SNAKE_CASE__ , help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''' , default=50 , type=SCREAMING_SNAKE_CASE__ , help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''' , action='''store_true''' , help='''If True, prints predictions while evaluating.''' , ) parser.add_argument( '''--print_docs''' , action='''store_true''' , help='''If True, prints docs retried while generating.''' , ) SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE : int = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def A ( _lowercase ): SCREAMING_SNAKE_CASE : List[str] = {} if args.model_type is None: SCREAMING_SNAKE_CASE : List[str] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): SCREAMING_SNAKE_CASE : Optional[int] = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration SCREAMING_SNAKE_CASE : Any = args.n_docs if args.index_name is not None: SCREAMING_SNAKE_CASE : List[str] = args.index_name if args.index_path is not None: SCREAMING_SNAKE_CASE : Optional[int] = args.index_path else: SCREAMING_SNAKE_CASE : Union[str, Any] = BartForConditionalGeneration SCREAMING_SNAKE_CASE : int = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''' , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE : str = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k SCREAMING_SNAKE_CASE : Tuple = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(SCREAMING_SNAKE_CASE__ , args.predictions_path , args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(SCREAMING_SNAKE_CASE__ ) ) logger.info(''' Batch size = %d''' , args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): SCREAMING_SNAKE_CASE : int = RagRetriever.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE : Any = model_class.from_pretrained(SCREAMING_SNAKE_CASE__ , retriever=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) model.retriever.init_retrieval() else: SCREAMING_SNAKE_CASE : Union[str, Any] = model_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) model.to(args.device ) with open(args.evaluation_set , '''r''' ) as eval_file, open(args.predictions_path , '''w''' ) as preds_file: SCREAMING_SNAKE_CASE : Dict = [] for line in tqdm(SCREAMING_SNAKE_CASE__ ): questions.append(line.strip() ) if len(SCREAMING_SNAKE_CASE__ ) == args.eval_batch_size: SCREAMING_SNAKE_CASE : Dict = evaluate_batch_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) preds_file.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) + '''\n''' ) preds_file.flush() SCREAMING_SNAKE_CASE : Optional[int] = [] if len(SCREAMING_SNAKE_CASE__ ) > 0: SCREAMING_SNAKE_CASE : Any = evaluate_batch_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) preds_file.write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) preds_file.flush() score_fn(SCREAMING_SNAKE_CASE__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": __UpperCamelCase : Optional[int] = get_args() main(args)
248
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = """\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ __snake_case = """\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ __snake_case = R""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Tuple = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0 UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ ) return { "accuracy": accuracy, }
658
0
import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase__ ( __lowercase ): def __init__(self : Any , snake_case_ : List[Any] , snake_case_ : Dict=1_3 , snake_case_ : Any=7 , snake_case_ : Union[str, Any]=True , snake_case_ : Optional[Any]=True , snake_case_ : Tuple=True , snake_case_ : Optional[int]=True , snake_case_ : Optional[Any]=9_9 , snake_case_ : Any=3_2 , snake_case_ : List[str]=5 , snake_case_ : Dict=4 , snake_case_ : Any=3_7 , snake_case_ : str="gelu" , snake_case_ : List[Any]=0.1 , snake_case_ : Tuple=0.1 , snake_case_ : Any=5_1_2 , snake_case_ : int=1_6 , snake_case_ : int=2 , snake_case_ : Any=0.02 , snake_case_ : List[Any]=False , snake_case_ : Tuple=True , snake_case_ : str="None" , snake_case_ : Optional[int]=3 , snake_case_ : str=4 , snake_case_ : Tuple=None , ): __a : List[str] = parent __a : List[Any] = batch_size __a : List[Any] = seq_length __a : Optional[int] = is_training __a : Dict = use_input_mask __a : List[Any] = use_token_type_ids __a : Dict = use_labels __a : int = vocab_size __a : int = hidden_size __a : List[str] = num_hidden_layers __a : Dict = num_attention_heads __a : Optional[int] = intermediate_size __a : Union[str, Any] = hidden_act __a : Dict = hidden_dropout_prob __a : List[Any] = attention_probs_dropout_prob __a : str = max_position_embeddings __a : Dict = type_vocab_size __a : str = type_sequence_label_size __a : Optional[Any] = initializer_range __a : List[Any] = num_labels __a : Optional[Any] = num_choices __a : str = relative_attention __a : Tuple = position_biased_input __a : Dict = pos_att_type __a : Optional[int] = scope def lowerCAmelCase (self : Any ): __a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : List[str] = None if self.use_input_mask: __a : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __a : Dict = None if self.use_token_type_ids: __a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Any = None __a : List[str] = None __a : Union[str, Any] = None if self.use_labels: __a : List[str] = 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 : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __a : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase (self : Optional[Any] ): return DebertaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def lowerCAmelCase (self : List[str] ): __a : Tuple = self.get_config() __a : List[Any] = 3_0_0 return config def lowerCAmelCase (self : Optional[Any] , snake_case_ : Union[str, Any] ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def lowerCAmelCase (self : List[Any] , snake_case_ : Dict , snake_case_ : int , snake_case_ : Optional[int] , snake_case_ : Tuple , snake_case_ : str , snake_case_ : str , snake_case_ : int ): __a : List[str] = DebertaModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __a : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] __a : str = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ )[0] __a : Tuple = model(SCREAMING_SNAKE_CASE_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def lowerCAmelCase (self : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Optional[Any] , snake_case_ : Dict , snake_case_ : int , snake_case_ : List[Any] ): __a : Dict = DebertaForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __a : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase (self : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : int , snake_case_ : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : List[Any] , snake_case_ : Dict , snake_case_ : str ): __a : List[Any] = self.num_labels __a : Optional[int] = DebertaForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __a : int = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase (self : Dict , snake_case_ : Optional[Any] , snake_case_ : List[Any] , snake_case_ : str , snake_case_ : str , snake_case_ : Any , snake_case_ : List[str] , snake_case_ : int ): __a : int = self.num_labels __a : Tuple = DebertaForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __a : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase (self : Optional[Any] , snake_case_ : Optional[Any] , snake_case_ : Tuple , snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : Dict , snake_case_ : int , snake_case_ : str ): __a : Tuple = DebertaForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __a : List[Any] = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=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 lowerCAmelCase (self : str ): __a : Dict = self.prepare_config_and_inputs() ( __a ) : str = config_and_inputs __a : List[str] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( __lowercase ,__lowercase ,unittest.TestCase ): _SCREAMING_SNAKE_CASE : Tuple = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Union[str, Any] = ( { 'feature-extraction': DebertaModel, 'fill-mask': DebertaForMaskedLM, 'question-answering': DebertaForQuestionAnswering, 'text-classification': DebertaForSequenceClassification, 'token-classification': DebertaForTokenClassification, 'zero-shot': DebertaForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : Optional[int] = True _SCREAMING_SNAKE_CASE : List[Any] = False _SCREAMING_SNAKE_CASE : Any = False _SCREAMING_SNAKE_CASE : Optional[int] = False _SCREAMING_SNAKE_CASE : List[str] = False def lowerCAmelCase (self : List[Any] ): __a : Optional[int] = DebertaModelTester(self ) __a : List[str] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=3_7 ) def lowerCAmelCase (self : Dict ): self.config_tester.run_common_tests() def lowerCAmelCase (self : Any ): __a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase (self : Any ): __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase (self : str ): __a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase (self : int ): __a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase (self : Dict ): __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def lowerCAmelCase (self : List[Any] ): for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a : Optional[Any] = DebertaModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def lowerCAmelCase (self : Optional[Any] ): pass @slow def lowerCAmelCase (self : str ): __a : List[str] = DebertaModel.from_pretrained('''microsoft/deberta-base''' ) __a : Union[str, Any] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) __a : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __a : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ )[0] # compare the actual values for a slice. __a : Tuple = torch.tensor( [[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , SCREAMING_SNAKE_CASE_ , atol=1E-4 ) , f"{output[:, 1:4, 1:4]}" )
521
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def _A ( ): UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase :Dict = parser.parse_args() return args.f def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ): UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) raise ValueError(F'''can\'t find {path}''' ) __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = self.get_auto_remove_tmp_dir() UpperCamelCase :Any = F''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :List[str] = F''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :int = F''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def UpperCAmelCase ( self ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2 UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[int] = F''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :Dict = F''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
658
0
"""simple docstring""" import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class lowercase ( lowercase__ ): def __init__(self : Optional[int] ,SCREAMING_SNAKE_CASE_ : str=0.01 ,SCREAMING_SNAKE_CASE_ : Optional[Any]=1_000 ) -> str: """simple docstring""" lowerCAmelCase = p_stop lowerCAmelCase = max_length def __iter__(self : Optional[Any] ) -> Tuple: """simple docstring""" lowerCAmelCase = 0 lowerCAmelCase = False while not stop and count < self.max_length: yield count count += 1 lowerCAmelCase = random.random() < self.p_stop class lowercase ( unittest.TestCase ): def UpperCAmelCase (self : Any ,SCREAMING_SNAKE_CASE_ : Any ,SCREAMING_SNAKE_CASE_ : List[Any] ,SCREAMING_SNAKE_CASE_ : int=False ,SCREAMING_SNAKE_CASE_ : Tuple=True ) -> Optional[int]: """simple docstring""" lowerCAmelCase = [ BatchSamplerShard(SCREAMING_SNAKE_CASE_ ,2 ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) for i in range(2 ) ] lowerCAmelCase = [list(SCREAMING_SNAKE_CASE_ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(SCREAMING_SNAKE_CASE_ ) for shard in batch_sampler_shards] ,[len(SCREAMING_SNAKE_CASE_ ) for e in expected] ) self.assertListEqual(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : List[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) # Expected shouldn't change self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. lowerCAmelCase = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is very small. lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : str ) -> Optional[int]: """simple docstring""" lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) # Expected shouldn't change self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size. lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is very small. lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : List[str] ) -> List[Any]: """simple docstring""" lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) # Expected shouldn't change self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. lowerCAmelCase = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(20 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is very small. lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[[0, 1]], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=3 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : int ) -> Dict: """simple docstring""" lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(24 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) # Expected shouldn't change self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size. lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(22 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(21 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) # Check the shards when the dataset is very small. lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[[0, 1]], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = BatchSampler(range(2 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [[], []] self.check_batch_sampler_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Optional[int] ) -> List[str]: """simple docstring""" lowerCAmelCase = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] lowerCAmelCase = [BatchSamplerShard(SCREAMING_SNAKE_CASE_ ,2 ,SCREAMING_SNAKE_CASE_ ,even_batches=SCREAMING_SNAKE_CASE_ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) ,3 ) self.assertEqual(len(batch_sampler_shards[1] ) ,2 ) self.assertListEqual(list(batch_sampler_shards[0] ) ,[[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) ,[[3, 4], [9, 10, 11]] ) def UpperCAmelCase (self : Any ,SCREAMING_SNAKE_CASE_ : str ,SCREAMING_SNAKE_CASE_ : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : Dict ,SCREAMING_SNAKE_CASE_ : Any=False ,SCREAMING_SNAKE_CASE_ : List[str]=2 ,SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ) -> List[Any]: """simple docstring""" random.seed(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = list(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = [ IterableDatasetShard( SCREAMING_SNAKE_CASE_ ,batch_size=SCREAMING_SNAKE_CASE_ ,drop_last=SCREAMING_SNAKE_CASE_ ,num_processes=SCREAMING_SNAKE_CASE_ ,process_index=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ,) for i in range(SCREAMING_SNAKE_CASE_ ) ] lowerCAmelCase = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(SCREAMING_SNAKE_CASE_ ) iterable_dataset_lists.append(list(SCREAMING_SNAKE_CASE_ ) ) lowerCAmelCase = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size lowerCAmelCase = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(len(SCREAMING_SNAKE_CASE_ ) % shard_batch_size == 0 ) lowerCAmelCase = [] for idx in range(0 ,len(SCREAMING_SNAKE_CASE_ ) ,SCREAMING_SNAKE_CASE_ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(SCREAMING_SNAKE_CASE_ ) < len(SCREAMING_SNAKE_CASE_ ): reference += reference self.assertListEqual(SCREAMING_SNAKE_CASE_ ,reference[: len(SCREAMING_SNAKE_CASE_ )] ) def UpperCAmelCase (self : Dict ) -> int: """simple docstring""" lowerCAmelCase = 42 lowerCAmelCase = RandomIterableDataset() self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) # Edge case with a very small dataset lowerCAmelCase = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) self.check_iterable_dataset_shards(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ,split_batches=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : Tuple ) -> Any: """simple docstring""" lowerCAmelCase = BatchSampler(range(16 ) ,batch_size=4 ,drop_last=SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = SkipBatchSampler(SCREAMING_SNAKE_CASE_ ,2 ) self.assertListEqual(list(SCREAMING_SNAKE_CASE_ ) ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase (self : Tuple ) -> Optional[int]: """simple docstring""" lowerCAmelCase = SkipDataLoader(list(range(16 ) ) ,batch_size=4 ,skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase (self : Dict ) -> Tuple: """simple docstring""" lowerCAmelCase = DataLoader(list(range(16 ) ) ,batch_size=4 ) lowerCAmelCase = skip_first_batches(SCREAMING_SNAKE_CASE_ ,num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] ,[[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase (self : str ) -> Tuple: """simple docstring""" lowerCAmelCase = DataLoaderShard(list(range(16 ) ) ,batch_size=4 ) for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) def UpperCAmelCase (self : str ) -> Optional[int]: """simple docstring""" Accelerator() lowerCAmelCase = DataLoaderDispatcher(range(16 ) ,batch_size=4 ) for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(SCREAMING_SNAKE_CASE_ ): self.assertEqual(dataloader.end_of_dataloader ,idx == 3 )
535
from __future__ import annotations from collections.abc import Callable def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ): UpperCamelCase :Optional[Any] = x_start UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCamelCase :Any = (x_end - x_start) / steps + xa UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCamelCase :Optional[int] = xa UpperCamelCase :List[str] = fxa return area if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE__ : int ): return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 10_00_00: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
658
0
"""simple docstring""" from collections import deque from math import floor from random import random from time import time class lowerCamelCase__ : def __init__( self ) -> List[Any]: """simple docstring""" lowercase : List[str] = {} def _UpperCAmelCase ( self , snake_case , snake_case , snake_case=1 ) -> Optional[Any]: """simple docstring""" if self.graph.get(SCREAMING_SNAKE_CASE_ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowercase : List[str] = [[w, v]] if not self.graph.get(SCREAMING_SNAKE_CASE_ ): lowercase : str = [] def _UpperCAmelCase ( self ) -> Optional[Any]: """simple docstring""" return list(self.graph ) def _UpperCAmelCase ( self , snake_case , snake_case ) -> List[str]: """simple docstring""" if self.graph.get(SCREAMING_SNAKE_CASE_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(SCREAMING_SNAKE_CASE_ ) def _UpperCAmelCase ( self , snake_case=-2 , snake_case=-1 ) -> Union[str, Any]: """simple docstring""" if s == d: return [] lowercase : Optional[Any] = [] lowercase : Union[str, Any] = [] if s == -2: lowercase : Tuple = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : str = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : Tuple = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(SCREAMING_SNAKE_CASE_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowercase : Dict = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : List[Any] = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Any = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return visited def _UpperCAmelCase ( self , snake_case=-1 ) -> Optional[int]: """simple docstring""" if c == -1: lowercase : List[str] = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(SCREAMING_SNAKE_CASE_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): lowercase : str = floor(random() * c ) + 1 if n != i: self.add_pair(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) def _UpperCAmelCase ( self , snake_case=-2 ) -> Tuple: """simple docstring""" lowercase : Union[str, Any] = deque() lowercase : Optional[Any] = [] if s == -2: lowercase : Optional[int] = list(self.graph )[0] d.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) while d: lowercase : List[str] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _UpperCAmelCase ( self , snake_case ) -> Union[str, Any]: """simple docstring""" lowercase : Optional[Any] = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def _UpperCAmelCase ( self , snake_case ) -> List[Any]: """simple docstring""" return len(self.graph[u] ) def _UpperCAmelCase ( self , snake_case=-2 ) -> Any: """simple docstring""" lowercase : str = [] lowercase : Optional[Any] = [] if s == -2: lowercase : Dict = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : Union[str, Any] = s lowercase : List[str] = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : str = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase : Tuple = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : List[Any] = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Any = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return sorted_nodes def _UpperCAmelCase ( self ) -> Dict: """simple docstring""" lowercase : int = [] lowercase : int = [] lowercase : Union[str, Any] = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : Union[str, Any] = -2 lowercase : List[str] = [] lowercase : Optional[Any] = s lowercase : Optional[Any] = False lowercase : Any = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase : List[str] = True if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : List[str] = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Union[str, Any] = False indirect_parents.append(SCREAMING_SNAKE_CASE_ ) lowercase : Union[str, Any] = s lowercase : List[Any] = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return list(SCREAMING_SNAKE_CASE_ ) def _UpperCAmelCase ( self ) -> Optional[int]: """simple docstring""" lowercase : int = [] lowercase : Optional[Any] = [] lowercase : Union[str, Any] = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : str = -2 lowercase : Any = [] lowercase : List[str] = s lowercase : Dict = False lowercase : List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : str = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase : Dict = len(SCREAMING_SNAKE_CASE_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase : Tuple = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase : Dict = True if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : Any = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Optional[Any] = False indirect_parents.append(SCREAMING_SNAKE_CASE_ ) lowercase : str = s lowercase : Optional[Any] = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return False def _UpperCAmelCase ( self , snake_case=-2 , snake_case=-1 ) -> int: """simple docstring""" lowercase : int = time() self.dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase : List[Any] = time() return end - begin def _UpperCAmelCase ( self , snake_case=-2 ) -> Dict: """simple docstring""" lowercase : Optional[int] = time() self.bfs(SCREAMING_SNAKE_CASE_ ) lowercase : Dict = time() return end - begin class lowerCamelCase__ : def __init__( self ) -> Optional[int]: """simple docstring""" lowercase : Optional[Any] = {} def _UpperCAmelCase ( self , snake_case , snake_case , snake_case=1 ) -> Optional[Any]: """simple docstring""" # check if the u exists if self.graph.get(SCREAMING_SNAKE_CASE_ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowercase : int = [[w, v]] # add the other way if self.graph.get(SCREAMING_SNAKE_CASE_ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowercase : Dict = [[w, u]] def _UpperCAmelCase ( self , snake_case , snake_case ) -> str: """simple docstring""" if self.graph.get(SCREAMING_SNAKE_CASE_ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(SCREAMING_SNAKE_CASE_ ) # the other way round if self.graph.get(SCREAMING_SNAKE_CASE_ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(SCREAMING_SNAKE_CASE_ ) def _UpperCAmelCase ( self , snake_case=-2 , snake_case=-1 ) -> Any: """simple docstring""" if s == d: return [] lowercase : Any = [] lowercase : List[Any] = [] if s == -2: lowercase : List[Any] = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : int = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : Optional[int] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(SCREAMING_SNAKE_CASE_ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowercase : Dict = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : Any = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Optional[int] = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return visited def _UpperCAmelCase ( self , snake_case=-1 ) -> List[str]: """simple docstring""" if c == -1: lowercase : Union[str, Any] = floor(random() * 1_0_0_0_0 ) + 1_0 for i in range(SCREAMING_SNAKE_CASE_ ): # every vertex has max 100 edges for _ in range(floor(random() * 1_0_2 ) + 1 ): lowercase : Union[str, Any] = floor(random() * c ) + 1 if n != i: self.add_pair(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , 1 ) def _UpperCAmelCase ( self , snake_case=-2 ) -> List[Any]: """simple docstring""" lowercase : Any = deque() lowercase : List[str] = [] if s == -2: lowercase : Union[str, Any] = list(self.graph )[0] d.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) while d: lowercase : Optional[int] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def _UpperCAmelCase ( self , snake_case ) -> Optional[Any]: """simple docstring""" return len(self.graph[u] ) def _UpperCAmelCase ( self ) -> Optional[Any]: """simple docstring""" lowercase : List[str] = [] lowercase : Optional[int] = [] lowercase : List[str] = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : str = -2 lowercase : Union[str, Any] = [] lowercase : List[Any] = s lowercase : List[str] = False lowercase : List[str] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : int = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase : Optional[int] = len(SCREAMING_SNAKE_CASE_ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase : Optional[int] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase : Dict = True if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : Tuple = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : Tuple = False indirect_parents.append(SCREAMING_SNAKE_CASE_ ) lowercase : Dict = s lowercase : Optional[Any] = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return list(SCREAMING_SNAKE_CASE_ ) def _UpperCAmelCase ( self ) -> List[Any]: """simple docstring""" lowercase : int = [] lowercase : Tuple = [] lowercase : List[str] = list(self.graph )[0] stack.append(SCREAMING_SNAKE_CASE_ ) visited.append(SCREAMING_SNAKE_CASE_ ) lowercase : Tuple = -2 lowercase : int = [] lowercase : Tuple = s lowercase : Optional[int] = False lowercase : Dict = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase : Optional[Any] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase : Union[str, Any] = len(SCREAMING_SNAKE_CASE_ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase : Optional[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase : Optional[int] = True if len(SCREAMING_SNAKE_CASE_ ) != 0: lowercase : int = stack[len(SCREAMING_SNAKE_CASE_ ) - 1] else: lowercase : List[Any] = False indirect_parents.append(SCREAMING_SNAKE_CASE_ ) lowercase : Optional[int] = s lowercase : Any = ss # check if se have reached the starting point if len(SCREAMING_SNAKE_CASE_ ) == 0: return False def _UpperCAmelCase ( self ) -> List[str]: """simple docstring""" return list(self.graph ) def _UpperCAmelCase ( self , snake_case=-2 , snake_case=-1 ) -> Any: """simple docstring""" lowercase : int = time() self.dfs(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowercase : List[str] = time() return end - begin def _UpperCAmelCase ( self , snake_case=-2 ) -> List[Any]: """simple docstring""" lowercase : List[Any] = time() self.bfs(SCREAMING_SNAKE_CASE_ ) lowercase : Dict = time() return end - begin
607
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :str = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = 10 UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps[0] UpperCamelCase :Union[str, Any] = scheduler.timesteps[1] UpperCamelCase :str = self.dummy_sample UpperCamelCase :List[str] = 0.1 * sample UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase ( self ) -> List[str]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # 1. scale model input UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :Tuple = pred_prev_sample UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = scheduler.timesteps UpperCamelCase :int = torch.manual_seed(0 ) UpperCamelCase :str = self.dummy_model() UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :int = pred_prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :Tuple = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = [39, 30, 12, 1, 0] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[int] = self.scheduler_classes[0] UpperCamelCase :List[str] = self.get_scheduler_config() UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
658
0
def UpperCamelCase_ ( __a , __a ) -> List[str]: _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 a__ : Union[str, Any] = float("-inf" ) for i in range(1 , n + 1 ): a__ : str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def UpperCamelCase_ ( __a , __a ) -> Optional[int]: _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a__ : Dict = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase_ ( __a , __a , __a ) -> Optional[int]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: a__ : Dict = float("-inf" ) for i in range(1 , n + 1 ): a__ : Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) a__ : str = max_revenue return max_rev[n] def UpperCamelCase_ ( __a , __a ) -> List[Any]: _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. a__ : List[str] = [float("-inf" ) for _ in range(n + 1 )] a__ : Dict = 0 for i in range(1 , n + 1 ): a__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): a__ : Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) a__ : Tuple = max_revenue_i return max_rev[n] def UpperCamelCase_ ( __a , __a ) -> List[Any]: if n < 0: a__ : Any = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): a__ : Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' f'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase_ ( ) -> Tuple: a__ : Dict = [6, 10, 12, 15, 20, 23] a__ : List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. a__ : str = 36 a__ : int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a__ : Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a__ : str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
37
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
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 A__ (snake_case : Optional[int] ) -> Any: __UpperCamelCase : List[str] = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: __UpperCamelCase : Dict = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: __UpperCamelCase : Any = 4 __UpperCamelCase : str = 48 __UpperCamelCase : str = '''pixelshuffle_aux''' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: __UpperCamelCase : Union[str, Any] = [6, 6, 6, 6] __UpperCamelCase : Union[str, Any] = 60 __UpperCamelCase : Any = [6, 6, 6, 6] __UpperCamelCase : int = '''pixelshuffledirect''' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: __UpperCamelCase : Union[str, Any] = 4 __UpperCamelCase : Optional[Any] = '''nearest+conv''' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: __UpperCamelCase : str = 1 __UpperCamelCase : Tuple = 1 __UpperCamelCase : List[str] = 1_26 __UpperCamelCase : List[str] = 7 __UpperCamelCase : Optional[Any] = 2_55.0 __UpperCamelCase : Union[str, Any] = '''''' return config def A__ (snake_case : Union[str, Any] , snake_case : int ) -> List[str]: if "patch_embed.proj" in name and "layers" not in name: __UpperCamelCase : List[str] = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __UpperCamelCase : List[str] = name.replace("""patch_embed.norm""" , """embeddings.patch_embeddings.layernorm""" ) if "layers" in name: __UpperCamelCase : List[Any] = name.replace("""layers""" , """encoder.stages""" ) if "residual_group.blocks" in name: __UpperCamelCase : List[str] = name.replace("""residual_group.blocks""" , """layers""" ) if "attn.proj" in name: __UpperCamelCase : Optional[int] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __UpperCamelCase : Any = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __UpperCamelCase : Any = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __UpperCamelCase : Any = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __UpperCamelCase : Union[str, Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __UpperCamelCase : Dict = name.replace("""mlp.fc2""" , """output.dense""" ) if "q_bias" in name: __UpperCamelCase : Any = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: __UpperCamelCase : Tuple = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: __UpperCamelCase : Optional[int] = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: __UpperCamelCase : Optional[int] = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if "patch_embed.proj" in name: __UpperCamelCase : Any = name.replace("""patch_embed.proj""" , """patch_embed.projection""" ) if name == "norm.weight": __UpperCamelCase : Optional[int] = '''layernorm.weight''' if name == "norm.bias": __UpperCamelCase : Optional[Any] = '''layernorm.bias''' if "conv_first" in name: __UpperCamelCase : int = name.replace("""conv_first""" , """first_convolution""" ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: __UpperCamelCase : Tuple = name.replace("""conv_last""" , """final_convolution""" ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: __UpperCamelCase : Dict = name.replace("""conv_before_upsample.0""" , """conv_before_upsample""" ) if "upsample.0" in name: __UpperCamelCase : Union[str, Any] = name.replace("""upsample.0""" , """upsample.convolution_0""" ) if "upsample.2" in name: __UpperCamelCase : str = name.replace("""upsample.2""" , """upsample.convolution_1""" ) __UpperCamelCase : Tuple = '''upsample.''' + name elif config.upsampler == "pixelshuffledirect": __UpperCamelCase : List[Any] = name.replace("""upsample.0.weight""" , """upsample.conv.weight""" ) __UpperCamelCase : Dict = name.replace("""upsample.0.bias""" , """upsample.conv.bias""" ) else: pass else: __UpperCamelCase : str = '''swin2sr.''' + name return name def A__ (snake_case : str , snake_case : int ) -> Optional[Any]: for key in orig_state_dict.copy().keys(): __UpperCamelCase : Tuple = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: __UpperCamelCase : int = key.split(""".""" ) __UpperCamelCase : Optional[int] = int(key_split[1] ) __UpperCamelCase : Optional[int] = int(key_split[4] ) __UpperCamelCase : Any = config.embed_dim if "weight" in key: __UpperCamelCase : Tuple = val[:dim, :] __UpperCamelCase : Union[str, Any] = val[dim : dim * 2, :] __UpperCamelCase : Any = val[-dim:, :] else: __UpperCamelCase : Dict = val[:dim] __UpperCamelCase : Dict = val[dim : dim * 2] __UpperCamelCase : Any = val[-dim:] pass else: __UpperCamelCase : Optional[Any] = val return orig_state_dict def A__ (snake_case : List[str] , snake_case : int , snake_case : int ) -> Optional[Any]: __UpperCamelCase : Optional[int] = get_config(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase : Tuple = SwinaSRForImageSuperResolution(SCREAMING_SNAKE_CASE__ ) model.eval() __UpperCamelCase : int = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" ) __UpperCamelCase : Tuple = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase : Union[str, Any] = model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: raise ValueError("""Missing keys when converting: {}""".format(SCREAMING_SNAKE_CASE__ ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F'''Unexpected key {key} in state_dict''' ) # verify values __UpperCamelCase : Optional[Any] = '''https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true''' __UpperCamelCase : List[str] = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert("""RGB""" ) __UpperCamelCase : str = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values __UpperCamelCase : List[str] = 1_26 if '''Jpeg''' in checkpoint_url else 2_56 __UpperCamelCase : Tuple = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) __UpperCamelCase : Any = transforms(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) if config.num_channels == 1: __UpperCamelCase : List[str] = pixel_values[:, 0, :, :].unsqueeze(1 ) __UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE__ ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: __UpperCamelCase : Any = torch.Size([1, 3, 5_12, 5_12] ) __UpperCamelCase : Dict = torch.tensor( [[-0.7087, -0.7138, -0.6721], [-0.8340, -0.8095, -0.7298], [-0.9149, -0.8414, -0.7940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: __UpperCamelCase : Tuple = torch.Size([1, 3, 10_24, 10_24] ) __UpperCamelCase : str = torch.tensor( [[-0.7775, -0.8105, -0.8933], [-0.7764, -0.8356, -0.9225], [-0.7976, -0.8686, -0.9579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here __UpperCamelCase : Dict = torch.Size([1, 3, 10_24, 10_24] ) __UpperCamelCase : Dict = torch.tensor( [[-0.8035, -0.7504, -0.7491], [-0.8538, -0.8124, -0.7782], [-0.8804, -0.8651, -0.8493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: __UpperCamelCase : Dict = torch.Size([1, 3, 5_12, 5_12] ) __UpperCamelCase : List[str] = torch.tensor( [[-0.7669, -0.8662, -0.8767], [-0.8810, -0.9962, -0.9820], [-0.9340, -1.0322, -1.1149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: __UpperCamelCase : Any = torch.Size([1, 3, 10_24, 10_24] ) __UpperCamelCase : Optional[Any] = torch.tensor( [[-0.5238, -0.5557, -0.6321], [-0.6016, -0.5903, -0.6391], [-0.6244, -0.6334, -0.6889]] ) 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] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) print("""Looks ok!""" ) __UpperCamelCase : Optional[int] = { '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''': ( '''swin2SR-classical-sr-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth''': ( '''swin2SR-classical-sr-x4-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth''': ( '''swin2SR-compressed-sr-x4-48''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth''': ( '''swin2SR-lightweight-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth''': ( '''swin2SR-realworld-sr-x4-64-bsrgan-psnr''' ), } __UpperCamelCase : 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(SCREAMING_SNAKE_CASE__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: model.push_to_hub(F'''caidas/{model_name}''' ) processor.push_to_hub(F'''caidas/{model_name}''' ) if __name__ == "__main__": a__ = 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__ = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
279
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: return None class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: return None class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =[ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[int]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> int: from transformers import BertModel UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCAmelCase ( self ) -> str: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[str]: from transformers import BertModel UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' ) @require_tf @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[Any]: from transformers import TFBertModel UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
658
0
import os import re import shutil import sys import tempfile import unittest import black a_ : int = 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_ : Any = ' def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n' class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" def _a (self ): '''simple docstring''' lowerCamelCase = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , "models/bert/" ) ) lowerCamelCase = 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 _a (self ): '''simple docstring''' lowerCamelCase = '''src/transformers''' shutil.rmtree(self.transformer_dir ) def _a (self , __a , __a , __a , __a=None ): '''simple docstring''' lowerCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: lowerCamelCase = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result lowerCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_19 ) lowerCamelCase = black.format_str(SCREAMING_SNAKE_CASE_ , mode=SCREAMING_SNAKE_CASE_ ) lowerCamelCase = 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 _a (self ): '''simple docstring''' lowerCamelCase = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead" ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a (self ): '''simple docstring''' 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 lowerCamelCase = '''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 _a (self ): '''simple docstring''' lowerCamelCase = check_copies.LOCALIZED_READMES['''README_zh-hans.md'''] lowerCamelCase = ( '''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.''' ) lowerCamelCase = ( '''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''' ) lowerCamelCase = ( '''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''' ) lowerCamelCase = 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_ ) lowerCamelCase = 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_ ) lowerCamelCase = ( '''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.''' ) lowerCamelCase = ( '''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''' ) lowerCamelCase = ( '''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''' ) lowerCamelCase = 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_ )
623
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Union[str, Any] = tempfile.mkdtemp() UpperCamelCase :List[str] = 5 # Realm tok UpperCamelCase :List[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCamelCase :Dict = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE_ , 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] ) ) UpperCamelCase :Any = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> RealmTokenizer: return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def UpperCAmelCase ( self ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = RealmConfig(num_block_records=self.num_block_records ) return config def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Tuple = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=SCREAMING_SNAKE_CASE_ , ) return block_records def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Optional[int] = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[Any] = self.get_config() UpperCamelCase :str = self.get_dummy_retriever() UpperCamelCase :int = retriever.tokenizer UpperCamelCase :Optional[Any] = np.array([0, 3] , dtype='''long''' ) UpperCamelCase :Optional[Any] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Tuple = tokenizer( ['''the fourth'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Optional[Any] = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = self.get_config() UpperCamelCase :Union[str, Any] = self.get_dummy_retriever() UpperCamelCase :Dict = retriever.tokenizer UpperCamelCase :str = np.array([0, 3, 5] , dtype='''long''' ) UpperCamelCase :List[str] = tokenizer(['''Test question'''] ).input_ids UpperCamelCase :Optional[Any] = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=SCREAMING_SNAKE_CASE_ , return_token_type_ids=SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , ).input_ids UpperCamelCase :Any = config.reader_seq_len UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = retriever( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , answer_ids=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , SCREAMING_SNAKE_CASE_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :str = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path UpperCamelCase :List[str] = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: UpperCamelCase :Tuple = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) UpperCamelCase :List[Any] = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
658
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer __UpperCamelCase : str = ["""bert-base-uncased""", """bert-base-cased"""] __UpperCamelCase : Any = """hf-internal-testing/tiny-bert-tf-only""" if is_tf_available(): class __SCREAMING_SNAKE_CASE ( tf.keras.Model ): def __init__( self , lowerCamelCase ) ->Any: '''simple docstring''' super().__init__() __a = tokenizer __a = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) __a = TFAutoModel.from_config(SCREAMING_SNAKE_CASE_ ) def __UpperCamelCase ( self , lowerCamelCase ) ->Dict: '''simple docstring''' __a = self.tokenizer(SCREAMING_SNAKE_CASE_ ) __a = self.bert(**SCREAMING_SNAKE_CASE_ ) return out["pooler_output"] @require_tf @require_tensorflow_text class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __UpperCamelCase ( self ) ->str: '''simple docstring''' super().setUp() __a = [ BertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false __a = [TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , use_fast_bert_tokenizer=SCREAMING_SNAKE_CASE_ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __a = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __a = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __UpperCamelCase ( self ) ->Tuple: '''simple docstring''' for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): __a = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors='tf' , padding='longest' ) __a = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def __UpperCamelCase ( self ) ->int: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __a = tf_tokenizer(self.paired_sentences ) __a = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def __UpperCamelCase ( self ) ->Optional[Any]: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __a = tf.function(SCREAMING_SNAKE_CASE_ ) for test_inputs in (self.test_sentences, self.paired_sentences): __a = tf.constant(SCREAMING_SNAKE_CASE_ ) __a = compiled_tokenizer(SCREAMING_SNAKE_CASE_ ) __a = tf_tokenizer(SCREAMING_SNAKE_CASE_ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __UpperCamelCase ( self ) ->Union[str, Any]: '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __a = ModelToSave(tokenizer=SCREAMING_SNAKE_CASE_ ) __a = tf.convert_to_tensor(self.test_sentences ) __a = model(SCREAMING_SNAKE_CASE_ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __a = Path(SCREAMING_SNAKE_CASE_ ) / '''saved.model''' model.save(SCREAMING_SNAKE_CASE_ ) __a = tf.keras.models.load_model(SCREAMING_SNAKE_CASE_ ) __a = loaded_model(SCREAMING_SNAKE_CASE_ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
448
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , ) -> Optional[Any]: UpperCamelCase :int = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :List[Any] = patch_size UpperCamelCase :Optional[int] = max_length UpperCamelCase :Union[str, Any] = num_mel_bins UpperCamelCase :Optional[int] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :Dict = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :str = num_attention_heads UpperCamelCase :Optional[int] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :str = type_sequence_label_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = scope UpperCamelCase :List[Any] = frequency_stride UpperCamelCase :Tuple = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) UpperCamelCase :List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 UpperCamelCase :List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 UpperCamelCase :Tuple = frequency_out_dimension * time_out_dimension UpperCamelCase :Optional[int] = num_patches + 2 def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :str = self.get_config() return config, input_values, labels def UpperCAmelCase ( self ) -> List[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = ASTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :List[Any] = {'''input_values''': input_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) UpperCamelCase_ : Any =( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[Any] =False UpperCamelCase_ : Dict =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = ASTModelTester(self ) UpperCamelCase :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason='''AST does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> str: pass def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Any = [*signature.parameters.keys()] UpperCamelCase :Optional[int] = ['''input_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Optional[int]: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :Union[str, Any] = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Any = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' ) UpperCamelCase , UpperCamelCase :Any = torchaudio.load(SCREAMING_SNAKE_CASE__ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase ( self ) -> Tuple: return ( ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.default_feature_extractor UpperCamelCase :Union[str, Any] = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = self.default_feature_extractor UpperCamelCase , UpperCamelCase :Dict = prepare_audio() UpperCamelCase :Dict = audio.squeeze().numpy() UpperCamelCase :int = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) # verify the logits UpperCamelCase :List[Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
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() UpperCamelCase = logging.get_logger(__name__) def __lowerCamelCase ( __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Union[str, Any]=False ) -> Union[str, Any]: __UpperCamelCase : Optional[Any] = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith("""head""" ): __UpperCamelCase : int = '''segformer.encoder.''' + key if key.startswith("""backbone""" ): __UpperCamelCase : Tuple = key.replace("""backbone""" , """segformer.encoder""" ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 __UpperCamelCase : List[str] = key[key.find("""patch_embed""" ) + len("""patch_embed""" )] __UpperCamelCase : List[str] = key.replace(f'patch_embed{idx}' , f'patch_embeddings.{int(SCREAMING_SNAKE_CASE__ )-1}' ) if "norm" in key: __UpperCamelCase : int = key.replace("""norm""" , """layer_norm""" ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 __UpperCamelCase : str = key[key.find("""segformer.encoder.layer_norm""" ) + len("""segformer.encoder.layer_norm""" )] __UpperCamelCase : Union[str, Any] = key.replace(f'layer_norm{idx}' , f'layer_norm.{int(SCREAMING_SNAKE_CASE__ )-1}' ) if "layer_norm1" in key: __UpperCamelCase : Union[str, Any] = key.replace("""layer_norm1""" , """layer_norm_1""" ) if "layer_norm2" in key: __UpperCamelCase : Dict = key.replace("""layer_norm2""" , """layer_norm_2""" ) if "block" in key: # replace for example block1 by block.0 __UpperCamelCase : List[str] = key[key.find("""block""" ) + len("""block""" )] __UpperCamelCase : str = key.replace(f'block{idx}' , f'block.{int(SCREAMING_SNAKE_CASE__ )-1}' ) if "attn.q" in key: __UpperCamelCase : Any = key.replace("""attn.q""" , """attention.self.query""" ) if "attn.proj" in key: __UpperCamelCase : List[str] = key.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in key: __UpperCamelCase : Optional[int] = key.replace("""attn""" , """attention.self""" ) if "fc1" in key: __UpperCamelCase : Dict = key.replace("""fc1""" , """dense1""" ) if "fc2" in key: __UpperCamelCase : str = key.replace("""fc2""" , """dense2""" ) if "linear_pred" in key: __UpperCamelCase : List[Any] = key.replace("""linear_pred""" , """classifier""" ) if "linear_fuse" in key: __UpperCamelCase : Optional[Any] = key.replace("""linear_fuse.conv""" , """linear_fuse""" ) __UpperCamelCase : Optional[Any] = key.replace("""linear_fuse.bn""" , """batch_norm""" ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 __UpperCamelCase : Optional[int] = key[key.find("""linear_c""" ) + len("""linear_c""" )] __UpperCamelCase : Dict = key.replace(f'linear_c{idx}' , f'linear_c.{int(SCREAMING_SNAKE_CASE__ )-1}' ) if key.startswith("""head""" ): __UpperCamelCase : str = key.replace("""head""" , """classifier""" ) __UpperCamelCase : List[Any] = value return new_state_dict def __lowerCamelCase ( __lowerCAmelCase : Any , __lowerCAmelCase : List[str] ) -> int: # for each of the encoder blocks: 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) __UpperCamelCase : Optional[int] = state_dict.pop(f'segformer.encoder.block.{i}.{j}.attention.self.kv.weight' ) __UpperCamelCase : str = 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 __UpperCamelCase : List[str] = kv_weight[ : config.hidden_sizes[i], : ] __UpperCamelCase : List[Any] = kv_bias[: config.hidden_sizes[i]] __UpperCamelCase : List[str] = kv_weight[ config.hidden_sizes[i] :, : ] __UpperCamelCase : List[Any] = kv_bias[ config.hidden_sizes[i] : ] def __lowerCamelCase ( ) -> Optional[int]: __UpperCamelCase : str = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __UpperCamelCase : Optional[int] = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return image @torch.no_grad() def __lowerCamelCase ( __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] ) -> Dict: __UpperCamelCase : Optional[Any] = SegformerConfig() __UpperCamelCase : Optional[Any] = False # set attributes based on model_name __UpperCamelCase : List[str] = '''huggingface/label-files''' if "segformer" in model_name: __UpperCamelCase : Any = model_name[len("""segformer.""" ) : len("""segformer.""" ) + 2] if "ade" in model_name: __UpperCamelCase : Tuple = 150 __UpperCamelCase : Any = '''ade20k-id2label.json''' __UpperCamelCase : Dict = (1, 150, 128, 128) elif "city" in model_name: __UpperCamelCase : Union[str, Any] = 19 __UpperCamelCase : str = '''cityscapes-id2label.json''' __UpperCamelCase : Optional[int] = (1, 19, 128, 128) else: raise ValueError(f'Model {model_name} not supported' ) elif "mit" in model_name: __UpperCamelCase : Optional[int] = True __UpperCamelCase : Optional[int] = model_name[4:6] __UpperCamelCase : List[str] = 1000 __UpperCamelCase : List[str] = '''imagenet-1k-id2label.json''' __UpperCamelCase : Union[str, Any] = (1, 1000) else: raise ValueError(f'Model {model_name} not supported' ) # set config attributes __UpperCamelCase : Dict = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type="""dataset""" ) , """r""" ) ) __UpperCamelCase : List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} __UpperCamelCase : Optional[int] = idalabel __UpperCamelCase : List[Any] = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": __UpperCamelCase : Optional[int] = [64, 128, 320, 512] __UpperCamelCase : int = 256 elif size == "b2": __UpperCamelCase : str = [64, 128, 320, 512] __UpperCamelCase : str = 768 __UpperCamelCase : Tuple = [3, 4, 6, 3] elif size == "b3": __UpperCamelCase : List[Any] = [64, 128, 320, 512] __UpperCamelCase : int = 768 __UpperCamelCase : List[str] = [3, 4, 18, 3] elif size == "b4": __UpperCamelCase : Optional[int] = [64, 128, 320, 512] __UpperCamelCase : str = 768 __UpperCamelCase : int = [3, 8, 27, 3] elif size == "b5": __UpperCamelCase : Optional[Any] = [64, 128, 320, 512] __UpperCamelCase : List[str] = 768 __UpperCamelCase : Optional[Any] = [3, 6, 40, 3] else: raise ValueError(f'Size {size} not supported' ) # load image processor (only resize + normalize) __UpperCamelCase : Dict = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=SCREAMING_SNAKE_CASE__ , align=SCREAMING_SNAKE_CASE__ , do_random_crop=SCREAMING_SNAKE_CASE__ ) # prepare image __UpperCamelCase : Optional[int] = prepare_img() __UpperCamelCase : str = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" ).pixel_values logger.info(f'Converting model {model_name}...' ) # load original state dict if encoder_only: __UpperCamelCase : List[str] = torch.load(SCREAMING_SNAKE_CASE__ , map_location=torch.device("""cpu""" ) ) else: __UpperCamelCase : Optional[int] = torch.load(SCREAMING_SNAKE_CASE__ , map_location=torch.device("""cpu""" ) )['''state_dict'''] # rename keys __UpperCamelCase : Tuple = rename_keys(SCREAMING_SNAKE_CASE__ , encoder_only=SCREAMING_SNAKE_CASE__ ) 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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # create HuggingFace model and load state dict if encoder_only: __UpperCamelCase : str = False __UpperCamelCase : Any = SegformerForImageClassification(SCREAMING_SNAKE_CASE__ ) else: __UpperCamelCase : int = SegformerForSemanticSegmentation(SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.eval() # forward pass __UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase : Union[str, Any] = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": __UpperCamelCase : Union[str, Any] = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": __UpperCamelCase : Tuple = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": __UpperCamelCase : Optional[int] = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": __UpperCamelCase : Any = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": __UpperCamelCase : Dict = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": __UpperCamelCase : int = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": __UpperCamelCase : List[Any] = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": __UpperCamelCase : int = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": __UpperCamelCase : Optional[int] = torch.tensor( [ [ [-1.13_72e01, -1.27_87e01, -1.34_77e01], [-1.25_36e01, -1.41_94e01, -1.44_09e01], [-1.32_17e01, -1.48_88e01, -1.53_27e01], ], [ [-1.47_91e01, -1.71_22e01, -1.82_77e01], [-1.71_63e01, -1.91_92e01, -1.95_33e01], [-1.78_97e01, -1.99_91e01, -2.03_15e01], ], [ [7.67_23e-01, 4.19_21e-01, -7.78_78e-02], [4.77_72e-01, 9.55_57e-03, -2.80_82e-01], [3.60_32e-01, -2.48_26e-01, -5.11_68e-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": __UpperCamelCase : Optional[int] = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": __UpperCamelCase : str = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": __UpperCamelCase : int = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": __UpperCamelCase : int = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": __UpperCamelCase : Dict = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": __UpperCamelCase : Union[str, Any] = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: __UpperCamelCase : Dict = 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] , SCREAMING_SNAKE_CASE__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) image_processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": UpperCamelCase = 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.' ) UpperCamelCase = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
269
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): if isinstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ): return image elif isinstance(SCREAMING_SNAKE_CASE__ , PIL.Image.Image ): UpperCamelCase :Dict = [image] if isinstance(image[0] , PIL.Image.Image ): UpperCamelCase :Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) )[None, :] for i in image] UpperCamelCase :int = np.concatenate(SCREAMING_SNAKE_CASE__ , axis=0 ) UpperCamelCase :Optional[Any] = np.array(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) / 2_55.0 UpperCamelCase :List[str] = image.transpose(0 , 3 , 1 , 2 ) UpperCamelCase :Tuple = 2.0 * image - 1.0 UpperCamelCase :Any = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) elif isinstance(image[0] , torch.Tensor ): UpperCamelCase :str = torch.cat(SCREAMING_SNAKE_CASE__ , dim=0 ) return image def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=0.99_95 ): if not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): UpperCamelCase :int = True UpperCamelCase :Dict = va.device UpperCamelCase :List[Any] = va.cpu().numpy() UpperCamelCase :str = va.cpu().numpy() UpperCamelCase :Dict = np.sum(va * va / (np.linalg.norm(SCREAMING_SNAKE_CASE__ ) * np.linalg.norm(SCREAMING_SNAKE_CASE__ )) ) if np.abs(SCREAMING_SNAKE_CASE__ ) > DOT_THRESHOLD: UpperCamelCase :Any = (1 - t) * va + t * va else: UpperCamelCase :Union[str, Any] = np.arccos(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = theta_a * t UpperCamelCase :str = np.sin(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = np.sin(theta_a - theta_t ) / sin_theta_a UpperCamelCase :List[Any] = sin_theta_t / sin_theta_a UpperCamelCase :Union[str, Any] = sa * va + sa * va if inputs_are_torch: UpperCamelCase :Dict = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) return va def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) UpperCamelCase :int = F.normalize(SCREAMING_SNAKE_CASE__ , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any ): for param in model.parameters(): UpperCamelCase :Any = value class UpperCAmelCase_ ( lowercase ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , ) -> str: super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE_ , text_encoder=SCREAMING_SNAKE_CASE_ , clip_model=SCREAMING_SNAKE_CASE_ , tokenizer=SCREAMING_SNAKE_CASE_ , unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , feature_extractor=SCREAMING_SNAKE_CASE_ , coca_model=SCREAMING_SNAKE_CASE_ , coca_tokenizer=SCREAMING_SNAKE_CASE_ , coca_transform=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = ( feature_extractor.size if isinstance(feature_extractor.size , SCREAMING_SNAKE_CASE_ ) else feature_extractor.size['''shortest_edge'''] ) UpperCamelCase :Any = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , SCREAMING_SNAKE_CASE_ ) set_requires_grad(self.clip_model , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCamelCase :Tuple = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: self.enable_attention_slicing(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: set_requires_grad(self.vae , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: set_requires_grad(self.unet , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: # get the original timestep using init_timestep UpperCamelCase :Union[str, Any] = min(int(num_inference_steps * strength ) , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = max(num_inference_steps - init_timestep , 0 ) UpperCamelCase :Optional[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> int: if not isinstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ): raise ValueError(F'''`image` has to be of type `torch.Tensor` but is {type(SCREAMING_SNAKE_CASE_ )}''' ) UpperCamelCase :Tuple = image.to(device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(SCREAMING_SNAKE_CASE_ ) ] UpperCamelCase :List[str] = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) else: UpperCamelCase :Any = self.vae.encode(SCREAMING_SNAKE_CASE_ ).latent_dist.sample(SCREAMING_SNAKE_CASE_ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[str] = 0.1_8215 * init_latents UpperCamelCase :Optional[Any] = init_latents.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) UpperCamelCase :List[Any] = randn_tensor(init_latents.shape , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) # get latents UpperCamelCase :Optional[Any] = self.scheduler.add_noise(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = init_latents return latents def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :List[str] = self.coca_transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): UpperCamelCase :Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) UpperCamelCase :List[Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('''<end_of_text>''' )[0].replace('''<start_of_text>''' , '''''' ).rstrip(''' .,''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :str = self.feature_extractor.preprocess(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = torch.from_numpy(clip_image_input['''pixel_values'''][0] ).unsqueeze(0 ).to(self.device ).half() UpperCamelCase :int = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = image_embeddings_clip.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: UpperCamelCase :List[str] = latents.detach().requires_grad_() UpperCamelCase :List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[Any] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): UpperCamelCase :List[str] = self.scheduler.alphas_cumprod[timestep] UpperCamelCase :Optional[int] = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf UpperCamelCase :List[Any] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 UpperCamelCase :int = torch.sqrt(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = self.scheduler.sigmas[index] UpperCamelCase :Union[str, Any] = latents - sigma * noise_pred else: raise ValueError(F'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :int = 1 / 0.1_8215 * sample UpperCamelCase :List[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :List[str] = transforms.Resize(self.feature_extractor_size )(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = self.normalize(SCREAMING_SNAKE_CASE_ ).to(latents.dtype ) UpperCamelCase :List[Any] = self.clip_model.get_image_features(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = spherical_dist_loss(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).mean() * clip_guidance_scale UpperCamelCase :Union[str, Any] = -torch.autograd.grad(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )[0] if isinstance(self.scheduler , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = latents.detach() + grads * (sigma**2) UpperCamelCase :Optional[Any] = noise_pred_original else: UpperCamelCase :List[str] = noise_pred_original - torch.sqrt(SCREAMING_SNAKE_CASE_ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 512 , SCREAMING_SNAKE_CASE_ = 0.6 , SCREAMING_SNAKE_CASE_ = 50 , SCREAMING_SNAKE_CASE_ = 7.5 , SCREAMING_SNAKE_CASE_ = 1 , SCREAMING_SNAKE_CASE_ = 0.0 , SCREAMING_SNAKE_CASE_ = 100 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = "pil" , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 0.8 , SCREAMING_SNAKE_CASE_ = 0.1 , SCREAMING_SNAKE_CASE_ = 0.1 , ) -> Dict: if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) and len(SCREAMING_SNAKE_CASE_ ) != batch_size: raise ValueError(F'''You have passed {batch_size} batch_size, but only {len(SCREAMING_SNAKE_CASE_ )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(SCREAMING_SNAKE_CASE_ , torch.Generator ) and batch_size > 1: UpperCamelCase :Optional[int] = [generator] + [None] * (batch_size - 1) UpperCamelCase :Tuple = [ ('''model''', self.coca_model is None), ('''tokenizer''', self.coca_tokenizer is None), ('''transform''', self.coca_transform is None), ] UpperCamelCase :Union[str, Any] = [x[0] for x in coca_is_none if x[1]] UpperCamelCase :Dict = ''', '''.join(SCREAMING_SNAKE_CASE_ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' F'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :Any = self.get_image_description(SCREAMING_SNAKE_CASE_ ) if style_prompt is None: if len(SCREAMING_SNAKE_CASE_ ): raise ValueError( F'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' F''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) UpperCamelCase :str = self.get_image_description(SCREAMING_SNAKE_CASE_ ) # get prompt text embeddings for content and style UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :List[Any] = self.tokenizer( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , ) UpperCamelCase :Tuple = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] UpperCamelCase :Dict = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # duplicate text embeddings for each generation per prompt UpperCamelCase :Union[str, Any] = text_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # set timesteps UpperCamelCase :str = '''offset''' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) UpperCamelCase :List[str] = {} if accepts_offset: UpperCamelCase :Tuple = 1 self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) UpperCamelCase , UpperCamelCase :Tuple = self.get_timesteps(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.device ) UpperCamelCase :Any = timesteps[:1].repeat(SCREAMING_SNAKE_CASE_ ) # Preprocess image UpperCamelCase :Union[str, Any] = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = preprocess(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = self.prepare_latents( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , text_embeddings.dtype , self.device , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = slerp(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if clip_guidance_scale > 0: UpperCamelCase :Dict = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = self.get_clip_image_embeddings(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = slerp( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. UpperCamelCase :Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: UpperCamelCase :Any = content_text_input.input_ids.shape[-1] UpperCamelCase :Any = self.tokenizer([''''''] , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) UpperCamelCase :Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt UpperCamelCase :Optional[int] = uncond_embeddings.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes UpperCamelCase :str = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. UpperCamelCase :Any = (batch_size, self.unet.config.in_channels, height // 8, width // 8) UpperCamelCase :int = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps UpperCamelCase :List[str] = torch.randn(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device='''cpu''' , dtype=SCREAMING_SNAKE_CASE_ ).to( self.device ) else: UpperCamelCase :int = 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}''' ) UpperCamelCase :str = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler UpperCamelCase :Union[str, Any] = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] UpperCamelCase :Optional[int] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) UpperCamelCase :Dict = {} if accepts_eta: UpperCamelCase :int = eta # check if the scheduler accepts generator UpperCamelCase :Optional[int] = '''generator''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: UpperCamelCase :List[str] = generator with self.progress_bar(total=SCREAMING_SNAKE_CASE_ ): for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # expand the latents if we are doing classifier free guidance UpperCamelCase :Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCamelCase :List[Any] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # predict the noise residual UpperCamelCase :List[str] = self.unet(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ ).sample # perform classifier free guidance if do_classifier_free_guidance: UpperCamelCase , UpperCamelCase :Any = noise_pred.chunk(2 ) UpperCamelCase :Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: UpperCamelCase :int = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) UpperCamelCase , UpperCamelCase :str = self.cond_fn( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) # compute the previous noisy sample x_t -> x_t-1 UpperCamelCase :List[str] = self.scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor UpperCamelCase :List[Any] = 1 / 0.1_8215 * latents UpperCamelCase :Optional[Any] = self.vae.decode(SCREAMING_SNAKE_CASE_ ).sample UpperCamelCase :str = (image / 2 + 0.5).clamp(0 , 1 ) UpperCamelCase :Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCamelCase :List[str] = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE_ , nsfw_content_detected=SCREAMING_SNAKE_CASE_ )
658
0
def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Optional[Any]: if exponent == 1: return base if exponent % 2 == 0: _UpperCAmelCase = _modexpt(SCREAMING_SNAKE_CASE__ , exponent // 2 , SCREAMING_SNAKE_CASE__ ) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(SCREAMING_SNAKE_CASE__ , exponent - 1 , SCREAMING_SNAKE_CASE__ )) % modulo_value def _SCREAMING_SNAKE_CASE ( snake_case = 1_7_7_7 , snake_case = 1_8_5_5 , snake_case = 8 ) -> List[str]: _UpperCAmelCase = base for _ in range(1 , SCREAMING_SNAKE_CASE__ ): _UpperCAmelCase = _modexpt(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1_0**digits ) return result if __name__ == "__main__": print(F'{solution() = }')
518
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :list[list[int]] = [] UpperCamelCase :list[int] = [] UpperCamelCase :List[str] = 0 UpperCamelCase :Any = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : int , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) __snake_case = [3, 34, 4, 12, 5, 2] __snake_case = 9 __snake_case = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
658
0
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 UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :Union[str, Any] , a :Union[str, Any] , a :Dict ) -> Tuple: return [ int(1_000 * (box[0] / width) ), int(1_000 * (box[1] / height) ), int(1_000 * (box[2] / width) ), int(1_000 * (box[3] / height) ), ] def _a ( a :np.ndarray , a :Optional[str] , a :Optional[str] = None ) -> Optional[Any]: a = tesseract_config if tesseract_config is not None else '''''' # apply OCR a = to_pil_image(SCREAMING_SNAKE_CASE__ ) a = pil_image.size a = pytesseract.image_to_data(SCREAMING_SNAKE_CASE__ , lang=SCREAMING_SNAKE_CASE__ , output_type='''dict''' , config=SCREAMING_SNAKE_CASE__ ) a = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates a = [idx for idx, word in enumerate(SCREAMING_SNAKE_CASE__ ) if not word.strip()] a = [word for idx, word in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices] a = [coord for idx, coord in enumerate(SCREAMING_SNAKE_CASE__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format a = [] for x, y, w, h in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a = [x, y, x + w, y + h] actual_boxes.append(SCREAMING_SNAKE_CASE__ ) # finally, normalize the bounding boxes a = [] for box in actual_boxes: normalized_boxes.append(normalize_box(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['pixel_values'] def __init__( self : List[Any] , __UpperCAmelCase : int = True , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : int = PILImageResampling.BILINEAR , __UpperCAmelCase : Optional[Any] = True , __UpperCAmelCase : Any = None , __UpperCAmelCase : List[str] = "" , **__UpperCAmelCase : List[Any] , ) ->None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) a = size if size is not None else {'''height''': 224, '''width''': 224} a = get_size_dict(SCREAMING_SNAKE_CASE_ ) a = do_resize a = size a = resample a = apply_ocr a = ocr_lang a = tesseract_config def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] = PILImageResampling.BILINEAR , __UpperCAmelCase : List[str] = None , **__UpperCAmelCase : List[str] , ) ->np.ndarray: """simple docstring""" a = 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 = (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 __lowerCAmelCase ( self : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str = None , __UpperCAmelCase : Optional[Any] = None , __UpperCAmelCase : Any = None , __UpperCAmelCase : List[str] = None , __UpperCAmelCase : Tuple = None , __UpperCAmelCase : List[str] = None , __UpperCAmelCase : List[Any] = None , __UpperCAmelCase : Optional[int] = ChannelDimension.FIRST , **__UpperCAmelCase : Tuple , ) ->PIL.Image.Image: """simple docstring""" a = do_resize if do_resize is not None else self.do_resize a = size if size is not None else self.size a = get_size_dict(SCREAMING_SNAKE_CASE_ ) a = resample if resample is not None else self.resample a = apply_ocr if apply_ocr is not None else self.apply_ocr a = ocr_lang if ocr_lang is not None else self.ocr_lang a = tesseract_config if tesseract_config is not None else self.tesseract_config a = 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 = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) a = [] a = [] for image in images: a = 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 = [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 = [flip_channel_order(SCREAMING_SNAKE_CASE_ ) for image in images] a = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] a = BatchFeature(data={'''pixel_values''': images} , tensor_type=SCREAMING_SNAKE_CASE_ ) if apply_ocr: a = words_batch a = boxes_batch return data
117
def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''check_bouncy() accepts only integer arguments''' ) UpperCamelCase :int = str(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = ''''''.join(sorted(SCREAMING_SNAKE_CASE__ ) ) return sorted_str_n != str_n and sorted_str_n[::-1] != str_n def _A ( SCREAMING_SNAKE_CASE__ : float = 99 ): if not 0 < percent < 100: raise ValueError('''solution() only accepts values from 0 to 100''' ) UpperCamelCase :Tuple = 0 UpperCamelCase :str = 1 while True: if check_bouncy(SCREAMING_SNAKE_CASE__ ): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(99)}''')
658
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) __UpperCamelCase : Union[str, Any] = logging.getLogger() def A ( ): SCREAMING_SNAKE_CASE : Optional[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) SCREAMING_SNAKE_CASE : Any = parser.parse_args() return args.f def A ( _lowercase ): SCREAMING_SNAKE_CASE : Optional[Any] = {} SCREAMING_SNAKE_CASE : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , '''all_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: SCREAMING_SNAKE_CASE : List[str] = json.load(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f"""can\'t find {path}""" ) return results def A ( ): SCREAMING_SNAKE_CASE : int = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() __UpperCamelCase : Optional[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase__ ( UpperCamelCase_): @classmethod def __A ( cls : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : List[str] = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) SCREAMING_SNAKE_CASE : Any = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __A ( cls : Dict ): '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Optional[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = 7 if get_gpu_count() > 1 else 2 SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : List[str] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : str = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : List[str] = get_results(SCREAMING_SNAKE_CASE_ ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['''eval_f1'''] , 28 ) self.assertGreaterEqual(result['''eval_exact'''] , 28 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : int = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Optional[int] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Tuple = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_rouge1'''] , 10 ) self.assertGreaterEqual(result['''eval_rouge2'''] , 2 ) self.assertGreaterEqual(result['''eval_rougeL'''] , 7 ) self.assertGreaterEqual(result['''eval_rougeLsum'''] , 7 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Optional[Any] = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Optional[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''translation_no_trainer''' ) ) ) @slow def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = logging.StreamHandler(sys.stdout ) logger.addHandler(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Union[str, Any] = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : List[Any] = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Tuple = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append('''--fp16''' ) run_command(self._launch_args + testargs ) SCREAMING_SNAKE_CASE : Optional[Any] = get_results(SCREAMING_SNAKE_CASE_ ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''image_classification_no_trainer''' ) ) )
248
def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Union[str, Any] = hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) UpperCamelCase :str = hex_num[0] == '''-''' if is_negative: UpperCamelCase :Union[str, Any] = hex_num[1:] try: UpperCamelCase :Optional[Any] = int(SCREAMING_SNAKE_CASE__ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) UpperCamelCase :Dict = '''''' while int_num > 0: UpperCamelCase :Tuple = str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
from math import sqrt def __UpperCamelCase ( lowerCAmelCase__ : int ): 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(sqrt(SCREAMING_SNAKE_CASE__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __UpperCamelCase ( lowerCAmelCase__ : int = 1_0_0_0_1 ): __a : List[str] = 0 __a : int = 1 while count != nth and number < 3: number += 1 if is_prime(SCREAMING_SNAKE_CASE__ ): count += 1 while count != nth: number += 2 if is_prime(SCREAMING_SNAKE_CASE__ ): count += 1 return number if __name__ == "__main__": print(F"""{solution() = }""")
521
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase , UpperCamelCase :List[Any] = position UpperCamelCase :Any = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] UpperCamelCase :Dict = [] for position in positions: UpperCamelCase , UpperCamelCase :str = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(SCREAMING_SNAKE_CASE__ ) return permissible_positions def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): return not any(elem == 0 for row in board for elem in row ) def _A ( SCREAMING_SNAKE_CASE__ : list[list[int]] , SCREAMING_SNAKE_CASE__ : tuple[int, int] , SCREAMING_SNAKE_CASE__ : int ): if is_complete(SCREAMING_SNAKE_CASE__ ): return True for position in get_valid_pos(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): UpperCamelCase , UpperCamelCase :Optional[int] = position if board[y][x] == 0: UpperCamelCase :Any = curr + 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , curr + 1 ): return True UpperCamelCase :Union[str, Any] = 0 return False def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[Any] = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Tuple = 1 if open_knight_tour_helper(SCREAMING_SNAKE_CASE__ , (i, j) , 1 ): return board UpperCamelCase :str = 0 UpperCamelCase :List[Any] = F'''Open Kight Tour cannot be performed on a board of size {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod()
658
0
"""simple docstring""" import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { """kakaobrain/align-base""": """https://huggingface.co/kakaobrain/align-base/resolve/main/config.json""", } class lowercase ( lowercase__ ): lowercase = 'align_text_model' def __init__(self : str ,SCREAMING_SNAKE_CASE_ : List[Any]=30_522 ,SCREAMING_SNAKE_CASE_ : Any=768 ,SCREAMING_SNAKE_CASE_ : Optional[int]=12 ,SCREAMING_SNAKE_CASE_ : List[str]=12 ,SCREAMING_SNAKE_CASE_ : Tuple=3_072 ,SCREAMING_SNAKE_CASE_ : Tuple="gelu" ,SCREAMING_SNAKE_CASE_ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE_ : Tuple=0.1 ,SCREAMING_SNAKE_CASE_ : int=512 ,SCREAMING_SNAKE_CASE_ : Tuple=2 ,SCREAMING_SNAKE_CASE_ : Optional[Any]=0.02 ,SCREAMING_SNAKE_CASE_ : int=1e-12 ,SCREAMING_SNAKE_CASE_ : int=0 ,SCREAMING_SNAKE_CASE_ : List[str]="absolute" ,SCREAMING_SNAKE_CASE_ : str=True ,**SCREAMING_SNAKE_CASE_ : Optional[Any] ,) -> int: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = vocab_size lowerCAmelCase = hidden_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = hidden_act lowerCAmelCase = intermediate_size lowerCAmelCase = hidden_dropout_prob lowerCAmelCase = attention_probs_dropout_prob lowerCAmelCase = max_position_embeddings lowerCAmelCase = type_vocab_size lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps lowerCAmelCase = position_embedding_type lowerCAmelCase = use_cache lowerCAmelCase = pad_token_id @classmethod def UpperCAmelCase (cls : Dict ,SCREAMING_SNAKE_CASE_ : List[str] ,**SCREAMING_SNAKE_CASE_ : List[Any] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = cls.get_config_dict(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) # get the text config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": lowerCAmelCase = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls ,'''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) class lowercase ( lowercase__ ): lowercase = 'align_vision_model' def __init__(self : List[str] ,SCREAMING_SNAKE_CASE_ : Optional[int] = 3 ,SCREAMING_SNAKE_CASE_ : List[str] = 600 ,SCREAMING_SNAKE_CASE_ : Optional[Any] = 2.0 ,SCREAMING_SNAKE_CASE_ : Optional[Any] = 3.1 ,SCREAMING_SNAKE_CASE_ : List[str] = 8 ,SCREAMING_SNAKE_CASE_ : Optional[int] = [3, 3, 5, 3, 5, 5, 3] ,SCREAMING_SNAKE_CASE_ : List[Any] = [32, 16, 24, 40, 80, 112, 192] ,SCREAMING_SNAKE_CASE_ : Union[str, Any] = [16, 24, 40, 80, 112, 192, 320] ,SCREAMING_SNAKE_CASE_ : List[Any] = [] ,SCREAMING_SNAKE_CASE_ : Any = [1, 2, 2, 2, 1, 2, 1] ,SCREAMING_SNAKE_CASE_ : List[Any] = [1, 2, 2, 3, 3, 4, 1] ,SCREAMING_SNAKE_CASE_ : Optional[Any] = [1, 6, 6, 6, 6, 6, 6] ,SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.25 ,SCREAMING_SNAKE_CASE_ : str = "swish" ,SCREAMING_SNAKE_CASE_ : Optional[int] = 2_560 ,SCREAMING_SNAKE_CASE_ : Dict = "mean" ,SCREAMING_SNAKE_CASE_ : List[Any] = 0.02 ,SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.0_01 ,SCREAMING_SNAKE_CASE_ : str = 0.99 ,SCREAMING_SNAKE_CASE_ : Optional[Any] = 0.2 ,**SCREAMING_SNAKE_CASE_ : int ,) -> Union[str, Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = num_channels lowerCAmelCase = image_size lowerCAmelCase = width_coefficient lowerCAmelCase = depth_coefficient lowerCAmelCase = depth_divisor lowerCAmelCase = kernel_sizes lowerCAmelCase = in_channels lowerCAmelCase = out_channels lowerCAmelCase = depthwise_padding lowerCAmelCase = strides lowerCAmelCase = num_block_repeats lowerCAmelCase = expand_ratios lowerCAmelCase = squeeze_expansion_ratio lowerCAmelCase = hidden_act lowerCAmelCase = hidden_dim lowerCAmelCase = pooling_type lowerCAmelCase = initializer_range lowerCAmelCase = batch_norm_eps lowerCAmelCase = batch_norm_momentum lowerCAmelCase = drop_connect_rate lowerCAmelCase = sum(SCREAMING_SNAKE_CASE_ ) * 4 @classmethod def UpperCAmelCase (cls : str ,SCREAMING_SNAKE_CASE_ : List[Any] ,**SCREAMING_SNAKE_CASE_ : Dict ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = cls.get_config_dict(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('''model_type''' ) == "align": lowerCAmelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls ,'''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) class lowercase ( lowercase__ ): lowercase = 'align' lowercase = True def __init__(self : int ,SCREAMING_SNAKE_CASE_ : Tuple=None ,SCREAMING_SNAKE_CASE_ : Optional[Any]=None ,SCREAMING_SNAKE_CASE_ : Dict=640 ,SCREAMING_SNAKE_CASE_ : List[str]=1.0 ,SCREAMING_SNAKE_CASE_ : int=0.02 ,**SCREAMING_SNAKE_CASE_ : List[str] ,) -> List[Any]: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE_ ) if text_config is None: lowerCAmelCase = {} logger.info('''text_config is None. Initializing the AlignTextConfig with default values.''' ) if vision_config is None: lowerCAmelCase = {} logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.''' ) lowerCAmelCase = AlignTextConfig(**SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = AlignVisionConfig(**SCREAMING_SNAKE_CASE_ ) lowerCAmelCase = projection_dim lowerCAmelCase = temperature_init_value lowerCAmelCase = initializer_range @classmethod def UpperCAmelCase (cls : int ,SCREAMING_SNAKE_CASE_ : str ,SCREAMING_SNAKE_CASE_ : List[str] ,**SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return cls(text_config=text_config.to_dict() ,vision_config=vision_config.to_dict() ,**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase (self : List[Any] ) -> Optional[int]: """simple docstring""" lowerCAmelCase = copy.deepcopy(self.__dict__ ) lowerCAmelCase = self.text_config.to_dict() lowerCAmelCase = self.vision_config.to_dict() lowerCAmelCase = self.__class__.model_type return output
535
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('''foo.json''',)] ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :int = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , config_name=SCREAMING_SNAKE_CASE_ ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = AutoConfig.from_pretrained('''gpt2''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = GenerationConfig() UpperCamelCase :List[str] = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } UpperCamelCase :Dict = copy.deepcopy(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = generation_config.update(**SCREAMING_SNAKE_CASE_ ) # update_kwargs was not modified (no side effects) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''foo''': '''bar'''} ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = GenerationConfig() UpperCamelCase :Tuple = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) UpperCamelCase :Union[str, Any] = GenerationConfig.from_model_config(SCREAMING_SNAKE_CASE_ ) assert not hasattr(SCREAMING_SNAKE_CASE_ , '''foo''' ) # no new kwargs should be initialized if from config def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Dict = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(default_config.num_beams , 1 ) UpperCamelCase :Tuple = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained(SCREAMING_SNAKE_CASE_ , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , SCREAMING_SNAKE_CASE_ ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @classmethod def UpperCAmelCase ( cls ) -> Optional[Any]: UpperCamelCase :List[str] = TOKEN HfFolder.save_token(SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase ( cls ) -> Union[str, Any]: try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) UpperCamelCase :List[Any] = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''test-generation-config''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained(F'''{USER}/test-generation-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = GenerationConfig( do_sample=SCREAMING_SNAKE_CASE_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) UpperCamelCase :Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( SCREAMING_SNAKE_CASE_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=SCREAMING_SNAKE_CASE_ , use_auth_token=self._token ) UpperCamelCase :Tuple = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(SCREAMING_SNAKE_CASE_ , getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) )
658
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: Dict =logging.get_logger(__name__) lowerCAmelCase: Optional[Any] ={ "google/vivit-b-16x2-kinetics400": ( "https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json" ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class lowerCamelCase__ ( __UpperCamelCase ): __UpperCAmelCase = 'vivit' def __init__( self , snake_case=2_2_4 , snake_case=3_2 , snake_case=[2, 1_6, 1_6] , snake_case=3 , snake_case=7_6_8 , snake_case=1_2 , snake_case=1_2 , snake_case=3_0_7_2 , snake_case="gelu_fast" , snake_case=0.0 , snake_case=0.0 , snake_case=0.02 , snake_case=1E-06 , snake_case=True , **snake_case , ) -> Optional[Any]: """simple docstring""" lowercase : List[str] = hidden_size lowercase : int = num_hidden_layers lowercase : List[Any] = num_attention_heads lowercase : Optional[Any] = intermediate_size lowercase : List[Any] = hidden_act lowercase : Any = hidden_dropout_prob lowercase : Tuple = attention_probs_dropout_prob lowercase : Dict = initializer_range lowercase : Tuple = layer_norm_eps lowercase : str = image_size lowercase : str = num_frames lowercase : List[str] = tubelet_size lowercase : List[str] = num_channels lowercase : int = qkv_bias super().__init__(**SCREAMING_SNAKE_CASE_ )
607
def _A ( SCREAMING_SNAKE_CASE__ : int ): if length <= 0 or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('''Length must be a positive integer.''' ) return [n * (2 * n - 1) for n in range(SCREAMING_SNAKE_CASE__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
658
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase : List[str] = logging.get_logger(__name__) UpperCamelCase : Union[str, Any] = { """weiweishi/roc-bert-base-zh""": """https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json""", } class A__ ( A__ ): """simple docstring""" _lowercase = 'roc_bert' def __init__( self : Union[str, Any] , lowerCamelCase__ : Union[str, Any]=30_522 , lowerCamelCase__ : Any=768 , lowerCamelCase__ : int=12 , lowerCamelCase__ : List[Any]=12 , lowerCamelCase__ : str=3_072 , lowerCamelCase__ : List[str]="gelu" , lowerCamelCase__ : Any=0.1 , lowerCamelCase__ : str=0.1 , lowerCamelCase__ : Dict=512 , lowerCamelCase__ : Optional[int]=2 , lowerCamelCase__ : Tuple=0.02 , lowerCamelCase__ : Any=1E-12 , lowerCamelCase__ : Union[str, Any]=True , lowerCamelCase__ : List[Any]=0 , lowerCamelCase__ : Dict="absolute" , lowerCamelCase__ : Dict=None , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Dict=768 , lowerCamelCase__ : Optional[Any]=910 , lowerCamelCase__ : Any=512 , lowerCamelCase__ : List[Any]=24_858 , lowerCamelCase__ : Dict=True , **lowerCamelCase__ : Optional[Any] , ): a__ : int = vocab_size a__ : Optional[int] = max_position_embeddings a__ : Dict = hidden_size a__ : Optional[int] = num_hidden_layers a__ : Any = num_attention_heads a__ : Optional[int] = intermediate_size a__ : Union[str, Any] = hidden_act a__ : Tuple = hidden_dropout_prob a__ : List[Any] = attention_probs_dropout_prob a__ : Tuple = initializer_range a__ : List[Any] = type_vocab_size a__ : List[str] = layer_norm_eps a__ : str = use_cache a__ : Union[str, Any] = enable_pronunciation a__ : Union[str, Any] = enable_shape a__ : List[str] = pronunciation_embed_dim a__ : int = pronunciation_vocab_size a__ : Dict = shape_embed_dim a__ : List[str] = shape_vocab_size a__ : Tuple = concat_input a__ : List[Any] = position_embedding_type a__ : List[str] = classifier_dropout super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )
37
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __snake_case = { """Acehnese Arabic""": """ace_Arab""", """Acehnese Latin""": """ace_Latn""", """Mesopotamian Arabic""": """acm_Arab""", """Ta'izzi-Adeni Arabic""": """acq_Arab""", """Tunisian Arabic""": """aeb_Arab""", """Afrikaans""": """afr_Latn""", """South Levantine Arabic""": """ajp_Arab""", """Akan""": """aka_Latn""", """Amharic""": """amh_Ethi""", """North Levantine Arabic""": """apc_Arab""", """Modern Standard Arabic""": """arb_Arab""", """Modern Standard Arabic Romanized""": """arb_Latn""", """Najdi Arabic""": """ars_Arab""", """Moroccan Arabic""": """ary_Arab""", """Egyptian Arabic""": """arz_Arab""", """Assamese""": """asm_Beng""", """Asturian""": """ast_Latn""", """Awadhi""": """awa_Deva""", """Central Aymara""": """ayr_Latn""", """South Azerbaijani""": """azb_Arab""", """North Azerbaijani""": """azj_Latn""", """Bashkir""": """bak_Cyrl""", """Bambara""": """bam_Latn""", """Balinese""": """ban_Latn""", """Belarusian""": """bel_Cyrl""", """Bemba""": """bem_Latn""", """Bengali""": """ben_Beng""", """Bhojpuri""": """bho_Deva""", """Banjar Arabic""": """bjn_Arab""", """Banjar Latin""": """bjn_Latn""", """Standard Tibetan""": """bod_Tibt""", """Bosnian""": """bos_Latn""", """Buginese""": """bug_Latn""", """Bulgarian""": """bul_Cyrl""", """Catalan""": """cat_Latn""", """Cebuano""": """ceb_Latn""", """Czech""": """ces_Latn""", """Chokwe""": """cjk_Latn""", """Central Kurdish""": """ckb_Arab""", """Crimean Tatar""": """crh_Latn""", """Welsh""": """cym_Latn""", """Danish""": """dan_Latn""", """German""": """deu_Latn""", """Southwestern Dinka""": """dik_Latn""", """Dyula""": """dyu_Latn""", """Dzongkha""": """dzo_Tibt""", """Greek""": """ell_Grek""", """English""": """eng_Latn""", """Esperanto""": """epo_Latn""", """Estonian""": """est_Latn""", """Basque""": """eus_Latn""", """Ewe""": """ewe_Latn""", """Faroese""": """fao_Latn""", """Fijian""": """fij_Latn""", """Finnish""": """fin_Latn""", """Fon""": """fon_Latn""", """French""": """fra_Latn""", """Friulian""": """fur_Latn""", """Nigerian Fulfulde""": """fuv_Latn""", """Scottish Gaelic""": """gla_Latn""", """Irish""": """gle_Latn""", """Galician""": """glg_Latn""", """Guarani""": """grn_Latn""", """Gujarati""": """guj_Gujr""", """Haitian Creole""": """hat_Latn""", """Hausa""": """hau_Latn""", """Hebrew""": """heb_Hebr""", """Hindi""": """hin_Deva""", """Chhattisgarhi""": """hne_Deva""", """Croatian""": """hrv_Latn""", """Hungarian""": """hun_Latn""", """Armenian""": """hye_Armn""", """Igbo""": """ibo_Latn""", """Ilocano""": """ilo_Latn""", """Indonesian""": """ind_Latn""", """Icelandic""": """isl_Latn""", """Italian""": """ita_Latn""", """Javanese""": """jav_Latn""", """Japanese""": """jpn_Jpan""", """Kabyle""": """kab_Latn""", """Jingpho""": """kac_Latn""", """Kamba""": """kam_Latn""", """Kannada""": """kan_Knda""", """Kashmiri Arabic""": """kas_Arab""", """Kashmiri Devanagari""": """kas_Deva""", """Georgian""": """kat_Geor""", """Central Kanuri Arabic""": """knc_Arab""", """Central Kanuri Latin""": """knc_Latn""", """Kazakh""": """kaz_Cyrl""", """Kabiyè""": """kbp_Latn""", """Kabuverdianu""": """kea_Latn""", """Khmer""": """khm_Khmr""", """Kikuyu""": """kik_Latn""", """Kinyarwanda""": """kin_Latn""", """Kyrgyz""": """kir_Cyrl""", """Kimbundu""": """kmb_Latn""", """Northern Kurdish""": """kmr_Latn""", """Kikongo""": """kon_Latn""", """Korean""": """kor_Hang""", """Lao""": """lao_Laoo""", """Ligurian""": """lij_Latn""", """Limburgish""": """lim_Latn""", """Lingala""": """lin_Latn""", """Lithuanian""": """lit_Latn""", """Lombard""": """lmo_Latn""", """Latgalian""": """ltg_Latn""", """Luxembourgish""": """ltz_Latn""", """Luba-Kasai""": """lua_Latn""", """Ganda""": """lug_Latn""", """Luo""": """luo_Latn""", """Mizo""": """lus_Latn""", """Standard Latvian""": """lvs_Latn""", """Magahi""": """mag_Deva""", """Maithili""": """mai_Deva""", """Malayalam""": """mal_Mlym""", """Marathi""": """mar_Deva""", """Minangkabau Arabic """: """min_Arab""", """Minangkabau Latin""": """min_Latn""", """Macedonian""": """mkd_Cyrl""", """Plateau Malagasy""": """plt_Latn""", """Maltese""": """mlt_Latn""", """Meitei Bengali""": """mni_Beng""", """Halh Mongolian""": """khk_Cyrl""", """Mossi""": """mos_Latn""", """Maori""": """mri_Latn""", """Burmese""": """mya_Mymr""", """Dutch""": """nld_Latn""", """Norwegian Nynorsk""": """nno_Latn""", """Norwegian Bokmål""": """nob_Latn""", """Nepali""": """npi_Deva""", """Northern Sotho""": """nso_Latn""", """Nuer""": """nus_Latn""", """Nyanja""": """nya_Latn""", """Occitan""": """oci_Latn""", """West Central Oromo""": """gaz_Latn""", """Odia""": """ory_Orya""", """Pangasinan""": """pag_Latn""", """Eastern Panjabi""": """pan_Guru""", """Papiamento""": """pap_Latn""", """Western Persian""": """pes_Arab""", """Polish""": """pol_Latn""", """Portuguese""": """por_Latn""", """Dari""": """prs_Arab""", """Southern Pashto""": """pbt_Arab""", """Ayacucho Quechua""": """quy_Latn""", """Romanian""": """ron_Latn""", """Rundi""": """run_Latn""", """Russian""": """rus_Cyrl""", """Sango""": """sag_Latn""", """Sanskrit""": """san_Deva""", """Santali""": """sat_Olck""", """Sicilian""": """scn_Latn""", """Shan""": """shn_Mymr""", """Sinhala""": """sin_Sinh""", """Slovak""": """slk_Latn""", """Slovenian""": """slv_Latn""", """Samoan""": """smo_Latn""", """Shona""": """sna_Latn""", """Sindhi""": """snd_Arab""", """Somali""": """som_Latn""", """Southern Sotho""": """sot_Latn""", """Spanish""": """spa_Latn""", """Tosk Albanian""": """als_Latn""", """Sardinian""": """srd_Latn""", """Serbian""": """srp_Cyrl""", """Swati""": """ssw_Latn""", """Sundanese""": """sun_Latn""", """Swedish""": """swe_Latn""", """Swahili""": """swh_Latn""", """Silesian""": """szl_Latn""", """Tamil""": """tam_Taml""", """Tatar""": """tat_Cyrl""", """Telugu""": """tel_Telu""", """Tajik""": """tgk_Cyrl""", """Tagalog""": """tgl_Latn""", """Thai""": """tha_Thai""", """Tigrinya""": """tir_Ethi""", """Tamasheq Latin""": """taq_Latn""", """Tamasheq Tifinagh""": """taq_Tfng""", """Tok Pisin""": """tpi_Latn""", """Tswana""": """tsn_Latn""", """Tsonga""": """tso_Latn""", """Turkmen""": """tuk_Latn""", """Tumbuka""": """tum_Latn""", """Turkish""": """tur_Latn""", """Twi""": """twi_Latn""", """Central Atlas Tamazight""": """tzm_Tfng""", """Uyghur""": """uig_Arab""", """Ukrainian""": """ukr_Cyrl""", """Umbundu""": """umb_Latn""", """Urdu""": """urd_Arab""", """Northern Uzbek""": """uzn_Latn""", """Venetian""": """vec_Latn""", """Vietnamese""": """vie_Latn""", """Waray""": """war_Latn""", """Wolof""": """wol_Latn""", """Xhosa""": """xho_Latn""", """Eastern Yiddish""": """ydd_Hebr""", """Yoruba""": """yor_Latn""", """Yue Chinese""": """yue_Hant""", """Chinese Simplified""": """zho_Hans""", """Chinese Traditional""": """zho_Hant""", """Standard Malay""": """zsm_Latn""", """Zulu""": """zul_Latn""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='facebook/nllb-200-distilled-600M' UpperCamelCase_ : Optional[Any] =( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) UpperCamelCase_ : Dict ='translator' UpperCamelCase_ : Any =AutoTokenizer UpperCamelCase_ : Optional[Any] =AutoModelForSeqaSeqLM UpperCamelCase_ : List[Any] =LANGUAGE_CODES UpperCamelCase_ : int =['text', 'text', 'text'] UpperCamelCase_ : Union[str, Any] =['text'] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: if src_lang not in self.lang_to_code: raise ValueError(F'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'''{tgt_lang} is not a supported language.''' ) UpperCamelCase :Optional[int] = self.lang_to_code[src_lang] UpperCamelCase :Union[str, Any] = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' , src_lang=SCREAMING_SNAKE_CASE_ , tgt_lang=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE_ )
658
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a__ = logging.get_logger(__name__) a__ = { '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''', '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''', } class SCREAMING_SNAKE_CASE_ ( _UpperCamelCase ): """simple docstring""" __magic_name__ : Dict = 'luke' def __init__( self : Optional[Any] , lowerCAmelCase : int=50267 , lowerCAmelCase : Union[str, Any]=500000 , lowerCAmelCase : Optional[Any]=768 , lowerCAmelCase : Optional[Any]=256 , lowerCAmelCase : str=12 , lowerCAmelCase : Dict=12 , lowerCAmelCase : str=3072 , lowerCAmelCase : Optional[int]="gelu" , lowerCAmelCase : int=0.1 , lowerCAmelCase : Any=0.1 , lowerCAmelCase : Tuple=512 , lowerCAmelCase : Optional[int]=2 , lowerCAmelCase : str=0.02 , lowerCAmelCase : Dict=1E-12 , lowerCAmelCase : str=True , lowerCAmelCase : Dict=None , lowerCAmelCase : Union[str, Any]=1 , lowerCAmelCase : Any=0 , lowerCAmelCase : Tuple=2 , **lowerCAmelCase : Optional[int] , ) -> Dict: """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_ ) __UpperCamelCase : Optional[Any] = vocab_size __UpperCamelCase : Union[str, Any] = entity_vocab_size __UpperCamelCase : Union[str, Any] = hidden_size __UpperCamelCase : List[str] = entity_emb_size __UpperCamelCase : Dict = num_hidden_layers __UpperCamelCase : List[str] = num_attention_heads __UpperCamelCase : Optional[Any] = hidden_act __UpperCamelCase : str = intermediate_size __UpperCamelCase : Tuple = hidden_dropout_prob __UpperCamelCase : List[str] = attention_probs_dropout_prob __UpperCamelCase : Union[str, Any] = max_position_embeddings __UpperCamelCase : List[str] = type_vocab_size __UpperCamelCase : List[str] = initializer_range __UpperCamelCase : Optional[Any] = layer_norm_eps __UpperCamelCase : int = use_entity_aware_attention __UpperCamelCase : Union[str, Any] = classifier_dropout
279
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. __snake_case = 10 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if array[i] == target: return i return -1 def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Tuple = 0 UpperCamelCase :Dict = len(SCREAMING_SNAKE_CASE__ ) while left <= right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = (left + right) // 3 + 1 UpperCamelCase :str = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: UpperCamelCase :int = one_third - 1 elif array[two_third] < target: UpperCamelCase :Any = two_third + 1 else: UpperCamelCase :Any = one_third + 1 UpperCamelCase :int = two_third - 1 else: return -1 def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : int ): if left < right: if right - left < precision: return lin_search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = (left + right) // 3 + 1 UpperCamelCase :Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(SCREAMING_SNAKE_CASE__ , one_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() __snake_case = input("""Enter numbers separated by comma:\n""").strip() __snake_case = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." __snake_case = int(input("""Enter the number to be found in the list:\n""").strip()) __snake_case = ite_ternary_search(collection, target) __snake_case = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
658
0
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def __lowercase( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = 10**-10 ): """simple docstring""" lowerCamelCase = a while True: lowerCamelCase = Decimal(SCREAMING_SNAKE_CASE__ ) - ( Decimal(eval(SCREAMING_SNAKE_CASE__ ) ) / Decimal(eval(str(diff(SCREAMING_SNAKE_CASE__ ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(SCREAMING_SNAKE_CASE__ ) ) < precision: # noqa: S307 return float(SCREAMING_SNAKE_CASE__ ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"""The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}""") # Find root of polynomial print(f"""The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}""") # Find Square Root of 5 print(f"""The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}""") # Exponential Roots print(f"""The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}""")
623
def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if n == 0: return 0 UpperCamelCase :Union[str, Any] = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :str = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + naive_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ ) ) return max_revue def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list , SCREAMING_SNAKE_CASE__ : list ): if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: UpperCamelCase :Dict = float('''-inf''' ) for i in range(1 , n + 1 ): UpperCamelCase :Union[str, Any] = max( SCREAMING_SNAKE_CASE__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , ) UpperCamelCase :str = max_revenue return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): _enforce_args(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. UpperCamelCase :List[str] = [float('''-inf''' ) for _ in range(n + 1 )] UpperCamelCase :Dict = 0 for i in range(1 , n + 1 ): UpperCamelCase :Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): UpperCamelCase :Optional[Any] = max(SCREAMING_SNAKE_CASE__ , prices[j - 1] + max_rev[i - j] ) UpperCamelCase :Tuple = max_revenue_i return max_rev[n] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list ): if n < 0: UpperCamelCase :Any = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(SCREAMING_SNAKE_CASE__ ) if n > len(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Union[str, Any] = ( '''Each integral piece of rod must have a corresponding price. ''' F'''Got n = {n} but length of prices = {len(SCREAMING_SNAKE_CASE__ )}''' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = [6, 10, 12, 15, 20, 23] UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. UpperCamelCase :str = 36 UpperCamelCase :int = top_down_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = bottom_up_cut_rod(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = naive_cut_rod_recursive(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
658
0
'''simple docstring''' 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 : str = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCamelCase : Optional[Any] = """ 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 ( SCREAMING_SNAKE_CASE__: str, SCREAMING_SNAKE_CASE__: Dict, SCREAMING_SNAKE_CASE__: Union[str, Any]=8 ) -> Optional[Any]: """simple docstring""" __a = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __a = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , ) ->str: '''simple docstring''' super().__init__() self.register_modules( unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ , movq=SCREAMING_SNAKE_CASE_ , ) __a = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __UpperCamelCase ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) ->Optional[Any]: '''simple docstring''' if latents is None: __a = randn_tensor(SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ , dtype=SCREAMING_SNAKE_CASE_ ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) __a = latents.to(SCREAMING_SNAKE_CASE_ ) __a = latents * scheduler.init_noise_sigma return latents def __UpperCamelCase ( self , lowerCamelCase=0 ) ->Union[str, Any]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __a = torch.device(F"""cuda:{gpu_id}""" ) __a = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def __UpperCamelCase ( self , lowerCamelCase=0 ) ->Optional[int]: '''simple docstring''' 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.' ) __a = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=SCREAMING_SNAKE_CASE_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __a = None for cpu_offloaded_model in [self.unet, self.movq]: __a = cpu_offload_with_hook(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , prev_module_hook=SCREAMING_SNAKE_CASE_ ) # We'll offload the last model manually. __a = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __UpperCamelCase ( self ) ->Dict: '''simple docstring''' if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(SCREAMING_SNAKE_CASE_ , '_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(SCREAMING_SNAKE_CASE_ ) def __call__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 100 , lowerCamelCase = 4.0 , lowerCamelCase = 1 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , ) ->Dict: '''simple docstring''' __a = self._execution_device __a = guidance_scale > 1.0 if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __a = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __a = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __a = torch.cat(SCREAMING_SNAKE_CASE_ , dim=0 ) __a = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: __a = image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) __a = negative_image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) __a = hint.repeat_interleave(SCREAMING_SNAKE_CASE_ , dim=0 ) __a = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=SCREAMING_SNAKE_CASE_ ) __a = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=SCREAMING_SNAKE_CASE_ ) self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ , device=SCREAMING_SNAKE_CASE_ ) __a = self.scheduler.timesteps __a = self.movq.config.latent_channels __a = downscale_height_and_width(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.movq_scale_factor ) # create initial latent __a = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE_ ) ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = {'''image_embeds''': image_embeds, '''hint''': hint} __a = self.unet( sample=SCREAMING_SNAKE_CASE_ , timestep=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , added_cond_kwargs=SCREAMING_SNAKE_CASE_ , return_dict=SCREAMING_SNAKE_CASE_ , )[0] if do_classifier_free_guidance: __a = noise_pred.split(latents.shape[1] , dim=1 ) __a = noise_pred.chunk(2 ) __a = variance_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __a = 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"] ): __a = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ , )[0] # post-processing __a = self.movq.decode(SCREAMING_SNAKE_CASE_ , force_not_quantize=SCREAMING_SNAKE_CASE_ )['''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"]: __a = image * 0.5 + 0.5 __a = image.clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __a = self.numpy_to_pil(SCREAMING_SNAKE_CASE_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=SCREAMING_SNAKE_CASE_ )
448
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase, lowercase ): """simple docstring""" UpperCamelCase_ : int ='focalnet' def __init__( self , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=96 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=[192, 384, 768, 768] , SCREAMING_SNAKE_CASE_=[2, 2, 6, 2] , SCREAMING_SNAKE_CASE_=[2, 2, 2, 2] , SCREAMING_SNAKE_CASE_=[3, 3, 3, 3] , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=4.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1e-4 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = image_size UpperCamelCase :Dict = patch_size UpperCamelCase :Tuple = num_channels UpperCamelCase :int = embed_dim UpperCamelCase :Optional[Any] = use_conv_embed UpperCamelCase :str = hidden_sizes UpperCamelCase :str = depths UpperCamelCase :Optional[int] = focal_levels UpperCamelCase :Tuple = focal_windows UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Optional[int] = mlp_ratio UpperCamelCase :Optional[Any] = hidden_dropout_prob UpperCamelCase :int = drop_path_rate UpperCamelCase :Dict = use_layerscale UpperCamelCase :List[str] = layerscale_value UpperCamelCase :Tuple = use_post_layernorm UpperCamelCase :int = use_post_layernorm_in_modulation UpperCamelCase :str = normalize_modulator UpperCamelCase :Any = initializer_range UpperCamelCase :Optional[Any] = layer_norm_eps UpperCamelCase :Dict = encoder_stride UpperCamelCase :int = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] UpperCamelCase , UpperCamelCase :int = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_ , out_indices=SCREAMING_SNAKE_CASE_ , stage_names=self.stage_names )
658
0
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def __lowerCamelCase ( __lowerCAmelCase : Any ) -> int: __UpperCamelCase : Tuple = os.path.join(args.tf_model_dir , """parameters.json""" ) __UpperCamelCase : List[Any] = json.loads(open(SCREAMING_SNAKE_CASE__ ).read() ) if not params: raise ValueError( f'It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.' ) if not args.output.endswith(""".pt""" ): __UpperCamelCase : Dict = args.output + '''.pt''' __UpperCamelCase : Optional[Any] = OrderedDict() with tf.device("""/CPU:0""" ): __UpperCamelCase : Optional[int] = tf.train.load_checkpoint(args.tf_model_dir ) __UpperCamelCase : List[str] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): __UpperCamelCase : List[str] = reader.get_tensor(SCREAMING_SNAKE_CASE__ ).astype(np.floataa ) if key_name.endswith("""/adam_m""" ) or key_name.endswith("""/adam_v""" ): continue if key_name.startswith("""pasts/""" ): if key_name.startswith("""pasts/mlp""" ): __UpperCamelCase : str = int(key_name[9] ) elif key_name.startswith("""pasts/out""" ): __UpperCamelCase : Optional[int] = 8 __UpperCamelCase : Optional[int] = '''model.sqout.%d.weight''' % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time __UpperCamelCase : Optional[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : List[str] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/moe""" ): __UpperCamelCase : Any = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/switch_gating/kernel""" ): __UpperCamelCase : List[str] = '''model.blocks.%d.feed_forward.mlp.router.classifier.weight''' % player __UpperCamelCase : str = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/softmlp/kernel""" ): __UpperCamelCase : int = '''model.blocks.%d.feed_forward.soft_bypass_mlp.weight''' % player __UpperCamelCase : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : str = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/wo/kernel""" ) or key_name.endswith("""/wi/kernel""" ): __UpperCamelCase : List[str] = key_name[-9:-7] for i in range(16 ): __UpperCamelCase : List[Any] = '''model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight''' % (player, i, nlayer) __UpperCamelCase : Dict = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided __UpperCamelCase : str = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/mlp""" ): __UpperCamelCase : Union[str, Any] = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/p1/kernel""" ): __UpperCamelCase : Optional[Any] = '''model.blocks.%d.feed_forward.mlp.wi.weight''' % player __UpperCamelCase : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Union[str, Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/p1/bias""" ): __UpperCamelCase : str = '''model.blocks.%d.feed_forward.mlp.wi.bias''' % player __UpperCamelCase : str = vnp.copy() # same because it is one dimensional __UpperCamelCase : Union[str, Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/p2/kernel""" ): __UpperCamelCase : Optional[Any] = '''model.blocks.%d.feed_forward.mlp.wo.weight''' % player __UpperCamelCase : Tuple = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/p2/bias""" ): __UpperCamelCase : Optional[Any] = '''model.blocks.%d.feed_forward.mlp.wo.bias''' % player __UpperCamelCase : Any = vnp.copy() # same because it is one dimensional __UpperCamelCase : int = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/ln""" ): __UpperCamelCase : Union[str, Any] = int(key_name[8:].split("""/""" )[0] ) if key_name.endswith("""/b""" ): __UpperCamelCase : List[Any] = '''model.blocks.%d.feed_forward.norm.bias''' % player __UpperCamelCase : Any = vnp.copy() # same because it is one dimensional __UpperCamelCase : int = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/g""" ): __UpperCamelCase : Any = '''model.blocks.%d.feed_forward.norm.weight''' % player __UpperCamelCase : Dict = vnp.copy() # same because it is one dimensional __UpperCamelCase : Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/att""" ): __UpperCamelCase : int = int(key_name[9:].split("""/""" )[0] ) if key_name.endswith("""/qkv/kernel""" ): __UpperCamelCase : Union[str, Any] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum __UpperCamelCase : Tuple = state[:, 0, :, :] __UpperCamelCase : List[str] = state[:, 1, :, :] __UpperCamelCase : int = state[:, 2, :, :] __UpperCamelCase : Dict = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : List[str] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Dict = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : int = '''model.blocks.%d.self_attn.self_attn.q_proj.weight''' % player __UpperCamelCase : Union[str, Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase : int = '''model.blocks.%d.self_attn.self_attn.k_proj.weight''' % player __UpperCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase : Any = '''model.blocks.%d.self_attn.self_attn.v_proj.weight''' % player __UpperCamelCase : Tuple = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/o/kernel""" ): __UpperCamelCase : Any = '''model.blocks.%d.self_attn.self_attn.out_proj.weight''' % player __UpperCamelCase : Any = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/an""" ): __UpperCamelCase : Tuple = int(key_name[8:].split("""/""" )[0] ) if key_name.endswith("""/b""" ): __UpperCamelCase : Union[str, Any] = '''model.blocks.%d.self_attn.norm.bias''' % player __UpperCamelCase : int = vnp.copy() # same because it is one dimensional __UpperCamelCase : str = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.endswith("""/g""" ): __UpperCamelCase : int = '''model.blocks.%d.self_attn.norm.weight''' % player __UpperCamelCase : str = vnp.copy() # same because it is one dimensional __UpperCamelCase : Dict = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif ( key_name.startswith("""model/wte""" ) or key_name.startswith("""model/wpe""" ) or key_name.startswith("""model/ete""" ) ): __UpperCamelCase : int = {'''wte''': '''embed_tokens''', '''wpe''': '''position_embeddings''', '''ete''': '''extra_position_embeddings'''}[ key_name[-3:] ] __UpperCamelCase : str = '''model.%s.weight''' % nlayer __UpperCamelCase : Optional[int] = vnp.copy() # same in embedded __UpperCamelCase : Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) if key_name.startswith("""model/wte""" ): __UpperCamelCase : Tuple = '''lm_head.weight''' __UpperCamelCase : Any = vnp.copy() # same in embedded __UpperCamelCase : Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name.startswith("""model/wob""" ): __UpperCamelCase : Optional[Any] = '''final_logits_bias''' __UpperCamelCase : List[str] = vnp.copy() # same in embedded __UpperCamelCase : Union[str, Any] = state.reshape((1, -1) ) __UpperCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name == "model/dense/kernel": __UpperCamelCase : Dict = '''model.last_project.weight''' __UpperCamelCase : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix __UpperCamelCase : Any = torch.tensor(SCREAMING_SNAKE_CASE__ ) elif key_name == "model/dense_1/bias": __UpperCamelCase : Dict = '''model.last_project.bias''' __UpperCamelCase : List[Any] = vnp.copy() # same because it is one dimensional __UpperCamelCase : Optional[Any] = torch.tensor(SCREAMING_SNAKE_CASE__ ) torch.save(SCREAMING_SNAKE_CASE__ , args.output ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser( description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model') parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model') UpperCamelCase = parser.parse_args() convert_tf_gptsan_to_pt(args)
269
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :Union[str, Any] = parent UpperCamelCase :Tuple = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Any = patch_size UpperCamelCase :List[str] = num_channels UpperCamelCase :int = is_training UpperCamelCase :str = use_labels UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :int = num_hidden_layers UpperCamelCase :List[Any] = backbone_out_indices UpperCamelCase :str = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :List[str] = attention_probs_dropout_prob UpperCamelCase :Union[str, Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :int = backbone_featmap_shape UpperCamelCase :Any = scope UpperCamelCase :int = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Dict = (image_size // patch_size) ** 2 UpperCamelCase :List[str] = num_patches + 1 def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :Tuple = None if self.use_labels: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Optional[int] = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Any = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :List[str] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Optional[Any] = self.num_labels UpperCamelCase :Optional[int] = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Dict: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :int = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Tuple =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Tuple =False def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Union[str, Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :int = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Optional[int] = [*signature.parameters.keys()] UpperCamelCase :Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Any = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Dict = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :str = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Tuple: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = False UpperCamelCase :List[Any] = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[int] = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :Optional[int] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Union[str, Any] = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Any: pass @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :Any = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[int]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Dict = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[Any] = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :List[str] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = prepare_img() UpperCamelCase :List[str] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :int = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
658
0
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def _SCREAMING_SNAKE_CASE ( snake_case ) -> Any: if "model" in orig_key: _UpperCAmelCase = orig_key.replace("""model.""" , """""" ) if "norm1" in orig_key: _UpperCAmelCase = orig_key.replace("""norm1""" , """attention.output.LayerNorm""" ) if "norm2" in orig_key: _UpperCAmelCase = orig_key.replace("""norm2""" , """output.LayerNorm""" ) if "norm" in orig_key: _UpperCAmelCase = orig_key.replace("""norm""" , """LayerNorm""" ) if "transformer" in orig_key: _UpperCAmelCase = orig_key.split(""".""" )[0].split("""_""" )[-1] _UpperCAmelCase = orig_key.replace(f"transformer_{layer_num}" , f"encoder.layer.{layer_num}" ) if "mha.attn" in orig_key: _UpperCAmelCase = orig_key.replace("""mha.attn""" , """attention.self""" ) if "mha" in orig_key: _UpperCAmelCase = orig_key.replace("""mha""" , """attention""" ) if "W_q" in orig_key: _UpperCAmelCase = orig_key.replace("""W_q""" , """self.query""" ) if "W_k" in orig_key: _UpperCAmelCase = orig_key.replace("""W_k""" , """self.key""" ) if "W_v" in orig_key: _UpperCAmelCase = orig_key.replace("""W_v""" , """self.value""" ) if "ff1" in orig_key: _UpperCAmelCase = orig_key.replace("""ff1""" , """intermediate.dense""" ) if "ff2" in orig_key: _UpperCAmelCase = orig_key.replace("""ff2""" , """output.dense""" ) if "ff" in orig_key: _UpperCAmelCase = orig_key.replace("""ff""" , """output.dense""" ) if "mlm_class" in orig_key: _UpperCAmelCase = orig_key.replace("""mlm.mlm_class""" , """cls.predictions.decoder""" ) if "mlm" in orig_key: _UpperCAmelCase = orig_key.replace("""mlm""" , """cls.predictions.transform""" ) if "cls" not in orig_key: _UpperCAmelCase = '''yoso.''' + orig_key return orig_key def _SCREAMING_SNAKE_CASE ( snake_case , snake_case ) -> List[str]: for key in orig_state_dict.copy().keys(): _UpperCAmelCase = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if ("pooler" in key) or ("sen_class" in key): continue else: _UpperCAmelCase = val _UpperCAmelCase = orig_state_dict['''cls.predictions.decoder.bias'''] _UpperCAmelCase = torch.arange(SCREAMING_SNAKE_CASE__ ).expand((1, -1) ) + 2 return orig_state_dict def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> str: _UpperCAmelCase = torch.load(SCREAMING_SNAKE_CASE__ , map_location="""cpu""" )['''model_state_dict'''] _UpperCAmelCase = YosoConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) _UpperCAmelCase = YosoForMaskedLM(SCREAMING_SNAKE_CASE__ ) _UpperCAmelCase = convert_checkpoint_helper(config.max_position_embeddings , SCREAMING_SNAKE_CASE__ ) print(model.load_state_dict(SCREAMING_SNAKE_CASE__ ) ) model.eval() model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}" ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--pytorch_model_path", default=None, type=str, required=True, help="Path to YOSO pytorch checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The json file for YOSO model config.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) a = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
518
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Union[str, Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: UpperCamelCase :Any = 128 elif "12-12" in model_name: UpperCamelCase :Union[str, Any] = 12 UpperCamelCase :Any = 12 elif "14-14" in model_name: UpperCamelCase :Optional[int] = 14 UpperCamelCase :List[str] = 14 elif "16-16" in model_name: UpperCamelCase :List[Any] = 16 UpperCamelCase :Optional[Any] = 16 else: raise ValueError('''Model not supported''' ) UpperCamelCase :Tuple = '''huggingface/label-files''' if "speech-commands" in model_name: UpperCamelCase :Optional[Any] = 35 UpperCamelCase :List[Any] = '''speech-commands-v2-id2label.json''' else: UpperCamelCase :Optional[int] = 527 UpperCamelCase :List[Any] = '''audioset-id2label.json''' UpperCamelCase :Any = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) , '''r''' ) ) UpperCamelCase :List[str] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :List[Any] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): if "module.v" in name: UpperCamelCase :Any = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: UpperCamelCase :int = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: UpperCamelCase :Tuple = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: UpperCamelCase :Optional[int] = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: UpperCamelCase :str = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: UpperCamelCase :Any = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: UpperCamelCase :Union[str, Any] = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: UpperCamelCase :str = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: UpperCamelCase :Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: UpperCamelCase :Dict = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCamelCase :List[str] = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: UpperCamelCase :Union[str, Any] = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: UpperCamelCase :int = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: UpperCamelCase :Tuple = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Any ): for key in orig_state_dict.copy().keys(): UpperCamelCase :Dict = orig_state_dict.pop(SCREAMING_SNAKE_CASE__ ) if "qkv" in key: UpperCamelCase :Any = key.split('''.''' ) UpperCamelCase :str = int(key_split[3] ) UpperCamelCase :Union[str, Any] = config.hidden_size if "weight" in key: UpperCamelCase :List[str] = val[:dim, :] UpperCamelCase :Optional[Any] = val[dim : dim * 2, :] UpperCamelCase :Optional[Any] = val[-dim:, :] else: UpperCamelCase :Dict = val[:dim] UpperCamelCase :Optional[int] = val[dim : dim * 2] UpperCamelCase :List[Any] = val[-dim:] else: UpperCamelCase :Union[str, Any] = val return orig_state_dict def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :List[str] = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=False ): UpperCamelCase :Optional[Any] = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict UpperCamelCase :Optional[int] = model_name_to_url[model_name] UpperCamelCase :Tuple = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE__ ) # rename some keys UpperCamelCase :Union[str, Any] = convert_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # load 🤗 model UpperCamelCase :int = ASTForAudioClassification(SCREAMING_SNAKE_CASE__ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 UpperCamelCase :Union[str, Any] = -4.2_67_73_93 if '''speech-commands''' not in model_name else -6.84_59_78 UpperCamelCase :List[str] = 4.5_68_99_74 if '''speech-commands''' not in model_name else 5.5_65_45_26 UpperCamelCase :Optional[Any] = 1024 if '''speech-commands''' not in model_name else 128 UpperCamelCase :int = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) if "speech-commands" in model_name: UpperCamelCase :Dict = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) UpperCamelCase :List[Any] = dataset[0]['''audio''']['''array'''] else: UpperCamelCase :List[Any] = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) UpperCamelCase , UpperCamelCase :Dict = torchaudio.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = waveform.squeeze().numpy() UpperCamelCase :Optional[int] = feature_extractor(SCREAMING_SNAKE_CASE__ , sampling_rate=16000 , return_tensors='''pt''' ) # forward pass UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": UpperCamelCase :Tuple = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": UpperCamelCase :Union[str, Any] = torch.tensor([-1.19_86, -7.09_03, -8.27_18] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": UpperCamelCase :str = torch.tensor([-2.61_28, -8.00_80, -9.43_44] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": UpperCamelCase :List[str] = torch.tensor([-1.50_80, -7.45_34, -8.89_17] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": UpperCamelCase :Dict = torch.tensor([-0.50_50, -6.58_33, -8.08_43] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": UpperCamelCase :List[str] = torch.tensor([-0.38_26, -7.03_36, -8.24_13] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": UpperCamelCase :Optional[int] = torch.tensor([-1.21_13, -6.91_01, -8.34_70] ) elif model_name == "ast-finetuned-speech-commands-v2": UpperCamelCase :List[Any] = torch.tensor([6.15_89, -8.05_66, -8.79_84] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) print(F'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F'''MIT/{model_name}''' ) feature_extractor.push_to_hub(F'''MIT/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""ast-finetuned-audioset-10-10-0.4593""", type=str, help="""Name of the Audio Spectrogram Transformer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
658
0
import pickle import numpy as np from matplotlib import pyplot as plt class lowercase_ : '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : int=0.2 , __UpperCAmelCase : Any=0.2 ) ->Tuple: """simple docstring""" a = bp_numa a = bp_numa a = bp_numa a = conva_get[:2] a = conva_get[2] a = size_pa a = rate_w a = rate_t a = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) a = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) a = -2 * np.random.rand(self.conva[1] ) + 1 a = -2 * np.random.rand(self.num_bpa ) + 1 a = -2 * np.random.rand(self.num_bpa ) + 1 def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Any ) ->Dict: """simple docstring""" a = { '''num_bp1''': self.num_bpa, '''num_bp2''': self.num_bpa, '''num_bp3''': self.num_bpa, '''conv1''': self.conva, '''step_conv1''': self.step_conva, '''size_pooling1''': self.size_poolinga, '''rate_weight''': self.rate_weight, '''rate_thre''': self.rate_thre, '''w_conv1''': self.w_conva, '''wkj''': self.wkj, '''vji''': self.vji, '''thre_conv1''': self.thre_conva, '''thre_bp2''': self.thre_bpa, '''thre_bp3''': self.thre_bpa, } with open(SCREAMING_SNAKE_CASE_ , '''wb''' ) as f: pickle.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) print(F"""Model saved: {save_path}""" ) @classmethod def __lowerCAmelCase ( cls : List[Any] , __UpperCAmelCase : Union[str, Any] ) ->int: """simple docstring""" with open(SCREAMING_SNAKE_CASE_ , '''rb''' ) as f: a = pickle.load(SCREAMING_SNAKE_CASE_ ) # noqa: S301 a = model_dic.get('''conv1''' ) conv_get.append(model_dic.get('''step_conv1''' ) ) a = model_dic.get('''size_pooling1''' ) a = model_dic.get('''num_bp1''' ) a = model_dic.get('''num_bp2''' ) a = model_dic.get('''num_bp3''' ) a = model_dic.get('''rate_weight''' ) a = model_dic.get('''rate_thre''' ) # create model instance a = CNN(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # modify model parameter a = model_dic.get('''w_conv1''' ) a = model_dic.get('''wkj''' ) a = model_dic.get('''vji''' ) a = model_dic.get('''thre_conv1''' ) a = model_dic.get('''thre_bp2''' ) a = model_dic.get('''thre_bp3''' ) return conv_ins def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Tuple ) ->int: """simple docstring""" return 1 / (1 + np.exp(-1 * x )) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" return round(SCREAMING_SNAKE_CASE_ , 3 ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = convs[0] a = convs[1] a = np.shape(SCREAMING_SNAKE_CASE_ )[0] # get the data slice of original image data, data_focus a = [] for i_focus in range(0 , size_data - size_conv + 1 , SCREAMING_SNAKE_CASE_ ): for j_focus in range(0 , size_data - size_conv + 1 , SCREAMING_SNAKE_CASE_ ): a = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(SCREAMING_SNAKE_CASE_ ) # calculate the feature map of every single kernel, and saved as list of matrix a = [] a = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(SCREAMING_SNAKE_CASE_ ): a = [] for i_focus in range(len(SCREAMING_SNAKE_CASE_ ) ): a = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(SCREAMING_SNAKE_CASE_ ) ) a = np.asmatrix(SCREAMING_SNAKE_CASE_ ).reshape( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) data_featuremap.append(SCREAMING_SNAKE_CASE_ ) # expanding the data slice to One dimenssion a = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(SCREAMING_SNAKE_CASE_ ) ) a = np.asarray(SCREAMING_SNAKE_CASE_ ) return focus_list, data_featuremap def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict="average_pool" ) ->Tuple: """simple docstring""" a = len(featuremaps[0] ) a = int(size_map / size_pooling ) a = [] for i_map in range(len(SCREAMING_SNAKE_CASE_ ) ): a = featuremaps[i_map] a = [] for i_focus in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for j_focus in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): a = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(SCREAMING_SNAKE_CASE_ ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(SCREAMING_SNAKE_CASE_ ) ) a = np.asmatrix(SCREAMING_SNAKE_CASE_ ).reshape(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) featuremap_pooled.append(SCREAMING_SNAKE_CASE_ ) return featuremap_pooled def __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[Any] ) ->Optional[int]: """simple docstring""" a = [] for i in range(len(SCREAMING_SNAKE_CASE_ ) ): a = np.shape(data[i] ) a = data[i].reshape(1 , shapes[0] * shapes[1] ) a = data_listed.getA().tolist()[0] data_expanded.extend(SCREAMING_SNAKE_CASE_ ) a = np.asarray(SCREAMING_SNAKE_CASE_ ) return data_expanded def __lowerCAmelCase ( self : str , __UpperCAmelCase : str ) ->Optional[int]: """simple docstring""" a = np.asarray(SCREAMING_SNAKE_CASE_ ) a = np.shape(SCREAMING_SNAKE_CASE_ ) a = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : str ) ->int: """simple docstring""" a = [] a = 0 for i_map in range(SCREAMING_SNAKE_CASE_ ): a = np.ones((size_map, size_map) ) for i in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for j in range(0 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): a = pd_pool[ i_pool ] a = i_pool + 1 a = np.multiply( SCREAMING_SNAKE_CASE_ , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(SCREAMING_SNAKE_CASE_ ) return pd_all def __lowerCAmelCase ( self : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Dict=bool ) ->List[Any]: """simple docstring""" print('''----------------------Start Training-------------------------''' ) print((''' - - Shape: Train_Data ''', np.shape(SCREAMING_SNAKE_CASE_ )) ) print((''' - - Shape: Teach_Data ''', np.shape(SCREAMING_SNAKE_CASE_ )) ) a = 0 a = [] a = 10_000 while rp < n_repeat and mse >= error_accuracy: a = 0 print(F"""-------------Learning Time {rp}--------------""" ) for p in range(len(SCREAMING_SNAKE_CASE_ ) ): # print('------------Learning Image: %d--------------'%p) a = np.asmatrix(datas_train[p] ) a = np.asarray(datas_teach[p] ) a = self.convolute( SCREAMING_SNAKE_CASE_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a = self.pooling(SCREAMING_SNAKE_CASE_ , self.size_poolinga ) a = np.shape(SCREAMING_SNAKE_CASE_ ) a = self._expand(SCREAMING_SNAKE_CASE_ ) a = data_bp_input a = np.dot(SCREAMING_SNAKE_CASE_ , self.vji.T ) - self.thre_bpa a = self.sig(SCREAMING_SNAKE_CASE_ ) a = np.dot(SCREAMING_SNAKE_CASE_ , self.wkj.T ) - self.thre_bpa a = self.sig(SCREAMING_SNAKE_CASE_ ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- a = np.multiply( (data_teach - bp_outa) , np.multiply(SCREAMING_SNAKE_CASE_ , (1 - bp_outa) ) ) a = np.multiply( np.dot(SCREAMING_SNAKE_CASE_ , self.wkj ) , np.multiply(SCREAMING_SNAKE_CASE_ , (1 - bp_outa) ) ) a = np.dot(SCREAMING_SNAKE_CASE_ , self.vji ) a = pd_i_all / (self.size_poolinga * self.size_poolinga) a = pd_conva_pooled.T.getA().tolist() a = self._calculate_gradient_from_pool( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): a = self._expand_mat(pd_conva_all[k_conv] ) a = self.rate_weight * np.dot(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) a = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) a = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer a = self.wkj + pd_k_all.T * bp_outa * self.rate_weight a = self.vji + pd_j_all.T * bp_outa * self.rate_weight a = self.thre_bpa - pd_k_all * self.rate_thre a = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image a = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) a = rp + 1 a = error_count / patterns all_mse.append(SCREAMING_SNAKE_CASE_ ) def draw_error(): a = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(SCREAMING_SNAKE_CASE_ , '''+-''' ) plt.plot(SCREAMING_SNAKE_CASE_ , '''r--''' ) plt.xlabel('''Learning Times''' ) plt.ylabel('''All_mse''' ) plt.grid(SCREAMING_SNAKE_CASE_ , alpha=0.5 ) plt.show() print('''------------------Training Complished---------------------''' ) print((''' - - Training epoch: ''', rp, F""" - - Mse: {mse:.6f}""") ) if draw_e: draw_error() return mse def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[str] ) ->int: """simple docstring""" a = [] print('''-------------------Start Testing-------------------------''' ) print((''' - - Shape: Test_Data ''', np.shape(SCREAMING_SNAKE_CASE_ )) ) for p in range(len(SCREAMING_SNAKE_CASE_ ) ): a = np.asmatrix(datas_test[p] ) a = self.convolute( SCREAMING_SNAKE_CASE_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a = self.pooling(SCREAMING_SNAKE_CASE_ , self.size_poolinga ) a = self._expand(SCREAMING_SNAKE_CASE_ ) a = data_bp_input a = bp_outa * self.vji.T - self.thre_bpa a = self.sig(SCREAMING_SNAKE_CASE_ ) a = bp_outa * self.wkj.T - self.thre_bpa a = self.sig(SCREAMING_SNAKE_CASE_ ) produce_out.extend(bp_outa.getA().tolist() ) a = [list(map(self.do_round , SCREAMING_SNAKE_CASE_ ) ) for each in produce_out] return np.asarray(SCREAMING_SNAKE_CASE_ ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[Any] ) ->int: """simple docstring""" a = np.asmatrix(SCREAMING_SNAKE_CASE_ ) a = self.convolute( SCREAMING_SNAKE_CASE_ , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) a = self.pooling(SCREAMING_SNAKE_CASE_ , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
117
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_llama""": ["""LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LlamaConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""LlamaTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """LlamaForCausalLM""", """LlamaModel""", """LlamaPreTrainedModel""", """LlamaForSequenceClassification""", ] if TYPE_CHECKING: from .configuration_llama import LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP, LlamaConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama import LlamaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_llama_fast import LlamaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_llama import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaPreTrainedModel else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch __UpperCamelCase : Any = logging.get_logger(__name__) class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ['pixel_values'] def __init__( self : Union[str, Any] , UpperCamelCase__ : List[str] = True , UpperCamelCase__ : Optional[Any] = None , UpperCamelCase__ : int = PILImageResampling.BILINEAR , UpperCamelCase__ : Optional[Any] = True , UpperCamelCase__ : Tuple = 1 / 255 , UpperCamelCase__ : Tuple = True , UpperCamelCase__ : Optional[Any] = None , UpperCamelCase__ : Any = True , **UpperCamelCase__ : Optional[Any] , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 224} SCREAMING_SNAKE_CASE : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : Optional[Any] = crop_size if crop_size is not None else {'''height''': 256, '''width''': 256} SCREAMING_SNAKE_CASE : Any = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE : Optional[Any] = do_resize SCREAMING_SNAKE_CASE : Dict = size SCREAMING_SNAKE_CASE : Tuple = resample SCREAMING_SNAKE_CASE : List[Any] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : List[Any] = do_center_crop SCREAMING_SNAKE_CASE : Dict = crop_size SCREAMING_SNAKE_CASE : Any = do_flip_channel_order def __A ( self : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] = PIL.Image.BILINEAR , UpperCamelCase__ : Union[str, Any] = None , **UpperCamelCase__ : str , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) SCREAMING_SNAKE_CASE : 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 __A ( self : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] = None , **UpperCamelCase__ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : 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()}""" ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self : Dict , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] = None , **UpperCamelCase__ : Union[str, Any] , ): '''simple docstring''' return rescale(SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def __A ( self : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] = None ): '''simple docstring''' return flip_channel_order(SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ ) def __A ( self : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict = None , UpperCamelCase__ : Tuple = None , UpperCamelCase__ : Optional[Any] = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Union[str, Any] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : List[Any] = None , UpperCamelCase__ : Any = ChannelDimension.FIRST , **UpperCamelCase__ : List[str] , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : str = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : List[str] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : Union[str, Any] = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) SCREAMING_SNAKE_CASE : List[str] = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : int = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Dict = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) SCREAMING_SNAKE_CASE : List[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_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[Any] = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE : List[Any] = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : str = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: SCREAMING_SNAKE_CASE : List[str] = [self.flip_channel_order(image=SCREAMING_SNAKE_CASE_ ) for image in images] SCREAMING_SNAKE_CASE : Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def __A ( self : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : Dict = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE : Tuple = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : List[Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
248
import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets __snake_case = """\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } """ __snake_case = """\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy. """ __snake_case = R""" Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") Examples: >>> metric = datasets.load_metric(\"competition_math\") >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"]) >>> print(results) {'accuracy': 1.0} """ @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' ), '''references''': datasets.Value('''string''' ), } ) , homepage='''https://github.com/hendrycks/math''' , codebase_urls=['''https://github.com/hendrycks/math'''] , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Tuple = 0.0 for i, j in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): n_correct += 1.0 if math_equivalence.is_equiv(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else 0.0 UpperCamelCase :int = n_correct / len(SCREAMING_SNAKE_CASE_ ) return { "accuracy": accuracy, }
658
0
def __UpperCamelCase ( lowerCAmelCase__ : List[str] ): __a : Dict = [0] * len(SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = [] __a : Dict = [] __a : str = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(SCREAMING_SNAKE_CASE__ ) ): if indegree[i] == 0: queue.append(SCREAMING_SNAKE_CASE__ ) while queue: __a : Any = queue.pop(0 ) cnt += 1 topo.append(SCREAMING_SNAKE_CASE__ ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(SCREAMING_SNAKE_CASE__ ) if cnt != len(SCREAMING_SNAKE_CASE__ ): print('''Cycle exists''' ) else: print(SCREAMING_SNAKE_CASE__ ) # Adjacency List of Graph lowercase__ ={0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
521
import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __snake_case = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ """text-classification""", """language-modeling""", """summarization""", """token-classification""", """question-answering""", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __snake_case = logging.getLogger() def _A ( ): UpperCamelCase :List[Any] = argparse.ArgumentParser() parser.add_argument('''-f''' ) UpperCamelCase :Dict = parser.parse_args() return args.f def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]="eval" ): UpperCamelCase :Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''{split}_results.json''' ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) raise ValueError(F'''can\'t find {path}''' ) __snake_case = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCAmelCase_ ( lowercase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_glue.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[Any] = F''' run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_clm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 100 ) @slow def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = self.get_auto_remove_tmp_dir() UpperCamelCase :Any = F''' run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_summarization_flax.main() UpperCamelCase :str = get_results(SCREAMING_SNAKE_CASE_ , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 10 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :List[str] = F''' run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_mlm_flax.main() UpperCamelCase :Dict = get_results(SCREAMING_SNAKE_CASE_ ) self.assertLess(result['''eval_perplexity'''] , 42 ) @slow def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.get_auto_remove_tmp_dir() UpperCamelCase :int = F''' run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_ta_mlm_flax.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.42 ) @slow def UpperCAmelCase ( self ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCamelCase :Tuple = 7 if get_gpu_count() > 1 else 2 UpperCamelCase :int = self.get_auto_remove_tmp_dir() UpperCamelCase :Optional[int] = F''' run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_flax_ner.main() UpperCamelCase :Any = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[str] = self.get_auto_remove_tmp_dir() UpperCamelCase :Dict = F''' run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 '''.split() with patch.object(SCREAMING_SNAKE_CASE_ , '''argv''' , SCREAMING_SNAKE_CASE_ ): run_qa.main() UpperCamelCase :int = get_results(SCREAMING_SNAKE_CASE_ ) self.assertGreaterEqual(result['''eval_f1'''] , 30 ) self.assertGreaterEqual(result['''eval_exact'''] , 30 )
658
0
"""simple docstring""" import math def __magic_name__ ( _lowerCamelCase: list, _lowerCamelCase: int = 0, _lowerCamelCase: int = 0 ) -> str: '''simple docstring''' lowerCAmelCase = end or len(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): lowerCAmelCase = i lowerCAmelCase = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: lowerCAmelCase = array[temp_index - 1] temp_index -= 1 lowerCAmelCase = temp_index_value return array def __magic_name__ ( _lowerCamelCase: list, _lowerCamelCase: int, _lowerCamelCase: int ) -> Union[str, Any]: # Max Heap '''simple docstring''' lowerCAmelCase = index lowerCAmelCase = 2 * index + 1 # Left Node lowerCAmelCase = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: lowerCAmelCase = left_index if right_index < heap_size and array[largest] < array[right_index]: lowerCAmelCase = right_index if largest != index: lowerCAmelCase = array[largest], array[index] heapify(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def __magic_name__ ( _lowerCamelCase: list ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase = len(SCREAMING_SNAKE_CASE__ ) for i in range(n // 2, -1, -1 ): heapify(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for i in range(n - 1, 0, -1 ): lowerCAmelCase = array[0], array[i] heapify(SCREAMING_SNAKE_CASE__, 0, SCREAMING_SNAKE_CASE__ ) return array def __magic_name__ ( _lowerCamelCase: list, _lowerCamelCase: int, _lowerCamelCase: int, _lowerCamelCase: int ) -> Dict: '''simple docstring''' if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def __magic_name__ ( _lowerCamelCase: list, _lowerCamelCase: int, _lowerCamelCase: int, _lowerCamelCase: int ) -> List[Any]: '''simple docstring''' lowerCAmelCase = low lowerCAmelCase = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i lowerCAmelCase = array[j], array[i] i += 1 def __magic_name__ ( _lowerCamelCase: list ) -> Optional[int]: '''simple docstring''' if len(SCREAMING_SNAKE_CASE__ ) == 0: return array lowerCAmelCase = 2 * math.ceil(math.loga(len(SCREAMING_SNAKE_CASE__ ) ) ) lowerCAmelCase = 16 return intro_sort(SCREAMING_SNAKE_CASE__, 0, len(SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def __magic_name__ ( _lowerCamelCase: list, _lowerCamelCase: int, _lowerCamelCase: int, _lowerCamelCase: int, _lowerCamelCase: int ) -> str: '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(SCREAMING_SNAKE_CASE__ ) max_depth -= 1 lowerCAmelCase = median_of_a(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, start + ((end - start) // 2) + 1, end - 1 ) lowerCAmelCase = partition(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) intro_sort(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = p return insertion_sort(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase = input("""Enter numbers separated by a comma : """).strip() UpperCAmelCase = [float(item) for item in user_input.split(""",""")] print(sort(unsorted))
535
from __future__ import annotations from collections.abc import Callable def _A ( SCREAMING_SNAKE_CASE__ : Callable[[int | float], int | float] , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int | float , SCREAMING_SNAKE_CASE__ : int = 100 , ): UpperCamelCase :Optional[Any] = x_start UpperCamelCase :Any = fnc(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = 0.0 for _ in range(SCREAMING_SNAKE_CASE__ ): # Approximates small segments of curve as linear and solve # for trapezoidal area UpperCamelCase :Any = (x_end - x_start) / steps + xa UpperCamelCase :Dict = fnc(SCREAMING_SNAKE_CASE__ ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step UpperCamelCase :Optional[int] = xa UpperCamelCase :List[str] = fxa return area if __name__ == "__main__": def _A ( SCREAMING_SNAKE_CASE__ : int ): return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") __snake_case = 10 while i <= 10_00_00: print(f'''with {i} steps: {trapezoidal_area(f, -5, 5, i)}''') i *= 10
658
0
"""simple docstring""" from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging lowerCAmelCase: int =logging.get_logger(__name__) def __snake_case ( __A ,__A ) -> str: try: with open(SCREAMING_SNAKE_CASE__ ,"""rb""" ) as flax_state_f: lowercase : Optional[int] = from_bytes(SCREAMING_SNAKE_CASE__ ,flax_state_f.read() ) except UnpicklingError as e: try: with open(SCREAMING_SNAKE_CASE__ ) as f: if f.read().startswith("""version""" ): raise OSError( """You seem to have cloned a repository without having git-lfs installed. Please""" """ install git-lfs and run `git lfs install` followed by `git lfs pull` in the""" """ folder you cloned.""" ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F'''Unable to convert {model_file} to Flax deserializable object. ''' ) return load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def __snake_case ( __A ,__A ) -> Optional[Any]: try: import torch # noqa: F401 except ImportError: logger.error( """Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see""" """ https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation""" """ instructions.""" ) raise # check if we have bf16 weights lowercase : Tuple = flatten_dict(jax.tree_util.tree_map(lambda __A : x.dtype == jnp.bfloataa ,SCREAMING_SNAKE_CASE__ ) ).values() if any(SCREAMING_SNAKE_CASE__ ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( """Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` """ """before loading those in PyTorch model.""" ) lowercase : Tuple = jax.tree_util.tree_map( lambda __A : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params ,SCREAMING_SNAKE_CASE__ ) lowercase : int = '''''' lowercase : str = flatten_dict(SCREAMING_SNAKE_CASE__ ,sep=""".""" ) lowercase : Optional[Any] = pt_model.state_dict() # keep track of unexpected & missing keys lowercase : Union[str, Any] = [] lowercase : int = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): lowercase : Union[str, Any] = flax_key_tuple.split(""".""" ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: lowercase : Optional[Any] = flax_key_tuple_array[:-1] + ['''weight'''] lowercase : Union[str, Any] = jnp.transpose(SCREAMING_SNAKE_CASE__ ,(3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": lowercase : Union[str, Any] = flax_key_tuple_array[:-1] + ['''weight'''] lowercase : List[Any] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": lowercase : Union[str, Any] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(SCREAMING_SNAKE_CASE__ ): lowercase : str = ( flax_key_tuple_string.replace("""_0""" ,""".0""" ) .replace("""_1""" ,""".1""" ) .replace("""_2""" ,""".2""" ) .replace("""_3""" ,""".3""" ) .replace("""_4""" ,""".4""" ) .replace("""_5""" ,""".5""" ) .replace("""_6""" ,""".6""" ) .replace("""_7""" ,""".7""" ) .replace("""_8""" ,""".8""" ) .replace("""_9""" ,""".9""" ) ) lowercase : Dict = '''.'''.join(SCREAMING_SNAKE_CASE__ ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'''Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ''' F'''to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) else: # add weight to pytorch dict lowercase : Dict = np.asarray(SCREAMING_SNAKE_CASE__ ) if not isinstance(SCREAMING_SNAKE_CASE__ ,np.ndarray ) else flax_tensor lowercase : Optional[int] = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) # remove from missing keys missing_keys.remove(SCREAMING_SNAKE_CASE__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(SCREAMING_SNAKE_CASE__ ) pt_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) # re-transform missing_keys to list lowercase : Tuple = list(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: logger.warning( """Some weights of the Flax model were not used when initializing the PyTorch model""" F''' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing''' F''' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture''' """ (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This""" F''' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect''' """ to be exactly identical (e.g. initializing a BertForSequenceClassification model from a""" """ FlaxBertForSequenceClassification model).""" ) if len(SCREAMING_SNAKE_CASE__ ) > 0: logger.warning( F'''Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly''' F''' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to''' """ use it for predictions and inference.""" ) return pt_model
607
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :str = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**SCREAMING_SNAKE_CASE_ ) return config def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[Any] = 10 UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Dict = self.scheduler_classes[0](**SCREAMING_SNAKE_CASE_ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps[0] UpperCamelCase :Union[str, Any] = scheduler.timesteps[1] UpperCamelCase :str = self.dummy_sample UpperCamelCase :List[str] = 0.1 * sample UpperCamelCase :List[str] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :str = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase ( self ) -> List[str]: for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :List[Any] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = 1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = scheduler.timesteps UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = self.dummy_model() UpperCamelCase :List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE_ ): # 1. scale model input UpperCamelCase :List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :List[Any] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :Tuple = pred_prev_sample UpperCamelCase :Any = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 192.7614 ) < 1e-2 assert abs(result_mean.item() - 0.2510 ) < 1e-3 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = self.scheduler_classes[0] UpperCamelCase :Optional[Any] = self.get_scheduler_config() UpperCamelCase :Optional[Any] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = [106, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = scheduler.timesteps UpperCamelCase :int = torch.manual_seed(0 ) UpperCamelCase :str = self.dummy_model() UpperCamelCase :List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input UpperCamelCase :List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 2. predict noise residual UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # 3. predict previous sample x_t-1 UpperCamelCase :Optional[int] = scheduler.step(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , generator=SCREAMING_SNAKE_CASE_ ).prev_sample UpperCamelCase :int = pred_prev_sample UpperCamelCase :Tuple = torch.sum(torch.abs(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE_ ) ) assert abs(result_sum.item() - 347.6357 ) < 1e-2 assert abs(result_mean.item() - 0.4527 ) < 1e-3 def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :Tuple = self.get_scheduler_config() UpperCamelCase :List[str] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = [39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[str] = self.scheduler_classes[0] UpperCamelCase :List[Any] = self.get_scheduler_config() UpperCamelCase :Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = [39, 30, 12, 1, 0] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) with self.assertRaises(SCREAMING_SNAKE_CASE_ , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE_ , timesteps=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Optional[int] = self.scheduler_classes[0] UpperCamelCase :List[str] = self.get_scheduler_config() UpperCamelCase :Dict = scheduler_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE_ , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE_ )
658
0
import math import random def UpperCamelCase_ ( __a , __a = False ) -> int: if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value UpperCamelCase : Dict = 0.02 def UpperCamelCase_ ( __a , __a ) -> int: a__ : List[str] = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(SCREAMING_SNAKE_CASE__ ): # Forward propagation a__ : Any = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? a__ : List[str] = (expected / 100) - layer_a # Error delta a__ : Optional[int] = layer_1_error * sigmoid_function(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase : List[Any] = int(input("""Expected value: """)) UpperCamelCase : List[Any] = int(input("""Number of propagations: """)) print(forward_propagation(expected, number_propagations))
37
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __snake_case = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
658
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = { '''configuration_jukebox''': [ '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''JukeboxConfig''', '''JukeboxPriorConfig''', '''JukeboxVQVAEConfig''', ], '''tokenization_jukebox''': ['''JukeboxTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST''', '''JukeboxModel''', '''JukeboxPreTrainedModel''', '''JukeboxVQVAE''', '''JukeboxPrior''', ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
279
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: return None class UpperCAmelCase_ : """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: return None class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =[ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase ( self ) -> List[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[int]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) @require_torch @slow def UpperCAmelCase ( self ) -> int: from transformers import BertModel UpperCamelCase :int = ['''[UNK]''', '''[SEP]''', '''[CLS]''', '''[PAD]''', '''[MASK]''', '''some''', '''other''', '''words'''] with NamedTemporaryFile(mode='''w+t''' ) as vocab_file: vocab_file.write('''\n'''.join(SCREAMING_SNAKE_CASE_ ) ) vocab_file.flush() UpperCamelCase :Tuple = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: UpperCamelCase :Union[str, Any] = BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE_ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , SCREAMING_SNAKE_CASE_ ) @require_tf @slow def UpperCAmelCase ( self ) -> str: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :Tuple = self._test_export(SCREAMING_SNAKE_CASE_ , '''tf''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = quantize(Path(SCREAMING_SNAKE_CASE_ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) @require_torch @slow def UpperCAmelCase ( self ) -> Optional[Any]: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: UpperCamelCase :str = self._test_export(SCREAMING_SNAKE_CASE_ , '''pt''' , 12 , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = quantize(SCREAMING_SNAKE_CASE_ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE_ ).stat().st_size: self.fail('''Quantized model is bigger than initial ONNX model''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: try: # Compute path with TemporaryDirectory() as tempdir: UpperCamelCase :Union[str, Any] = Path(SCREAMING_SNAKE_CASE_ ).joinpath('''model.onnx''' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE_ ) @require_torch @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[str]: from transformers import BertModel UpperCamelCase :List[Any] = BertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :int = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''pt''' ) @require_tf @require_tokenizers @slow def UpperCAmelCase ( self ) -> List[Any]: from transformers import TFBertModel UpperCamelCase :Optional[Any] = TFBertModel(BertConfig.from_pretrained('''lysandre/tiny-bert-random''' ) ) UpperCamelCase :Optional[Any] = BertTokenizerFast.from_pretrained('''lysandre/tiny-bert-random''' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , '''tf''' ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :Tuple = FeatureExtractionPipeline(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''output_0''', '''output_1'''] UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = infer_shapes(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE_ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE_ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: '''batch''', 1: '''sequence'''} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['''output_0'''] , {0: '''batch''', 1: '''sequence'''} ) self.assertDictEqual(shapes['''output_1'''] , {0: '''batch'''} ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''input_ids''', '''attention_mask''', '''token_type_ids'''] UpperCamelCase :Tuple = {'''input_ids''': [1, 2, 3, 4], '''attention_mask''': [0, 0, 0, 0], '''token_type_ids''': [1, 1, 1, 1]} UpperCamelCase , UpperCamelCase :Any = ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE_ ) , set(SCREAMING_SNAKE_CASE_ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE_ , (tokens['''input_ids'''], tokens['''token_type_ids'''], tokens['''attention_mask''']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) UpperCamelCase , UpperCamelCase :Tuple = ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['''input_ids'''] ) self.assertEqual(ordered_input_names[0] , '''input_ids''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :str = generate_identified_filename(Path('''/home/something/my_fake_model.onnx''' ) , '''-test''' ) self.assertEqual('''/home/something/my_fake_model-test.onnx''' , generated.as_posix() )
658
0