code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): 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 not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 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 __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : 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(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): 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""")
73
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaPriorEmbaEmbPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ,unittest.TestCase ): _UpperCAmelCase : int = KandinskyVaaControlnetImgaImgPipeline _UpperCAmelCase : List[Any] = ["image_embeds", "negative_image_embeds", "image", "hint"] _UpperCAmelCase : Dict = ["image_embeds", "negative_image_embeds", "image", "hint"] _UpperCAmelCase : Any = [ "generator", "height", "width", "strength", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] _UpperCAmelCase : Union[str, Any] = False @property def __lowerCamelCase ( self : int ) ->Tuple: return 3_2 @property def __lowerCamelCase ( self : Dict ) ->Tuple: return 3_2 @property def __lowerCamelCase ( self : Optional[int] ) ->Union[str, Any]: return self.time_input_dim @property def __lowerCamelCase ( self : List[str] ) ->Tuple: return self.time_input_dim * 4 @property def __lowerCamelCase ( self : Tuple ) ->List[Any]: return 1_0_0 @property def __lowerCamelCase ( self : Tuple ) ->List[str]: torch.manual_seed(0 ) lowerCamelCase__ : Optional[int] = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } lowerCamelCase__ : List[str] = UNetaDConditionModel(**A ) return model @property def __lowerCamelCase ( self : Union[str, Any] ) ->Optional[Any]: return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def __lowerCamelCase ( self : Optional[int] ) ->Union[str, Any]: torch.manual_seed(0 ) lowerCamelCase__ : Union[str, Any] = VQModel(**self.dummy_movq_kwargs ) return model def __lowerCamelCase ( self : Tuple ) ->List[str]: lowerCamelCase__ : List[str] = self.dummy_unet lowerCamelCase__ : Tuple = self.dummy_movq lowerCamelCase__ : int = { '''num_train_timesteps''': 1_0_0_0, '''beta_schedule''': '''linear''', '''beta_start''': 0.0_00_85, '''beta_end''': 0.0_12, '''clip_sample''': False, '''set_alpha_to_one''': False, '''steps_offset''': 0, '''prediction_type''': '''epsilon''', '''thresholding''': False, } lowerCamelCase__ : Any = DDIMScheduler(**A ) lowerCamelCase__ : List[str] = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def __lowerCamelCase ( self : Tuple , A : List[Any] , A : List[str]=0 ) ->Union[str, Any]: lowerCamelCase__ : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(A ) ).to(A ) lowerCamelCase__ : str = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( A ) # create init_image lowerCamelCase__ : Tuple = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(A ) ).to(A ) lowerCamelCase__ : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase__ : str = Image.fromarray(np.uinta(A ) ).convert('''RGB''' ).resize((2_5_6, 2_5_6) ) # create hint lowerCamelCase__ : Dict = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(A ) ).to(A ) if str(A ).startswith('''mps''' ): lowerCamelCase__ : List[Any] = torch.manual_seed(A ) else: lowerCamelCase__ : Any = torch.Generator(device=A ).manual_seed(A ) lowerCamelCase__ : Tuple = { '''image''': init_image, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''num_inference_steps''': 1_0, '''guidance_scale''': 7.0, '''strength''': 0.2, '''output_type''': '''np''', } return inputs def __lowerCamelCase ( self : List[str] ) ->List[str]: lowerCamelCase__ : Union[str, Any] = '''cpu''' lowerCamelCase__ : Tuple = self.get_dummy_components() lowerCamelCase__ : Dict = self.pipeline_class(**A ) lowerCamelCase__ : Dict = pipe.to(A ) pipe.set_progress_bar_config(disable=A ) lowerCamelCase__ : Optional[Any] = pipe(**self.get_dummy_inputs(A ) ) lowerCamelCase__ : Tuple = output.images lowerCamelCase__ : Tuple = pipe( **self.get_dummy_inputs(A ) , return_dict=A , )[0] lowerCamelCase__ : Union[str, Any] = image[0, -3:, -3:, -1] lowerCamelCase__ : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCamelCase__ : Union[str, Any] = np.array( [0.54_98_50_34, 0.55_50_93_65, 0.52_56_15_04, 0.5_57_04_94, 0.5_59_38_18, 0.5_26_39_79, 0.50_28_56_43, 0.5_06_98_46, 0.51_19_67_36] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): def __lowerCamelCase ( self : str ) ->List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self : List[str] ) ->Union[str, Any]: lowerCamelCase__ : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_img2img_robotcat_fp16.npy''' ) lowerCamelCase__ : Optional[int] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) lowerCamelCase__ : int = init_image.resize((5_1_2, 5_1_2) ) lowerCamelCase__ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) lowerCamelCase__ : Optional[int] = torch.from_numpy(np.array(A ) ).float() / 2_5_5.0 lowerCamelCase__ : Any = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) lowerCamelCase__ : str = '''A robot, 4k photo''' lowerCamelCase__ : Union[str, Any] = KandinskyVaaPriorEmbaEmbPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(A ) lowerCamelCase__ : Optional[Any] = KandinskyVaaControlnetImgaImgPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' , torch_dtype=torch.floataa ) lowerCamelCase__ : Optional[Any] = pipeline.to(A ) pipeline.set_progress_bar_config(disable=A ) lowerCamelCase__ : Optional[Any] = torch.Generator(device='''cpu''' ).manual_seed(0 ) lowerCamelCase__ : Optional[Any] = pipe_prior( A , image=A , strength=0.85 , generator=A , negative_prompt='''''' , ).to_tuple() lowerCamelCase__ : List[Any] = pipeline( image=A , image_embeds=A , negative_image_embeds=A , hint=A , generator=A , num_inference_steps=1_0_0 , height=5_1_2 , width=5_1_2 , strength=0.5 , output_type='''np''' , ) lowerCamelCase__ : Tuple = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(A , A )
365
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel _A : Optional[Any] = { 'text_branch': 'text_model', 'audio_branch': 'audio_model.audio_encoder', 'attn': 'attention.self', 'self.proj': 'output.dense', 'attention.self_mask': 'attn_mask', 'mlp.fc1': 'intermediate.dense', 'mlp.fc2': 'output.dense', 'norm1': 'layernorm_before', 'norm2': 'layernorm_after', 'bn0': 'batch_norm', } _A : Any = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc') def _a ( UpperCAmelCase , UpperCAmelCase=False ) -> str: """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : List[str] = create_model( '''HTSAT-tiny''' , '''roberta''' , UpperCAmelCase , precision='''fp32''' , device='''cuda:0''' if torch.cuda.is_available() else '''cpu''' , enable_fusion=UpperCAmelCase , fusion_type='''aff_2d''' if enable_fusion else None , ) return model, model_cfg def _a ( UpperCAmelCase ) -> Optional[int]: """simple docstring""" lowerCamelCase__ : Optional[int] = {} lowerCamelCase__ : int = R'''.*sequential.(\d+).*''' lowerCamelCase__ : Any = R'''.*_projection.(\d+).*''' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: lowerCamelCase__ : List[str] = key.replace(UpperCAmelCase , UpperCAmelCase ) if re.match(UpperCAmelCase , UpperCAmelCase ): # replace sequential layers with list lowerCamelCase__ : List[Any] = re.match(UpperCAmelCase , UpperCAmelCase ).group(1 ) lowerCamelCase__ : Optional[int] = key.replace(f"sequential.{sequential_layer}." , f"layers.{int(UpperCAmelCase )//3}.linear." ) elif re.match(UpperCAmelCase , UpperCAmelCase ): lowerCamelCase__ : Optional[int] = int(re.match(UpperCAmelCase , UpperCAmelCase ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... lowerCamelCase__ : str = 1 if projecton_layer == 0 else 2 lowerCamelCase__ : List[str] = key.replace(f"_projection.{projecton_layer}." , f"_projection.linear{transformers_projection_layer}." ) if "audio" and "qkv" in key: # split qkv into query key and value lowerCamelCase__ : Optional[Any] = value lowerCamelCase__ : Optional[Any] = mixed_qkv.size(0 ) // 3 lowerCamelCase__ : Tuple = mixed_qkv[:qkv_dim] lowerCamelCase__ : Dict = mixed_qkv[qkv_dim : qkv_dim * 2] lowerCamelCase__ : int = mixed_qkv[qkv_dim * 2 :] lowerCamelCase__ : Optional[int] = query_layer lowerCamelCase__ : str = key_layer lowerCamelCase__ : List[str] = value_layer else: lowerCamelCase__ : Tuple = value return model_state_dict def _a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=False ) -> List[Any]: """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : Dict = init_clap(UpperCAmelCase , enable_fusion=UpperCAmelCase ) clap_model.eval() lowerCamelCase__ : List[Any] = clap_model.state_dict() lowerCamelCase__ : Dict = rename_state_dict(UpperCAmelCase ) lowerCamelCase__ : Optional[int] = ClapConfig() lowerCamelCase__ : Optional[int] = enable_fusion lowerCamelCase__ : Optional[Any] = ClapModel(UpperCAmelCase ) # ignore the spectrogram embedding layer model.load_state_dict(UpperCAmelCase , strict=UpperCAmelCase ) model.save_pretrained(UpperCAmelCase ) transformers_config.save_pretrained(UpperCAmelCase ) if __name__ == "__main__": _A : int = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not') _A : Tuple = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
265
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __UpperCAmelCase = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCAmelCase = """ Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior.to(\"cuda\") >>> prompt = \"A red cartoon frog, 4k\" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16 ... ) >>> pipe.to(\"cuda\") >>> init_image = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/frog.png\" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save(\"red_frog.png\") ``` """ def __A ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE : List[str] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def __A ( lowerCamelCase_ , lowerCamelCase_=5_12 , lowerCamelCase_=5_12 ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) SCREAMING_SNAKE_CASE : Optional[int] = np.array(pil_image.convert("""RGB""" ) ) SCREAMING_SNAKE_CASE : int = arr.astype(np.floataa ) / 127.5 - 1 SCREAMING_SNAKE_CASE : Optional[int] = np.transpose(lowerCamelCase_ , [2, 0, 1] ) SCREAMING_SNAKE_CASE : Optional[Any] = torch.from_numpy(lowerCamelCase_ ).unsqueeze(0 ) return image class UpperCamelCase__ ( lowercase_ ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase_ : UNetaDConditionModel , lowerCamelCase_ : DDPMScheduler , lowerCamelCase_ : VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=lowerCamelCase_ , scheduler=lowerCamelCase_ , movq=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCamelCase_ ( self : Dict , lowerCamelCase_ : int , lowerCamelCase_ : List[Any] , lowerCamelCase_ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = min(int(num_inference_steps * strength ) , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = max(num_inference_steps - init_timestep , 0 ) SCREAMING_SNAKE_CASE : int = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCamelCase_ ( self : Any , lowerCamelCase_ : Dict , lowerCamelCase_ : Dict , lowerCamelCase_ : Union[str, Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : List[Any] , lowerCamelCase_ : List[Any] , lowerCamelCase_ : List[Any]=None ): '''simple docstring''' if not isinstance(lowerCamelCase_ , (torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(lowerCamelCase_ )}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = image.to(device=lowerCamelCase_ , dtype=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = batch_size * num_images_per_prompt if image.shape[1] == 4: SCREAMING_SNAKE_CASE : str = image else: if isinstance(lowerCamelCase_ , lowerCamelCase_ ) and len(lowerCamelCase_ ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(lowerCamelCase_ )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) elif isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Any = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(lowerCamelCase_ ) ] SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(lowerCamelCase_ , dim=0 ) else: SCREAMING_SNAKE_CASE : List[str] = self.movq.encode(lowerCamelCase_ ).latent_dist.sample(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = self.movq.config.scaling_factor * init_latents SCREAMING_SNAKE_CASE : List[str] = torch.cat([init_latents] , dim=0 ) SCREAMING_SNAKE_CASE : Tuple = init_latents.shape SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor(lowerCamelCase_ , generator=lowerCamelCase_ , device=lowerCamelCase_ , dtype=lowerCamelCase_ ) # get latents SCREAMING_SNAKE_CASE : Dict = self.scheduler.add_noise(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = init_latents return latents def lowerCamelCase_ ( self : Union[str, Any] , lowerCamelCase_ : List[Any]=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) SCREAMING_SNAKE_CASE : Dict = torch.device(f'''cuda:{gpu_id}''' ) SCREAMING_SNAKE_CASE : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[Any] , lowerCamelCase_ : Tuple=0 ): '''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.""" ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.device(f'''cuda:{gpu_id}''' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=lowerCamelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE : Any = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = cpu_offload_with_hook(lowerCamelCase_ , lowerCamelCase_ , prev_module_hook=lowerCamelCase_ ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE : int = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase_ , """_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(lowerCamelCase_ ) def __call__( self : Dict , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] , lowerCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 5_12 , lowerCamelCase_ : int = 1_00 , lowerCamelCase_ : float = 4.0 , lowerCamelCase_ : float = 0.3 , lowerCamelCase_ : int = 1 , lowerCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase_ : Optional[str] = "pil" , lowerCamelCase_ : bool = True , ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self._execution_device SCREAMING_SNAKE_CASE : Union[str, Any] = guidance_scale > 1.0 if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : List[Any] = image_embeds.shape[0] if isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = torch.cat(lowerCamelCase_ , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE : List[str] = image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Any = negative_image_embeds.repeat_interleave(lowerCamelCase_ , dim=0 ) SCREAMING_SNAKE_CASE : Optional[int] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowerCamelCase_ ) if not isinstance(lowerCamelCase_ , lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = [image] if not all(isinstance(lowerCamelCase_ , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( f'''Input is in incorrect format: {[type(lowerCamelCase_ ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' ) SCREAMING_SNAKE_CASE : List[str] = torch.cat([prepare_image(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) for i in image] , dim=0 ) SCREAMING_SNAKE_CASE : List[str] = image.to(dtype=image_embeds.dtype , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = self.movq.encode(lowerCamelCase_ )["""latents"""] SCREAMING_SNAKE_CASE : Optional[Any] = latents.repeat_interleave(lowerCamelCase_ , dim=0 ) self.scheduler.set_timesteps(lowerCamelCase_ , device=lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_timesteps(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = downscale_height_and_width(lowerCamelCase_ , lowerCamelCase_ , self.movq_scale_factor ) SCREAMING_SNAKE_CASE : Dict = self.prepare_latents( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , image_embeds.dtype , lowerCamelCase_ , lowerCamelCase_ ) for i, t in enumerate(self.progress_bar(lowerCamelCase_ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE : Dict = {"""image_embeds""": image_embeds} SCREAMING_SNAKE_CASE : List[Any] = self.unet( sample=lowerCamelCase_ , timestep=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , added_cond_kwargs=lowerCamelCase_ , return_dict=lowerCamelCase_ , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE : List[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE : str = 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"] ): SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.step( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , generator=lowerCamelCase_ , )[0] # post-processing SCREAMING_SNAKE_CASE : Tuple = self.movq.decode(lowerCamelCase_ , force_not_quantize=lowerCamelCase_ )["""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"]: SCREAMING_SNAKE_CASE : Optional[Any] = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : Optional[Any] = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : List[str] = self.numpy_to_pil(lowerCamelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase_ )
323
'''simple docstring''' import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class UpperCamelCase__ : """simple docstring""" def __init__( self : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : str=14 , lowerCamelCase_ : Optional[Any]=7 , lowerCamelCase_ : Dict=True , lowerCamelCase_ : str=True , lowerCamelCase_ : str=False , lowerCamelCase_ : Optional[int]=True , lowerCamelCase_ : int=99 , lowerCamelCase_ : List[str]=32 , lowerCamelCase_ : int=4 , lowerCamelCase_ : List[Any]=4 , lowerCamelCase_ : List[str]=4 , lowerCamelCase_ : Union[str, Any]=37 , lowerCamelCase_ : int="gelu" , lowerCamelCase_ : List[str]=0.1 , lowerCamelCase_ : Union[str, Any]=0.1 , lowerCamelCase_ : List[str]=5_12 , lowerCamelCase_ : Union[str, Any]=0.02 , ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Optional[int] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : List[str] = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE : Union[str, Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : List[Any] = rotary_dim SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : int = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Tuple = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Dict = vocab_size - 1 SCREAMING_SNAKE_CASE : str = vocab_size - 1 SCREAMING_SNAKE_CASE : List[Any] = vocab_size - 1 def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : List[str] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=lowerCamelCase_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowerCamelCase_ ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE : Tuple = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict def lowerCamelCase_ ( self : Optional[int] , lowerCamelCase_ : str , lowerCamelCase_ : Dict , lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = 20 SCREAMING_SNAKE_CASE : Any = model_class_name(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = model.init_cache(input_ids.shape[0] , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE : Any = model( input_ids[:, :-1] , attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE : str = model( input_ids[:, -1:] , attention_mask=lowerCamelCase_ , past_key_values=outputs_cache.past_key_values , position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : int = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def lowerCamelCase_ ( self : List[Any] , lowerCamelCase_ : Tuple , lowerCamelCase_ : Any , lowerCamelCase_ : List[str] , lowerCamelCase_ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = 20 SCREAMING_SNAKE_CASE : Dict = model_class_name(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) SCREAMING_SNAKE_CASE : str = model.init_cache(input_ids.shape[0] , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE : Any = model( input_ids[:, :-1] , attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE : Dict = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=lowerCamelCase_ , position_ids=lowerCamelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) @require_flax class UpperCamelCase__ ( lowercase_ , lowercase_ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () SCREAMING_SNAKE_CASE__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowerCamelCase_ ( self : str ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxGPTJModelTester(self ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) @tooslow def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = GPTaTokenizer.from_pretrained("""gpt2""" , pad_token="""<|endoftext|>""" , padding_side="""left""" ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer(["""Hello this is a long string""", """Hey"""] , return_tensors="""np""" , padding=lowerCamelCase_ , truncation=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = FlaxGPTJForCausalLM.from_pretrained("""EleutherAI/gpt-j-6B""" ) SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Optional[Any] = model.config.eos_token_id SCREAMING_SNAKE_CASE : str = jax.jit(model.generate ) SCREAMING_SNAKE_CASE : str = jit_generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , pad_token_id=tokenizer.pad_token_id ).sequences SCREAMING_SNAKE_CASE : Tuple = tokenizer.batch_decode(lowerCamelCase_ , skip_special_tokens=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = [ """Hello this is a long string of text.\n\nI'm trying to get the text of the""", """Hey, I'm a little late to the party. I'm going to""", ] self.assertListEqual(lowerCamelCase_ , lowerCamelCase_ ) @is_pt_flax_cross_test def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE : str = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE : List[str] = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE : int = getattr(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = pt_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE : int = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Optional[int] = 1 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 1 SCREAMING_SNAKE_CASE : Optional[int] = pt_model_class(lowerCamelCase_ ).eval() SCREAMING_SNAKE_CASE : str = model_class(lowerCamelCase_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : Tuple = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Any = fx_state with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = pt_model(**lowerCamelCase_ ).to_tuple() SCREAMING_SNAKE_CASE : Any = fx_model(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = model_class.from_pretrained(lowerCamelCase_ , from_pt=lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = fx_model_loaded(**lowerCamelCase_ ).to_tuple() self.assertEqual( len(lowerCamelCase_ ) , len(lowerCamelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @is_pt_flax_cross_test def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : List[str] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE : Dict = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE : int = getattr(lowerCamelCase_ , lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Tuple = pt_model_class(lowerCamelCase_ ).eval() SCREAMING_SNAKE_CASE : Any = model_class(lowerCamelCase_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE : List[Any] = load_flax_weights_in_pytorch_model(lowerCamelCase_ , fx_model.params ) SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE : str = pt_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(lowerCamelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = 0 SCREAMING_SNAKE_CASE : Dict = 1 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Tuple = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = pt_model(**lowerCamelCase_ ).to_tuple() SCREAMING_SNAKE_CASE : Optional[Any] = fx_model(**lowerCamelCase_ ).to_tuple() self.assertEqual(len(lowerCamelCase_ ) , len(lowerCamelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE : Dict = pt_model_class.from_pretrained(lowerCamelCase_ , from_flax=lowerCamelCase_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = pt_model_loaded(**lowerCamelCase_ ).to_tuple() self.assertEqual( len(lowerCamelCase_ ) , len(lowerCamelCase_ ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @tooslow def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : Union[str, Any] = model_class_name.from_pretrained("""EleutherAI/gpt-j-6B""" ) SCREAMING_SNAKE_CASE : Optional[int] = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase_ )
323
1
"""simple docstring""" import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class _lowercase ( __UpperCAmelCase ): lowercase_ = 'MCTCTFeatureExtractor' lowercase_ = 'AutoTokenizer' def __init__( self , UpperCAmelCase_ , UpperCAmelCase_ ) -> Optional[int]: super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) lowerCamelCase : Tuple = self.feature_extractor lowerCamelCase : Optional[int] = False def __call__( self , *UpperCAmelCase_ , **UpperCAmelCase_ ) -> Dict: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*UpperCAmelCase_ , **UpperCAmelCase_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) lowerCamelCase : str = kwargs.pop('raw_speech' ) else: lowerCamelCase : Any = kwargs.pop('audio' , UpperCAmelCase_ ) lowerCamelCase : int = kwargs.pop('sampling_rate' , UpperCAmelCase_ ) lowerCamelCase : Optional[int] = kwargs.pop('text' , UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 0: lowerCamelCase : Dict = args[0] lowerCamelCase : Any = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: lowerCamelCase : Dict = self.feature_extractor(UpperCAmelCase_ , *UpperCAmelCase_ , sampling_rate=UpperCAmelCase_ , **UpperCAmelCase_ ) if text is not None: lowerCamelCase : Optional[int] = self.tokenizer(UpperCAmelCase_ , **UpperCAmelCase_ ) if text is None: return inputs elif audio is None: return encodings else: lowerCamelCase : int = encodings['input_ids'] return inputs def _UpperCamelCase ( self , *UpperCAmelCase_ , **UpperCAmelCase_ ) -> Any: return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _UpperCamelCase ( self , *UpperCAmelCase_ , **UpperCAmelCase_ ) -> Optional[int]: # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*UpperCAmelCase_ , **UpperCAmelCase_ ) lowerCamelCase : Dict = kwargs.pop('input_features' , UpperCAmelCase_ ) lowerCamelCase : List[str] = kwargs.pop('labels' , UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 0: lowerCamelCase : List[str] = args[0] lowerCamelCase : Optional[int] = args[1:] if input_features is not None: lowerCamelCase : Union[str, Any] = self.feature_extractor.pad(UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) if labels is not None: lowerCamelCase : int = self.tokenizer.pad(UpperCAmelCase_ , **UpperCAmelCase_ ) if labels is None: return input_features elif input_features is None: return labels else: lowerCamelCase : List[str] = labels['input_ids'] return input_features def _UpperCamelCase ( self , *UpperCAmelCase_ , **UpperCAmelCase_ ) -> Dict: return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @contextmanager def _UpperCamelCase ( self ) -> Dict: warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) lowerCamelCase : List[Any] = True lowerCamelCase : Dict = self.tokenizer yield lowerCamelCase : int = self.feature_extractor lowerCamelCase : List[Any] = False
205
"""simple docstring""" def UpperCAmelCase ( a_ = 10 ): '''simple docstring''' if not isinstance(a_, a_ ) or n < 0: raise ValueError('Invalid input' ) lowerCamelCase : Union[str, Any] = 10**n lowerCamelCase : int = 2_8433 * (pow(2, 783_0457, a_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"""{solution(1_0) = }""")
205
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer A: List[str] = logging.get_logger(__name__) # pylint: disable=invalid-name A: List[str] = "\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : Union[PIL.Image.Image, np.ndarray] class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Optional[Any]: '''simple docstring''' super().__init__() self.register_modules( prior=_SCREAMING_SNAKE_CASE , image_encoder=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , renderer=_SCREAMING_SNAKE_CASE , ) def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' if latents is None: UpperCAmelCase : Union[str, Any] = 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}" ) UpperCAmelCase : List[str] = latents.to(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Any = latents * scheduler.init_noise_sigma return latents def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE=0 ) -> List[str]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) UpperCAmelCase : List[str] = torch.device(F"cuda:{gpu_id}" ) UpperCAmelCase : Optional[Any] = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @property def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' if self.device != torch.device("""meta""" ) or not hasattr(self.image_encoder , """_hf_hook""" ): return self.device for module in self.image_encoder.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 def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> Any: '''simple docstring''' if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and isinstance(image[0] , torch.Tensor ): UpperCAmelCase : Dict = torch.cat(_SCREAMING_SNAKE_CASE , axis=0 ) if image[0].ndim == 4 else torch.stack(_SCREAMING_SNAKE_CASE , axis=0 ) if not isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): UpperCAmelCase : Any = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values[0].unsqueeze(0 ) UpperCAmelCase : Optional[Any] = image.to(dtype=self.image_encoder.dtype , device=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : str = self.image_encoder(_SCREAMING_SNAKE_CASE )["""last_hidden_state"""] UpperCAmelCase : int = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 UpperCAmelCase : Optional[Any] = image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE , dim=0 ) if do_classifier_free_guidance: UpperCAmelCase : Tuple = torch.zeros_like(_SCREAMING_SNAKE_CASE ) # 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([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1 , _SCREAMING_SNAKE_CASE = 25 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 4.0 , _SCREAMING_SNAKE_CASE = 64 , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ) -> Optional[Any]: '''simple docstring''' if isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): UpperCAmelCase : List[str] = 1 elif isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): UpperCAmelCase : str = image.shape[0] elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): UpperCAmelCase : Optional[int] = len(_SCREAMING_SNAKE_CASE ) else: raise ValueError( F"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_SCREAMING_SNAKE_CASE )}" ) UpperCAmelCase : str = self._execution_device UpperCAmelCase : List[Any] = batch_size * num_images_per_prompt UpperCAmelCase : List[Any] = guidance_scale > 1.0 UpperCAmelCase : Dict = self._encode_image(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # prior self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : str = self.scheduler.timesteps UpperCAmelCase : Optional[int] = self.prior.config.num_embeddings UpperCAmelCase : int = self.prior.config.embedding_dim UpperCAmelCase : Tuple = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim UpperCAmelCase : List[Any] = latents.reshape(latents.shape[0] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE ) ): # expand the latents if we are doing classifier free guidance UpperCAmelCase : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCAmelCase : Optional[Any] = self.scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[str] = self.prior( _SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , proj_embedding=_SCREAMING_SNAKE_CASE , ).predicted_image_embedding # remove the variance UpperCAmelCase , UpperCAmelCase : Dict = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: UpperCAmelCase , UpperCAmelCase : Dict = noise_pred.chunk(2 ) UpperCAmelCase : Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) UpperCAmelCase : Optional[Any] = self.scheduler.step( _SCREAMING_SNAKE_CASE , timestep=_SCREAMING_SNAKE_CASE , sample=_SCREAMING_SNAKE_CASE , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[Any] = [] for i, latent in enumerate(_SCREAMING_SNAKE_CASE ): print() UpperCAmelCase : int = self.renderer.decode( latent[None, :] , _SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : Any = torch.stack(_SCREAMING_SNAKE_CASE ) if output_type not in ["np", "pil"]: raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}" ) UpperCAmelCase : List[Any] = images.cpu().numpy() if output_type == "pil": UpperCAmelCase : Tuple = [self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_SCREAMING_SNAKE_CASE )
109
'''simple docstring''' UpperCAmelCase_ : Dict = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] UpperCAmelCase_ : Any = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] UpperCAmelCase_ : Tuple = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] UpperCAmelCase_ : Dict = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] UpperCAmelCase_ : Tuple = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] UpperCAmelCase_ : Union[str, Any] = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] UpperCAmelCase_ : Tuple = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] UpperCAmelCase_ : int = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
200
0
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : Tuple = GPTSanJapaneseTokenizer _snake_case : List[Any] = False _snake_case : List[Any] = {"""do_clean_text""": False, """add_prefix_space""": False} def a__ ( self ): super().setUp() # fmt: off __a = ["こん", "こんに", "にちは", "ばんは", "世界,㔺界", "、", "。", "<BR>", "<SP>", "<TAB>", "<URL>", "<EMAIL>", "<TEL>", "<DATE>", "<PRICE>", "<BLOCK>", "<KIGOU>", "<U2000U2BFF>", "<|emoji1|>", "<unk>", "<|bagoftoken|>", "<|endoftext|>"] # fmt: on __a = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀 __a = {"unk_token": "<unk>"} __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["emoji_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.emoji_file , "w" ) as emoji_writer: emoji_writer.write(json.dumps(_lowercase ) ) def a__ ( self , **lowerCamelCase ): kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **_lowercase ) def a__ ( self , lowerCamelCase ): __a = "こんにちは、世界。 \nこんばんは、㔺界。😀" __a = "こんにちは、世界。 \nこんばんは、世界。😀" return input_text, output_text def a__ ( self , lowerCamelCase ): __a , __a = self.get_input_output_texts(_lowercase ) __a = tokenizer.encode(_lowercase , add_special_tokens=_lowercase ) __a = tokenizer.decode(_lowercase , clean_up_tokenization_spaces=_lowercase ) return text, ids def a__ ( self ): pass # TODO add if relevant def a__ ( self ): pass # TODO add if relevant def a__ ( self ): pass # TODO add if relevant def a__ ( self ): __a = self.get_tokenizer() # Testing tokenization __a = "こんにちは、世界。 こんばんは、㔺界。" __a = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"] __a = tokenizer.tokenize(_lowercase ) self.assertListEqual(_lowercase , _lowercase ) # Testing conversion to ids without special tokens __a = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] __a = tokenizer.convert_tokens_to_ids(_lowercase ) self.assertListEqual(_lowercase , _lowercase ) # Testing conversion to ids with special tokens __a = tokens + [tokenizer.unk_token] __a = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] __a = tokenizer.convert_tokens_to_ids(_lowercase ) self.assertListEqual(_lowercase , _lowercase ) def a__ ( self ): __a = self.get_tokenizer() # Testing tokenization __a = "こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。" __a = "こんにちは、、、、世界。こんばんは、、、、世界。" __a = tokenizer.encode(_lowercase ) __a = tokenizer.decode(_lowercase ) self.assertEqual(_lowercase , _lowercase ) @slow def a__ ( self ): __a = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization __a = "こんにちは、世界。" __a = "こんばんは、㔺界。😀" __a = "こんにちは、世界。こんばんは、世界。😀" __a = tokenizer.encode(prefix_text + input_text ) __a = tokenizer.encode("" , prefix_text=prefix_text + input_text ) __a = tokenizer.encode(_lowercase , prefix_text=_lowercase ) __a = tokenizer.decode(_lowercase ) __a = tokenizer.decode(_lowercase ) __a = tokenizer.decode(_lowercase ) self.assertEqual(_lowercase , _lowercase ) self.assertEqual(_lowercase , _lowercase ) self.assertEqual(_lowercase , _lowercase ) @slow def a__ ( self ): __a = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) # Testing tokenization __a = "こんにちは、世界。" __a = "こんばんは、㔺界。😀" __a = len(tokenizer.encode(_lowercase ) ) - 2 __a = len(tokenizer.encode(_lowercase ) ) - 2 __a = [1] + [0] * (len_prefix + len_text + 1) __a = [1] * (len_prefix + len_text + 1) + [0] __a = [1] + [1] * (len_prefix) + [0] * (len_text + 1) __a = tokenizer(prefix_text + input_text ).token_type_ids __a = tokenizer("" , prefix_text=prefix_text + input_text ).token_type_ids __a = tokenizer(_lowercase , prefix_text=_lowercase ).token_type_ids self.assertListEqual(_lowercase , _lowercase ) self.assertListEqual(_lowercase , _lowercase ) self.assertListEqual(_lowercase , _lowercase ) @slow def a__ ( self ): __a = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) __a = tokenizer.encode("あンいワ" ) __a = tokenizer.encode("" , prefix_text="あンいワ" ) __a = tokenizer.encode("いワ" , prefix_text="あン" ) self.assertEqual(tokenizer.decode(_lowercase ) , tokenizer.decode(_lowercase ) ) self.assertEqual(tokenizer.decode(_lowercase ) , tokenizer.decode(_lowercase ) ) self.assertNotEqual(_lowercase , _lowercase ) self.assertNotEqual(_lowercase , _lowercase ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def a__ ( self ): __a = self.tokenizer_class.from_pretrained("Tanrei/GPTSAN-japanese" ) __a = [["武田信玄", "は、"], ["織田信長", "の配下の、"]] __a = tokenizer(_lowercase , padding=_lowercase ) __a = tokenizer.batch_encode_plus(_lowercase , padding=_lowercase ) # fmt: off __a = [[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] __a = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] __a = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , _lowercase ) self.assertListEqual(x_token.token_type_ids , _lowercase ) self.assertListEqual(x_token.attention_mask , _lowercase ) self.assertListEqual(x_token_a.input_ids , _lowercase ) self.assertListEqual(x_token_a.token_type_ids , _lowercase ) self.assertListEqual(x_token_a.attention_mask , _lowercase ) def a__ ( self ): # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def a__ ( self ): # tokenizer has no padding token pass
366
"""simple docstring""" import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE__:Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:List[Any] = {"""vocab_file""": """vocab.txt"""} SCREAMING_SNAKE_CASE__:Optional[int] = { """vocab_file""": { """openbmb/cpm-ant-10b""": """https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt""", }, } SCREAMING_SNAKE_CASE__:Tuple = { """openbmb/cpm-ant-10b""": 1024, } def _lowerCamelCase( a ): __a = collections.OrderedDict() with open(a , "r" , encoding="utf-8" ) as reader: __a = reader.readlines() for index, token in enumerate(a ): __a = token.rstrip("\n" ) __a = index return vocab class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase , lowerCamelCase="<unk>" , lowerCamelCase=200 ): __a = vocab __a = unk_token __a = max_input_chars_per_word def a__ ( self , lowerCamelCase ): __a = list(lowerCamelCase ) if len(lowerCamelCase ) > self.max_input_chars_per_word: return [self.unk_token] __a = 0 __a = [] while start < len(lowerCamelCase ): __a = len(lowerCamelCase ) __a = None while start < end: __a = "".join(chars[start:end] ) if substr in self.vocab: __a = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(lowerCamelCase ) __a = end return sub_tokens class snake_case__ ( snake_case_ ): _snake_case : Optional[int] = VOCAB_FILES_NAMES _snake_case : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : int = ["""input_ids""", """attention_mask"""] _snake_case : int = False def __init__( self , lowerCamelCase , lowerCamelCase="<d>" , lowerCamelCase="</d>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase="<unk>" , lowerCamelCase="</n>" , lowerCamelCase="</_>" , lowerCamelCase="left" , **lowerCamelCase , ): requires_backends(self , ["jieba"] ) super().__init__( bod_token=lowerCamelCase , eod_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , unk_token=lowerCamelCase , line_token=lowerCamelCase , space_token=lowerCamelCase , padding_side=lowerCamelCase , **lowerCamelCase , ) __a = bod_token __a = eod_token __a = load_vocab(lowerCamelCase ) __a = self.encoder[space_token] __a = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] __a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda lowerCamelCase : x[1] ) ) __a = {v: k for k, v in self.encoder.items()} __a = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def a__ ( self ): return self.encoder[self.bod_token] @property def a__ ( self ): return self.encoder[self.eod_token] @property def a__ ( self ): return self.encoder["\n"] @property def a__ ( self ): return len(self.encoder ) def a__ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def a__ ( self , lowerCamelCase ): __a = [] for x in jieba.cut(lowerCamelCase , cut_all=lowerCamelCase ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(lowerCamelCase ) ) return output_tokens def a__ ( self , lowerCamelCase , **lowerCamelCase ): __a = [i for i in token_ids if i >= 0] __a = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase ): return token in self.encoder def a__ ( self , lowerCamelCase ): return "".join(lowerCamelCase ) def a__ ( self , lowerCamelCase ): return self.encoder.get(lowerCamelCase , self.encoder.get(self.unk_token ) ) def a__ ( self , lowerCamelCase ): return self.decoder.get(lowerCamelCase , self.unk_token ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): if os.path.isdir(lowerCamelCase ): __a = os.path.join( lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) else: __a = (filename_prefix + "-" if filename_prefix else "") + save_directory __a = 0 if " " in self.encoder: __a = self.encoder[" "] del self.encoder[" "] if "\n" in self.encoder: __a = self.encoder["\n"] del self.encoder["\n"] __a = collections.OrderedDict(sorted(self.encoder.items() , key=lambda lowerCamelCase : x[1] ) ) with open(lowerCamelCase , "w" , encoding="utf-8" ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive." " Please check that the vocabulary is not corrupted!" ) __a = token_index writer.write(token + "\n" ) index += 1 return (vocab_file,) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCamelCase , token_ids_a=lowerCamelCase , already_has_special_tokens=lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(lowerCamelCase )) + [1] + ([0] * len(lowerCamelCase )) return [1] + ([0] * len(lowerCamelCase ))
268
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''salesforce/blip2-opt-2.7b''': '''https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json''', } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Tuple = 'blip_2_vision_model' def __init__( self : List[Any] ,_UpperCAmelCase : List[Any]=1408 ,_UpperCAmelCase : Optional[int]=6144 ,_UpperCAmelCase : List[str]=39 ,_UpperCAmelCase : Dict=16 ,_UpperCAmelCase : Optional[Any]=224 ,_UpperCAmelCase : Any=14 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[int]=0.0_00_01 ,_UpperCAmelCase : Tuple=0.0 ,_UpperCAmelCase : Union[str, Any]=1E-10 ,_UpperCAmelCase : Any=True ,**_UpperCAmelCase : Dict ,): super().__init__(**_UpperCAmelCase ) _a : int = hidden_size _a : List[str] = intermediate_size _a : List[Any] = num_hidden_layers _a : Optional[int] = num_attention_heads _a : Tuple = patch_size _a : List[str] = image_size _a : int = initializer_range _a : Union[str, Any] = attention_dropout _a : Union[str, Any] = layer_norm_eps _a : List[str] = hidden_act _a : Any = qkv_bias @classmethod def __lowercase ( cls : Tuple ,_UpperCAmelCase : Union[str, os.PathLike] ,**_UpperCAmelCase : Any ): cls._set_token_in_kwargs(_UpperCAmelCase ) _a , _a : List[Any] = cls.get_config_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": _a : Union[str, Any] = 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(_UpperCAmelCase ,**_UpperCAmelCase ) class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Tuple = 'blip_2_qformer' def __init__( self : int ,_UpperCAmelCase : List[str]=30522 ,_UpperCAmelCase : Dict=768 ,_UpperCAmelCase : Tuple=12 ,_UpperCAmelCase : Any=12 ,_UpperCAmelCase : int=3072 ,_UpperCAmelCase : str="gelu" ,_UpperCAmelCase : Dict=0.1 ,_UpperCAmelCase : str=0.1 ,_UpperCAmelCase : int=512 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1E-12 ,_UpperCAmelCase : int=0 ,_UpperCAmelCase : Optional[int]="absolute" ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Any=1408 ,**_UpperCAmelCase : Optional[int] ,): super().__init__(pad_token_id=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Any = vocab_size _a : Optional[int] = hidden_size _a : Dict = num_hidden_layers _a : Dict = num_attention_heads _a : str = hidden_act _a : Any = intermediate_size _a : Dict = hidden_dropout_prob _a : str = attention_probs_dropout_prob _a : Union[str, Any] = max_position_embeddings _a : Tuple = initializer_range _a : Optional[int] = layer_norm_eps _a : int = position_embedding_type _a : Optional[Any] = cross_attention_frequency _a : List[str] = encoder_hidden_size @classmethod def __lowercase ( cls : Dict ,_UpperCAmelCase : Union[str, os.PathLike] ,**_UpperCAmelCase : Union[str, Any] ): cls._set_token_in_kwargs(_UpperCAmelCase ) _a , _a : str = cls.get_config_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": _a : Any = config_dict['qformer_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(_UpperCAmelCase ,**_UpperCAmelCase ) class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Tuple = 'blip-2' lowerCAmelCase : Any = True def __init__( self : Any ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : int=32 ,**_UpperCAmelCase : str ): super().__init__(**_UpperCAmelCase ) if vision_config is None: _a : str = {} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: _a : List[str] = {} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: _a : List[Any] = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) _a : Optional[Any] = BlipaVisionConfig(**_UpperCAmelCase ) _a : Tuple = BlipaQFormerConfig(**_UpperCAmelCase ) _a : Optional[int] = text_config['model_type'] if 'model_type' in text_config else 'opt' _a : Any = CONFIG_MAPPING[text_model_type](**_UpperCAmelCase ) _a : Dict = self.text_config.tie_word_embeddings _a : Union[str, Any] = self.text_config.is_encoder_decoder _a : int = num_query_tokens _a : str = self.vision_config.hidden_size _a : Optional[Any] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES _a : Optional[int] = 1.0 _a : str = 0.02 @classmethod def __lowercase ( cls : str ,_UpperCAmelCase : BlipaVisionConfig ,_UpperCAmelCase : BlipaQFormerConfig ,_UpperCAmelCase : PretrainedConfig ,**_UpperCAmelCase : List[Any] ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**_UpperCAmelCase ,) def __lowercase ( self : int ): _a : Dict = copy.deepcopy(self.__dict__ ) _a : Any = self.vision_config.to_dict() _a : Optional[int] = self.qformer_config.to_dict() _a : Dict = self.text_config.to_dict() _a : Optional[Any] = self.__class__.model_type return output
89
import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, ByTaTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): snake_case_ : Optional[Any] = "pt" elif is_tf_available(): snake_case_ : Union[str, Any] = "tf" else: snake_case_ : str = "jax" class __snake_case ( a , unittest.TestCase ): UpperCAmelCase__ : List[Any] = ByTaTokenizer UpperCAmelCase__ : int = False def lowerCamelCase ( self : Optional[int]): """simple docstring""" super().setUp() UpperCAmelCase_ = ByTaTokenizer() tokenizer.save_pretrained(self.tmpdirname) @cached_property def lowerCamelCase ( self : Tuple): """simple docstring""" return ByTaTokenizer.from_pretrained('''google/byt5-small''') def lowerCamelCase ( self : List[str] , **_snake_case : Union[str, Any]): """simple docstring""" return self.tokenizer_class.from_pretrained(self.tmpdirname , **_snake_case) def lowerCamelCase ( self : Dict , _snake_case : int , _snake_case : Tuple=False , _snake_case : Dict=20 , _snake_case : Optional[Any]=5): """simple docstring""" UpperCAmelCase_ = [] for i in range(len(_snake_case)): try: UpperCAmelCase_ = tokenizer.decode([i] , clean_up_tokenization_spaces=_snake_case) except UnicodeDecodeError: pass toks.append((i, tok)) UpperCAmelCase_ = list(filter(lambda _snake_case: re.match(r'''^[ a-zA-Z]+$''' , t[1]) , _snake_case)) UpperCAmelCase_ = list(filter(lambda _snake_case: [t[0]] == tokenizer.encode(t[1] , add_special_tokens=_snake_case) , _snake_case)) if max_length is not None and len(_snake_case) > max_length: UpperCAmelCase_ = toks[:max_length] if min_length is not None and len(_snake_case) < min_length and len(_snake_case) > 0: while len(_snake_case) < min_length: UpperCAmelCase_ = toks + toks # toks_str = [t[1] for t in toks] UpperCAmelCase_ = [t[0] for t in toks] # Ensure consistency UpperCAmelCase_ = tokenizer.decode(_snake_case , clean_up_tokenization_spaces=_snake_case) if " " not in output_txt and len(_snake_case) > 1: UpperCAmelCase_ = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=_snake_case) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=_snake_case) ) if with_prefix_space: UpperCAmelCase_ = ''' ''' + output_txt UpperCAmelCase_ = tokenizer.encode(_snake_case , add_special_tokens=_snake_case) return output_txt, output_ids def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = tokenizer(['''hi</s>''', '''I went to the gym</s>''', '''</s>''']) UpperCAmelCase_ = tokenizer(['''hi''', '''I went to the gym''', '''''']) self.assertListEqual(batch_with_eos_added['''input_ids'''] , batch_without_eos_added['''input_ids''']) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = '''Unicode €.''' UpperCAmelCase_ = tokenizer(_snake_case) UpperCAmelCase_ = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1] self.assertEqual(encoded['''input_ids'''] , _snake_case) # decoding UpperCAmelCase_ = tokenizer.decode(_snake_case) self.assertEqual(_snake_case , '''Unicode €.</s>''') UpperCAmelCase_ = tokenizer('''e è é ê ë''') UpperCAmelCase_ = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1] self.assertEqual(encoded['''input_ids'''] , _snake_case) # decoding UpperCAmelCase_ = tokenizer.decode(_snake_case) self.assertEqual(_snake_case , '''e è é ê ë</s>''') # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''')) , '''e è é ê ë</s>''') def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off UpperCAmelCase_ = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: on UpperCAmelCase_ = tokenizer(_snake_case , padding=_snake_case , return_tensors=_snake_case) self.assertIsInstance(_snake_case , _snake_case) if FRAMEWORK != "jax": UpperCAmelCase_ = list(batch.input_ids.numpy()[0]) else: UpperCAmelCase_ = list(batch.input_ids.tolist()[0]) self.assertListEqual(_snake_case , _snake_case) self.assertEqual((2, 37) , batch.input_ids.shape) self.assertEqual((2, 37) , batch.attention_mask.shape) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] UpperCAmelCase_ = tokenizer(_snake_case , padding=_snake_case , return_tensors=_snake_case) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , _snake_case) self.assertIn('''attention_mask''' , _snake_case) self.assertNotIn('''decoder_input_ids''' , _snake_case) self.assertNotIn('''decoder_attention_mask''' , _snake_case) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = [ '''Summary of the text.''', '''Another summary.''', ] UpperCAmelCase_ = tokenizer( text_target=_snake_case , max_length=32 , padding='''max_length''' , truncation=_snake_case , return_tensors=_snake_case) self.assertEqual(32 , targets['''input_ids'''].shape[1]) def lowerCamelCase ( self : int): """simple docstring""" UpperCAmelCase_ = self.ta_base_tokenizer UpperCAmelCase_ = ['''A long paragraph for summarization. </s>'''] UpperCAmelCase_ = ['''Summary of the text. </s>'''] # fmt: off UpperCAmelCase_ = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] UpperCAmelCase_ = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: on UpperCAmelCase_ = tokenizer(_snake_case , text_target=_snake_case) self.assertEqual(_snake_case , batch['''input_ids'''][0]) self.assertEqual(_snake_case , batch['''labels'''][0]) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): self.assertNotEqual(tokenizer.model_max_length , 42) # Now let's start the test UpperCAmelCase_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = ''' He is very happy, UNwant\u00E9d,running''' UpperCAmelCase_ = tokenizer.encode(_snake_case , add_special_tokens=_snake_case) tokenizer.save_pretrained(_snake_case) UpperCAmelCase_ = tokenizer.__class__.from_pretrained(_snake_case) UpperCAmelCase_ = after_tokenizer.encode(_snake_case , add_special_tokens=_snake_case) self.assertListEqual(_snake_case , _snake_case) shutil.rmtree(_snake_case) UpperCAmelCase_ = self.get_tokenizers(model_max_length=42) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam''']) UpperCAmelCase_ = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''') tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens}) UpperCAmelCase_ = tokenizer.encode(_snake_case , add_special_tokens=_snake_case) tokenizer.save_pretrained(_snake_case) UpperCAmelCase_ = tokenizer.__class__.from_pretrained(_snake_case) UpperCAmelCase_ = after_tokenizer.encode(_snake_case , add_special_tokens=_snake_case) self.assertListEqual(_snake_case , _snake_case) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens) self.assertEqual(after_tokenizer.model_max_length , 42) UpperCAmelCase_ = tokenizer.__class__.from_pretrained(_snake_case , model_max_length=43) self.assertEqual(tokenizer.model_max_length , 43) shutil.rmtree(_snake_case) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_snake_case) with open(os.path.join(_snake_case , '''special_tokens_map.json''') , encoding='''utf-8''') as json_file: UpperCAmelCase_ = json.load(_snake_case) with open(os.path.join(_snake_case , '''tokenizer_config.json''') , encoding='''utf-8''') as json_file: UpperCAmelCase_ = json.load(_snake_case) UpperCAmelCase_ = [F"""<extra_id_{i}>""" for i in range(125)] UpperCAmelCase_ = added_tokens_extra_ids + [ '''an_additional_special_token''' ] UpperCAmelCase_ = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(_snake_case , '''special_tokens_map.json''') , '''w''' , encoding='''utf-8''') as outfile: json.dump(_snake_case , _snake_case) with open(os.path.join(_snake_case , '''tokenizer_config.json''') , '''w''' , encoding='''utf-8''') as outfile: json.dump(_snake_case , _snake_case) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files UpperCAmelCase_ = tokenizer_class.from_pretrained( _snake_case , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''])) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained UpperCAmelCase_ = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=_snake_case)] UpperCAmelCase_ = tokenizer_class.from_pretrained( _snake_case , additional_special_tokens=_snake_case , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''])) , ) def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(_snake_case) UpperCAmelCase_ = tokenizer_class.from_pretrained(_snake_case) self.assertTrue(tokenizer.decode([255]) == '''''') def lowerCamelCase ( self : int): """simple docstring""" pass def lowerCamelCase ( self : Optional[int]): """simple docstring""" pass def lowerCamelCase ( self : Dict): """simple docstring""" pass def lowerCamelCase ( self : List[Any]): """simple docstring""" pass def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = self.get_tokenizers(fast=_snake_case , do_lower_case=_snake_case) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): UpperCAmelCase_ = ['''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''x''', '''t''', '''</s>'''] UpperCAmelCase_ = tokenizer.convert_tokens_to_string(_snake_case) self.assertIsInstance(_snake_case , _snake_case) def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}"""): UpperCAmelCase_ = [ '''bos_token''', '''eos_token''', '''unk_token''', '''sep_token''', '''pad_token''', '''cls_token''', '''mask_token''', ] UpperCAmelCase_ = 0 UpperCAmelCase_ = tokenizer.convert_ids_to_tokens( _snake_case , skip_special_tokens=_snake_case) for attr in attributes_list: setattr(_snake_case , attr + '''_id''' , _snake_case) self.assertEqual(getattr(_snake_case , _snake_case) , _snake_case) self.assertEqual(getattr(_snake_case , attr + '''_id''') , _snake_case) setattr(_snake_case , attr + '''_id''' , _snake_case) self.assertEqual(getattr(_snake_case , _snake_case) , _snake_case) self.assertEqual(getattr(_snake_case , attr + '''_id''') , _snake_case) setattr(_snake_case , '''additional_special_tokens_ids''' , []) self.assertListEqual(getattr(_snake_case , '''additional_special_tokens''') , []) self.assertListEqual(getattr(_snake_case , '''additional_special_tokens_ids''') , []) setattr(_snake_case , '''additional_special_tokens_ids''' , [token_id_to_test_setters]) self.assertListEqual(getattr(_snake_case , '''additional_special_tokens''') , [token_to_test_setters]) self.assertListEqual(getattr(_snake_case , '''additional_special_tokens_ids''') , [token_id_to_test_setters])
51
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=_a ) class A_ ( _a ): lowerCAmelCase__ = field(default='image-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) lowerCAmelCase__ = Features({'image': Image()} ) lowerCAmelCase__ = Features({'labels': ClassLabel} ) lowerCAmelCase__ = "image" lowerCAmelCase__ = "labels" def _lowercase ( self: Optional[Any] ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' if self.label_column not in features: raise ValueError(F"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] ,__lowerCAmelCase ): raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""" ) _lowerCamelCase : Any = copy.deepcopy(self ) _lowerCamelCase : Optional[Any] = self.label_schema.copy() _lowerCamelCase : int = features[self.label_column] _lowerCamelCase : Optional[int] = label_schema return task_template @property def _lowercase ( self: Any ): '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
340
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase_( _lowerCamelCase ) -> Tuple: '''simple docstring''' _lowerCamelCase : Optional[int] = {} _lowerCamelCase : Optional[int] = tokenizer(example["content"] , truncation=_lowerCamelCase )["input_ids"] _lowerCamelCase : Dict = len(example["content"] ) / len(output["input_ids"] ) return output _lowerCAmelCase : Tuple = HfArgumentParser(PretokenizationArguments) _lowerCAmelCase : Optional[int] = parser.parse_args() if args.num_workers is None: _lowerCAmelCase : Any = multiprocessing.cpu_count() _lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained(args.tokenizer_dir) _lowerCAmelCase : Union[str, Any] = time.time() _lowerCAmelCase : Optional[int] = load_dataset(args.dataset_name, split='''train''') print(f'''Dataset loaded in {time.time()-t_start:.2f}s''') _lowerCAmelCase : Any = time.time() _lowerCAmelCase : Dict = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ '''repo_name''', '''path''', '''copies''', '''size''', '''content''', '''license''', '''hash''', '''line_mean''', '''line_max''', '''alpha_frac''', '''autogenerated''', ], ) print(f'''Dataset tokenized in {time.time()-t_start:.2f}s''') _lowerCAmelCase : str = time.time() ds.push_to_hub(args.tokenized_data_repo) print(f'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
340
1
'''simple docstring''' from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCAmelCase__ : lowerCAmelCase : Optional[Any] = 42 lowerCAmelCase : List[str] = 42 class lowerCAmelCase__ : def __init__( self : Dict , lowerCamelCase__ : Any ) ->Optional[int]: '''simple docstring''' _UpperCAmelCase : list[list[Edge]] = [[] for _ in range(lowerCamelCase__ )] _UpperCAmelCase : List[str] = size def __getitem__( self : Tuple , lowerCamelCase__ : List[Any] ) ->Iterator[Edge]: '''simple docstring''' return iter(self._graph[vertex] ) @property def lowerCAmelCase__ ( self : List[str] ) ->List[Any]: '''simple docstring''' return self._size def lowerCAmelCase__ ( self : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Dict , lowerCamelCase__ : int ) ->Optional[int]: '''simple docstring''' if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(lowerCamelCase__ , lowerCamelCase__ ) ) def lowerCAmelCase__ ( self : Tuple , lowerCamelCase__ : List[str] , lowerCamelCase__ : Dict ) ->int | None: '''simple docstring''' _UpperCAmelCase : List[Any] = deque([start_vertex] ) _UpperCAmelCase : list[int | None] = [None] * self.size _UpperCAmelCase : List[Any] = 0 while queue: _UpperCAmelCase : str = queue.popleft() _UpperCAmelCase : Union[str, Any] = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: _UpperCAmelCase : Any = current_distance + edge.weight _UpperCAmelCase : Dict = distances[edge.destination_vertex] if ( isinstance(lowerCamelCase__ , lowerCamelCase__ ) and new_distance >= dest_vertex_distance ): continue _UpperCAmelCase : Optional[Any] = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
234
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. a : Tuple = {"""LayoutLMv2Config""", """LayoutLMv3Config"""} @is_pipeline_test class UpperCamelCase_ ( unittest.TestCase ): lowercase = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowercase = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowercase = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def _lowercase( self , A , A , A ) -> Dict: UpperCAmelCase : Union[str, Any] = ZeroShotClassificationPipeline( model=A , tokenizer=A , candidate_labels=["""polics""", """health"""] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def _lowercase( self , A , A ) -> Optional[int]: UpperCAmelCase : Dict = classifier("""Who are you voting for in 2020?""" , candidate_labels="""politics""" ) self.assertEqual(A , {"""sequence""": ANY(A ), """labels""": [ANY(A )], """scores""": [ANY(A )]} ) # No kwarg UpperCAmelCase : Optional[int] = classifier("""Who are you voting for in 2020?""" , ["""politics"""] ) self.assertEqual(A , {"""sequence""": ANY(A ), """labels""": [ANY(A )], """scores""": [ANY(A )]} ) UpperCAmelCase : str = classifier("""Who are you voting for in 2020?""" , candidate_labels=["""politics"""] ) self.assertEqual(A , {"""sequence""": ANY(A ), """labels""": [ANY(A )], """scores""": [ANY(A )]} ) UpperCAmelCase : List[Any] = classifier("""Who are you voting for in 2020?""" , candidate_labels="""politics, public health""" ) self.assertEqual( A , {"""sequence""": ANY(A ), """labels""": [ANY(A ), ANY(A )], """scores""": [ANY(A ), ANY(A )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ) , 1.0 ) UpperCAmelCase : Optional[int] = classifier("""Who are you voting for in 2020?""" , candidate_labels=["""politics""", """public health"""] ) self.assertEqual( A , {"""sequence""": ANY(A ), """labels""": [ANY(A ), ANY(A )], """scores""": [ANY(A ), ANY(A )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["""scores"""] ) ) , 1.0 ) UpperCAmelCase : Dict = classifier( """Who are you voting for in 2020?""" , candidate_labels="""politics""" , hypothesis_template="""This text is about {}""" ) self.assertEqual(A , {"""sequence""": ANY(A ), """labels""": [ANY(A )], """scores""": [ANY(A )]} ) # https://github.com/huggingface/transformers/issues/13846 UpperCAmelCase : str = classifier(["""I am happy"""] , ["""positive""", """negative"""] ) self.assertEqual( A , [ {"""sequence""": ANY(A ), """labels""": [ANY(A ), ANY(A )], """scores""": [ANY(A ), ANY(A )]} for i in range(1 ) ] , ) UpperCAmelCase : List[str] = classifier(["""I am happy""", """I am sad"""] , ["""positive""", """negative"""] ) self.assertEqual( A , [ {"""sequence""": ANY(A ), """labels""": [ANY(A ), ANY(A )], """scores""": [ANY(A ), ANY(A )]} for i in range(2 ) ] , ) with self.assertRaises(A ): classifier("""""" , candidate_labels="""politics""" ) with self.assertRaises(A ): classifier(A , candidate_labels="""politics""" ) with self.assertRaises(A ): classifier("""Who are you voting for in 2020?""" , candidate_labels="""""" ) with self.assertRaises(A ): classifier("""Who are you voting for in 2020?""" , candidate_labels=A ) with self.assertRaises(A ): classifier( """Who are you voting for in 2020?""" , candidate_labels="""politics""" , hypothesis_template="""Not formatting template""" , ) with self.assertRaises(A ): classifier( """Who are you voting for in 2020?""" , candidate_labels="""politics""" , hypothesis_template=A , ) self.run_entailment_id(A ) def _lowercase( self , A ) -> Any: UpperCAmelCase : Tuple = zero_shot_classifier.model.config UpperCAmelCase : Union[str, Any] = config.labelaid UpperCAmelCase : Tuple = zero_shot_classifier.entailment_id UpperCAmelCase : Any = {"""LABEL_0""": 0, """LABEL_1""": 1, """LABEL_2""": 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) UpperCAmelCase : Optional[Any] = {"""entailment""": 0, """neutral""": 1, """contradiction""": 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) UpperCAmelCase : Any = {"""ENTAIL""": 0, """NON-ENTAIL""": 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) UpperCAmelCase : List[str] = {"""ENTAIL""": 2, """NEUTRAL""": 1, """CONTR""": 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) UpperCAmelCase : Tuple = original_labelaid self.assertEqual(A , zero_shot_classifier.entailment_id ) @require_torch def _lowercase( self ) -> str: UpperCAmelCase : int = pipeline( """zero-shot-classification""" , model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""" , framework="""pt""" , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( """Who are you voting for in 2020?""" * 100 , candidate_labels=["""politics""", """public health""", """science"""] ) @require_torch def _lowercase( self ) -> Union[str, Any]: UpperCAmelCase : Optional[int] = pipeline( """zero-shot-classification""" , model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""" , framework="""pt""" , ) UpperCAmelCase : Union[str, Any] = zero_shot_classifier( """Who are you voting for in 2020?""" , candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(A ) , { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @require_tf def _lowercase( self ) -> Optional[int]: UpperCAmelCase : Optional[Any] = pipeline( """zero-shot-classification""" , model="""sshleifer/tiny-distilbert-base-cased-distilled-squad""" , framework="""tf""" , ) UpperCAmelCase : List[Any] = zero_shot_classifier( """Who are you voting for in 2020?""" , candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(A ) , { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""science""", """public health""", """politics"""], """scores""": [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @slow @require_torch def _lowercase( self ) -> List[str]: UpperCAmelCase : Optional[int] = pipeline("""zero-shot-classification""" , model="""roberta-large-mnli""" , framework="""pt""" ) UpperCAmelCase : Optional[int] = zero_shot_classifier( """Who are you voting for in 2020?""" , candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(A ) , { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) UpperCAmelCase : str = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""" , candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""] , multi_label=A , ) self.assertEqual( nested_simplify(A ) , { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , ) @slow @require_tf def _lowercase( self ) -> List[str]: UpperCAmelCase : int = pipeline("""zero-shot-classification""" , model="""roberta-large-mnli""" , framework="""tf""" ) UpperCAmelCase : Tuple = zero_shot_classifier( """Who are you voting for in 2020?""" , candidate_labels=["""politics""", """public health""", """science"""] ) self.assertEqual( nested_simplify(A ) , { """sequence""": """Who are you voting for in 2020?""", """labels""": ["""politics""", """public health""", """science"""], """scores""": [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) UpperCAmelCase : Any = zero_shot_classifier( """The dominant sequence transduction models are based on complex recurrent or convolutional neural networks""" """ in an encoder-decoder configuration. The best performing models also connect the encoder and decoder""" """ through an attention mechanism. We propose a new simple network architecture, the Transformer, based""" """ solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two""" """ machine translation tasks show these models to be superior in quality while being more parallelizable""" """ and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014""" """ English-to-German translation task, improving over the existing best results, including ensembles by""" """ over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new""" """ single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small""" """ fraction of the training costs of the best models from the literature. We show that the Transformer""" """ generalizes well to other tasks by applying it successfully to English constituency parsing both with""" """ large and limited training data.""" , candidate_labels=["""machine learning""", """statistics""", """translation""", """vision"""] , multi_label=A , ) self.assertEqual( nested_simplify(A ) , { """sequence""": ( """The dominant sequence transduction models are based on complex recurrent or convolutional neural""" """ networks in an encoder-decoder configuration. The best performing models also connect the""" """ encoder and decoder through an attention mechanism. We propose a new simple network""" """ architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence""" """ and convolutions entirely. Experiments on two machine translation tasks show these models to be""" """ superior in quality while being more parallelizable and requiring significantly less time to""" """ train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,""" """ improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014""" """ English-to-French translation task, our model establishes a new single-model state-of-the-art""" """ BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training""" """ costs of the best models from the literature. We show that the Transformer generalizes well to""" """ other tasks by applying it successfully to English constituency parsing both with large and""" """ limited training data.""" ), """labels""": ["""translation""", """machine learning""", """vision""", """statistics"""], """scores""": [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , )
265
0
'''simple docstring''' from __future__ import annotations def _a( UpperCamelCase__ : List[str], UpperCamelCase__ : Union[str, Any], UpperCamelCase__ : int, UpperCamelCase__ : List[str] ): # noqa: E741 '''simple docstring''' while r - l > 1: SCREAMING_SNAKE_CASE__ : List[str] =(l + r) // 2 if v[m] >= key: SCREAMING_SNAKE_CASE__ : Dict =m else: SCREAMING_SNAKE_CASE__ : Any =m # noqa: E741 return r def _a( UpperCamelCase__ : list[int] ): '''simple docstring''' if len(UpperCamelCase__ ) == 0: return 0 SCREAMING_SNAKE_CASE__ : List[Any] =[0] * len(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =1 SCREAMING_SNAKE_CASE__ : Union[str, Any] =v[0] for i in range(1, len(UpperCamelCase__ ) ): if v[i] < tail[0]: SCREAMING_SNAKE_CASE__ : List[Any] =v[i] elif v[i] > tail[length - 1]: SCREAMING_SNAKE_CASE__ : int =v[i] length += 1 else: SCREAMING_SNAKE_CASE__ : Union[str, Any] =v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
222
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def _a( UpperCamelCase__ : int ): '''simple docstring''' if not isinstance(UpperCamelCase__, UpperCamelCase__ ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =precision SCREAMING_SNAKE_CASE__ : int =ceil(precision / 1_4 ) SCREAMING_SNAKE_CASE__ : int =4_2_6_8_8_0 * Decimal(1_0_0_0_5 ).sqrt() SCREAMING_SNAKE_CASE__ : Tuple =1 SCREAMING_SNAKE_CASE__ : Any =1_3_5_9_1_4_0_9 SCREAMING_SNAKE_CASE__ : List[Any] =Decimal(UpperCamelCase__ ) for k in range(1, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : str =factorial(6 * k ) // (factorial(3 * k ) * factorial(UpperCamelCase__ ) ** 3) linear_term += 5_4_5_1_4_0_1_3_4 exponential_term *= -2_6_2_5_3_7_4_1_2_6_4_0_7_6_8_0_0_0 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a_ = 5_0 print(F'''The first {n} digits of pi is: {pi(n)}''')
222
1
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __lowerCAmelCase ( TensorFormatter[Mapping, """torch.Tensor""", Mapping] ): def __init__( self , lowerCAmelCase=None , **lowerCAmelCase ) -> Optional[Any]: '''simple docstring''' super().__init__(features=lowerCAmelCase ) _lowercase =torch_tensor_kwargs import torch # noqa import torch at initialization def A__ ( self , lowerCAmelCase ) -> int: '''simple docstring''' import torch if isinstance(lowerCAmelCase , lowerCAmelCase ) and column: if all( isinstance(lowerCAmelCase , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCAmelCase ) return column def A__ ( self , lowerCAmelCase ) -> str: '''simple docstring''' import torch if isinstance(lowerCAmelCase , (str, bytes, type(lowerCAmelCase )) ): return value elif isinstance(lowerCAmelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _lowercase ={} if isinstance(lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): _lowercase ={'dtype': torch.intaa} elif isinstance(lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _lowercase ={'dtype': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCAmelCase , PIL.Image.Image ): _lowercase =np.asarray(lowerCAmelCase ) return torch.tensor(lowerCAmelCase , **{**default_dtype, **self.torch_tensor_kwargs} ) def A__ ( self , lowerCAmelCase ) -> str: '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCAmelCase , '__array__' ) and not isinstance(lowerCAmelCase , torch.Tensor ): _lowercase =data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCAmelCase , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCAmelCase ) for substruct in data_struct] ) elif isinstance(lowerCAmelCase , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCAmelCase ) for substruct in data_struct] ) return self._tensorize(lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> Tuple: '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCAmelCase , map_list=lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> Mapping: '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_row(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_row(lowerCAmelCase ) return self.recursive_tensorize(lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> "torch.Tensor": '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_column(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_column(lowerCAmelCase , pa_table.column_names[0] ) _lowercase =self.recursive_tensorize(lowerCAmelCase ) _lowercase =self._consolidate(lowerCAmelCase ) return column def A__ ( self , lowerCAmelCase ) -> Mapping: '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_batch(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_batch(lowerCAmelCase ) _lowercase =self.recursive_tensorize(lowerCAmelCase ) for column_name in batch: _lowercase =self._consolidate(batch[column_name] ) return batch
205
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class __lowerCAmelCase ( TensorFormatter[Mapping, """torch.Tensor""", Mapping] ): def __init__( self , lowerCAmelCase=None , **lowerCAmelCase ) -> Optional[Any]: '''simple docstring''' super().__init__(features=lowerCAmelCase ) _lowercase =torch_tensor_kwargs import torch # noqa import torch at initialization def A__ ( self , lowerCAmelCase ) -> int: '''simple docstring''' import torch if isinstance(lowerCAmelCase , lowerCAmelCase ) and column: if all( isinstance(lowerCAmelCase , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowerCAmelCase ) return column def A__ ( self , lowerCAmelCase ) -> str: '''simple docstring''' import torch if isinstance(lowerCAmelCase , (str, bytes, type(lowerCAmelCase )) ): return value elif isinstance(lowerCAmelCase , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _lowercase ={} if isinstance(lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): _lowercase ={'dtype': torch.intaa} elif isinstance(lowerCAmelCase , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _lowercase ={'dtype': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowerCAmelCase , PIL.Image.Image ): _lowercase =np.asarray(lowerCAmelCase ) return torch.tensor(lowerCAmelCase , **{**default_dtype, **self.torch_tensor_kwargs} ) def A__ ( self , lowerCAmelCase ) -> str: '''simple docstring''' import torch # support for torch, tf, jax etc. if hasattr(lowerCAmelCase , '__array__' ) and not isinstance(lowerCAmelCase , torch.Tensor ): _lowercase =data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowerCAmelCase , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowerCAmelCase ) for substruct in data_struct] ) elif isinstance(lowerCAmelCase , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowerCAmelCase ) for substruct in data_struct] ) return self._tensorize(lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> Tuple: '''simple docstring''' return map_nested(self._recursive_tensorize , lowerCAmelCase , map_list=lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> Mapping: '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_row(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_row(lowerCAmelCase ) return self.recursive_tensorize(lowerCAmelCase ) def A__ ( self , lowerCAmelCase ) -> "torch.Tensor": '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_column(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_column(lowerCAmelCase , pa_table.column_names[0] ) _lowercase =self.recursive_tensorize(lowerCAmelCase ) _lowercase =self._consolidate(lowerCAmelCase ) return column def A__ ( self , lowerCAmelCase ) -> Mapping: '''simple docstring''' _lowercase =self.numpy_arrow_extractor().extract_batch(lowerCAmelCase ) _lowercase =self.python_features_decoder.decode_batch(lowerCAmelCase ) _lowercase =self.recursive_tensorize(lowerCAmelCase ) for column_name in batch: _lowercase =self._consolidate(batch[column_name] ) return batch
205
1
from math import sqrt import numpy as np from sympy import symbols # Coefficient # Speed of light (m/s) SCREAMING_SNAKE_CASE_ = 2_9_9_7_9_2_4_5_8 # Symbols SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = symbols("""ct x y z""") def __lowercase ( _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' if velocity > c: raise ValueError("""Speed must not exceed light speed 299,792,458 [m/s]!""" ) elif velocity < 1: # Usually the speed should be much higher than 1 (c order of magnitude) raise ValueError("""Speed must be greater than or equal to 1!""" ) return velocity / c def __lowercase ( _SCREAMING_SNAKE_CASE ) -> float: '''simple docstring''' return 1 / sqrt(1 - beta(_SCREAMING_SNAKE_CASE ) ** 2 ) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> np.ndarray: '''simple docstring''' return np.array( [ [gamma(_SCREAMING_SNAKE_CASE ), -gamma(_SCREAMING_SNAKE_CASE ) * beta(_SCREAMING_SNAKE_CASE ), 0, 0], [-gamma(_SCREAMING_SNAKE_CASE ) * beta(_SCREAMING_SNAKE_CASE ), gamma(_SCREAMING_SNAKE_CASE ), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], ] ) def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> np.ndarray: '''simple docstring''' if event is None: SCREAMING_SNAKE_CASE = np.array([ct, x, y, z] ) # Symbolic four vector else: event[0] *= c # x0 is ct (speed of light * time) return transformation_matrix(_SCREAMING_SNAKE_CASE ) @ event if __name__ == "__main__": import doctest doctest.testmod() # Example of symbolic vector: SCREAMING_SNAKE_CASE_ = transform(2_9_9_7_9_2_4_5) print("""Example of four vector: """) print(F'''ct\' = {four_vector[0]}''') print(F'''x\' = {four_vector[1]}''') print(F'''y\' = {four_vector[2]}''') print(F'''z\' = {four_vector[3]}''') # Substitute symbols with numerical values SCREAMING_SNAKE_CASE_ = {ct: c, x: 1, y: 1, z: 1} SCREAMING_SNAKE_CASE_ = [four_vector[i].subs(sub_dict) for i in range(4)] print(F'''\n{numerical_vector}''')
193
from __future__ import annotations def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> list[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = len(_SCREAMING_SNAKE_CASE ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: SCREAMING_SNAKE_CASE = i + 1 else: SCREAMING_SNAKE_CASE = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F'''{two_pointer([2, 7, 1_1, 1_5], 9) = }''')
193
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def lowercase__ ( __lowercase : Dict=None ) -> str: """simple docstring""" __UpperCamelCase = argparse.ArgumentParser(add_help=__lowercase , allow_abbrev=__lowercase ) # The main config parser __UpperCamelCase = config_command_parser(__lowercase ) # The subparser to add commands to __UpperCamelCase = config_parser.add_subparsers(title='subcommands' , dest='subcommand' ) # Then add other parsers with the parent parser default_command_parser(__lowercase , parents=[parent_parser] ) update_command_parser(__lowercase , parents=[parent_parser] ) return config_parser def lowercase__ ( ) -> int: """simple docstring""" __UpperCamelCase = get_config_parser() __UpperCamelCase = config_parser.parse_args() if not hasattr(__lowercase , 'func' ): config_parser.print_help() exit(1 ) # Run args.func(__lowercase ) if __name__ == "__main__": main()
53
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version lowerCamelCase_ = get_logger(__name__) class UpperCamelCase_ : __magic_name__ = '''dummy_data''' __magic_name__ = '''datasets''' __magic_name__ = False def __init__( self : str , lowerCAmelCase_ : str , lowerCAmelCase_ : str , lowerCAmelCase_ : Union[Version, str] , lowerCAmelCase_ : Optional[str] = None , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = True , lowerCAmelCase_ : Optional[List[Callable]] = None , ) -> Tuple: UpperCAmelCase_ : Optional[int] = 0 UpperCAmelCase_ : int = dataset_name UpperCAmelCase_ : Optional[int] = cache_dir UpperCAmelCase_ : Tuple = use_local_dummy_data UpperCAmelCase_ : int = config # download_callbacks take a single url as input UpperCAmelCase_ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root UpperCAmelCase_ : Optional[Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general UpperCAmelCase_ : Dict = str(lowerCAmelCase_ ) # to be downloaded UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : int = None @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> str: if self._dummy_file is None: UpperCAmelCase_ : List[str] = self.download_dummy_data() return self._dummy_file @property def _SCREAMING_SNAKE_CASE ( self : Tuple ) -> int: if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Optional[int]: return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: UpperCAmelCase_ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) UpperCAmelCase_ : Union[str, Any] = cached_path( lowerCAmelCase_ , cache_dir=self.cache_dir , extract_compressed_file=lowerCAmelCase_ , force_extract=lowerCAmelCase_ ) return os.path.join(lowerCAmelCase_ , self.dummy_file_name ) @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def _SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: if self._bucket_url is None: UpperCAmelCase_ : Union[str, Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[Any]: # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowerCAmelCase_ : List[str] , *lowerCAmelCase_ : List[Any] ) -> Optional[int]: if self.load_existing_dummy_data: # dummy data is downloaded and tested UpperCAmelCase_ : Dict = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned UpperCAmelCase_ : Optional[int] = self.dummy_file_name # special case when data_url is a dict if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return self.create_dummy_data_dict(lowerCAmelCase_ , lowerCAmelCase_ ) elif isinstance(lowerCAmelCase_ , (list, tuple) ): return self.create_dummy_data_list(lowerCAmelCase_ , lowerCAmelCase_ ) else: return self.create_dummy_data_single(lowerCAmelCase_ , lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowerCAmelCase_ : int , *lowerCAmelCase_ : Union[str, Any] ) -> Any: return self.download_and_extract(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Dict , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Tuple ) -> Any: return self.download_and_extract(lowerCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : str , lowerCAmelCase_ : Union[str, Any] , *lowerCAmelCase_ : Tuple , **lowerCAmelCase_ : Tuple ) -> Union[str, Any]: return path def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[str]: return {} def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase_ : int , lowerCAmelCase_ : List[Any] ) -> List[Any]: UpperCAmelCase_ : Dict = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): for single_url in single_urls: download_callback(lowerCAmelCase_ ) else: UpperCAmelCase_ : Tuple = single_urls download_callback(lowerCAmelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : List[str] = [os.path.join(lowerCAmelCase_ , urllib.parse.quote_plus(Path(lowerCAmelCase_ ).name ) ) for x in single_urls] else: UpperCAmelCase_ : Optional[int] = single_urls UpperCAmelCase_ : Optional[Any] = os.path.join(lowerCAmelCase_ , urllib.parse.quote_plus(Path(lowerCAmelCase_ ).name ) ) UpperCAmelCase_ : int = value # make sure that values are unique if all(isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique UpperCAmelCase_ : List[str] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[int] ) -> Dict: UpperCAmelCase_ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one UpperCAmelCase_ : int = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , lowerCAmelCase_ ) ) for url in data_url ) UpperCAmelCase_ : Union[str, Any] = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): UpperCAmelCase_ : Tuple = [data_url[0]] * len(lowerCAmelCase_ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(lowerCAmelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus UpperCAmelCase_ : Dict = os.path.join(lowerCAmelCase_ , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(lowerCAmelCase_ ) return dummy_data_list def _SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ) -> Optional[int]: for download_callback in self.download_callbacks: download_callback(lowerCAmelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus UpperCAmelCase_ : Optional[Any] = os.path.join(lowerCAmelCase_ , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(lowerCAmelCase_ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: pass def _SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[int]: pass def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , lowerCAmelCase_ : Dict ) -> Optional[Any]: def _iter_archive_members(lowerCAmelCase_ : Dict ): # this preserves the order of the members inside the ZIP archive UpperCAmelCase_ : str = Path(self.dummy_file ).parent UpperCAmelCase_ : Optional[Any] = path.relative_to(lowerCAmelCase_ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: UpperCAmelCase_ : str = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = Path(lowerCAmelCase_ ) UpperCAmelCase_ : List[Any] = _iter_archive_members(lowerCAmelCase_ ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(lowerCAmelCase_ ).as_posix(), file_path.open("rb" ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase_ : Tuple ) -> str: if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): UpperCAmelCase_ : str = [paths] for path in paths: if os.path.isfile(lowerCAmelCase_ ): if os.path.basename(lowerCAmelCase_ ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(lowerCAmelCase_ ): if os.path.basename(lowerCAmelCase_ ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(lowerCAmelCase_ ): if filename.startswith((".", "__") ): continue yield os.path.join(lowerCAmelCase_ , lowerCAmelCase_ )
268
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ = {'configuration_opt': ['OPT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'OPTConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'OPT_PRETRAINED_MODEL_ARCHIVE_LIST', 'OPTForCausalLM', 'OPTModel', 'OPTPreTrainedModel', 'OPTForSequenceClassification', 'OPTForQuestionAnswering', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ['TFOPTForCausalLM', 'TFOPTModel', 'TFOPTPreTrainedModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ 'FlaxOPTForCausalLM', 'FlaxOPTModel', 'FlaxOPTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys snake_case_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
356
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer 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_file''': '''tokenizer.json'''} snake_case_ = { '''vocab_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''', }, '''merges_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/tokenizer.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/tokenizer.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/tokenizer.json''', }, } snake_case_ = { '''gpt2''': 1_024, '''gpt2-medium''': 1_024, '''gpt2-large''': 1_024, '''gpt2-xl''': 1_024, '''distilgpt2''': 1_024, } class SCREAMING_SNAKE_CASE__ (__snake_case ): __lowerCamelCase : List[str] = VOCAB_FILES_NAMES __lowerCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : int = ["""input_ids""", """attention_mask"""] __lowerCamelCase : str = GPTaTokenizer def __init__( self , a=None , a=None , a=None , a="<|endoftext|>" , a="<|endoftext|>" , a="<|endoftext|>" , a=False , **a , ): super().__init__( a , a , tokenizer_file=a , unk_token=a , bos_token=a , eos_token=a , add_prefix_space=a , **a , ) lowercase__ : int = kwargs.pop('add_bos_token' , a) lowercase__ : List[str] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('add_prefix_space' , a) != add_prefix_space: lowercase__ : Optional[Any] = getattr(a , pre_tok_state.pop('type')) lowercase__ : List[Any] = add_prefix_space lowercase__ : str = pre_tok_class(**a) lowercase__ : Tuple = add_prefix_space def snake_case_ ( self , *a , **a): lowercase__ : Tuple = kwargs.get('is_split_into_words' , a) 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(*a , **a) def snake_case_ ( self , *a , **a): lowercase__ : Optional[Any] = kwargs.get('is_split_into_words' , a) 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(*a , **a) def snake_case_ ( self , a , a = None): lowercase__ : Any = self._tokenizer.model.save(a , name=a) return tuple(a) def snake_case_ ( self , a): lowercase__ : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a , add_special_tokens=a) + [self.eos_token_id]) if len(a) > self.model_max_length: lowercase__ : Union[str, Any] = input_ids[-self.model_max_length :] return input_ids
216
0
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=_UpperCAmelCase ) class lowercase__ ( _UpperCAmelCase ): a_ =field(default="""image-classification""", metadata={"""include_in_asdict_even_if_is_default""": True} ) a_ =Features({"""image""": Image()} ) a_ =Features({"""labels""": ClassLabel} ) a_ ="image" a_ ="labels" def UpperCAmelCase ( self , __UpperCAmelCase )-> Union[str, Any]: '''simple docstring''' if self.label_column not in features: raise ValueError(F"Column {self.label_column} is not present in features." ) if not isinstance(features[self.label_column] , __UpperCAmelCase ): raise ValueError(F"Column {self.label_column} is not a ClassLabel." ) lowerCAmelCase__ = copy.deepcopy(self ) lowerCAmelCase__ = self.label_schema.copy() lowerCAmelCase__ = features[self.label_column] lowerCAmelCase__ = label_schema return task_template @property def UpperCAmelCase ( self )-> Dict[str, str]: '''simple docstring''' return { self.image_column: "image", self.label_column: "labels", }
340
from collections import defaultdict def _a ( UpperCamelCase_ : int ) -> int: """simple docstring""" lowerCAmelCase__ = 1 lowerCAmelCase__ = True for v in tree[start]: if v not in visited: ret += dfs(UpperCamelCase_ ) if ret % 2 == 0: cuts.append(UpperCamelCase_ ) return ret def _a ( ) -> Optional[Any]: """simple docstring""" dfs(1 ) if __name__ == "__main__": a_, a_ = 10, 9 a_ = defaultdict(list) a_ = {} a_ = [] a_ = 0 a_ = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
340
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin __snake_case : Optional[int] = """\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n""" class __SCREAMING_SNAKE_CASE ( unittest.TestCase , __lowercase): def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = load_tool('text-question-answering' ) self.tool.setup() lowerCAmelCase__ = load_tool('text-question-answering' , remote=lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = self.tool(lowerCAmelCase__ , 'What did Hugging Face do in April 2021?' ) self.assertEqual(lowerCAmelCase__ , 'launched the BigScience Research Workshop' ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = self.remote_tool(lowerCAmelCase__ , 'What did Hugging Face do in April 2021?' ) self.assertEqual(lowerCAmelCase__ , 'launched the BigScience Research Workshop' ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = self.tool(text=lowerCAmelCase__ , question='What did Hugging Face do in April 2021?' ) self.assertEqual(lowerCAmelCase__ , 'launched the BigScience Research Workshop' ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = self.remote_tool(text=lowerCAmelCase__ , question='What did Hugging Face do in April 2021?' ) self.assertEqual(lowerCAmelCase__ , 'launched the BigScience Research Workshop' )
367
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
122
0
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder _UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _UpperCAmelCase : Optional[Any] = 256 class lowercase ( _SCREAMING_SNAKE_CASE ): __lowercase : Union[str, Any] = ["melgan"] def __init__( self , A_ , A_ , A_ , A_ , A_ , ) -> None: """simple docstring""" super().__init__() # From MELGAN UpperCamelCase = math.log(1e-5 ) # Matches MelGAN training. UpperCamelCase = 4.0 # Largest value for most examples UpperCamelCase = 128 self.register_modules( notes_encoder=A_ , continuous_encoder=A_ , decoder=A_ , scheduler=A_ , melgan=A_ , ) def __UpperCamelCase ( self , A_ , A_=(-1.0, 1.0) , A_=False ) -> List[str]: """simple docstring""" UpperCamelCase , UpperCamelCase = output_range if clip: UpperCamelCase = torch.clip(A_ , self.min_value , self.max_value ) # Scale to [0, 1]. UpperCamelCase = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def __UpperCamelCase ( self , A_ , A_=(-1.0, 1.0) , A_=False ) -> Optional[Any]: """simple docstring""" UpperCamelCase , UpperCamelCase = input_range UpperCamelCase = torch.clip(A_ , A_ , A_ ) if clip else outputs # Scale to [0, 1]. UpperCamelCase = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def __UpperCamelCase ( self , A_ , A_ , A_ ) -> List[Any]: """simple docstring""" UpperCamelCase = input_tokens > 0 UpperCamelCase , UpperCamelCase = self.notes_encoder( encoder_input_tokens=A_ , encoder_inputs_mask=A_ ) UpperCamelCase , UpperCamelCase = self.continuous_encoder( encoder_inputs=A_ , encoder_inputs_mask=A_ ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def __UpperCamelCase ( self , A_ , A_ , A_ ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = noise_time if not torch.is_tensor(A_ ): UpperCamelCase = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(A_ ) and len(timesteps.shape ) == 0: UpperCamelCase = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCamelCase = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) UpperCamelCase = self.decoder( encodings_and_masks=A_ , decoder_input_tokens=A_ , decoder_noise_time=A_ ) return logits @torch.no_grad() def __call__( self , A_ , A_ = None , A_ = 100 , A_ = True , A_ = "numpy" , A_ = None , A_ = 1 , ) -> Union[AudioPipelineOutput, Tuple]: """simple docstring""" if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A_ , A_ ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(A_ )}.''' ) UpperCamelCase = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) UpperCamelCase = np.zeros([1, 0, self.n_dims] , np.floataa ) UpperCamelCase = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=A_ , device=self.device ) for i, encoder_input_tokens in enumerate(A_ ): if i == 0: UpperCamelCase = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. UpperCamelCase = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=A_ , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. UpperCamelCase = ones UpperCamelCase = self.scale_features( A_ , output_range=[-1.0, 1.0] , clip=A_ ) UpperCamelCase = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=A_ , continuous_mask=A_ , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop UpperCamelCase = randn_tensor( shape=encoder_continuous_inputs.shape , generator=A_ , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(A_ ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCamelCase = self.decode( encodings_and_masks=A_ , input_tokens=A_ , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 UpperCamelCase = self.scheduler.step(A_ , A_ , A_ , generator=A_ ).prev_sample UpperCamelCase = self.scale_to_features(A_ , input_range=[-1.0, 1.0] ) UpperCamelCase = mel[:1] UpperCamelCase = mel.cpu().float().numpy() UpperCamelCase = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A_ , A_ ) logger.info('Generated segment' , A_ ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( 'Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( 'Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.' ) if output_type == "numpy": UpperCamelCase = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: UpperCamelCase = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=A_ )
222
import requests def A ( lowercase , lowercase ) -> None: '''simple docstring''' UpperCamelCase = {'Content-Type': 'application/json'} UpperCamelCase = requests.post(lowercase , json={'text': message_body} , headers=lowercase ) if response.status_code != 200: UpperCamelCase = ( 'Request to slack returned an error ' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(lowercase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
222
1
import random def snake_case_ ( lowerCAmelCase_ : int ): __lowercase : List[str] = num - 1 __lowercase : List[str] = 0 while s % 2 == 0: __lowercase : List[str] = s // 2 t += 1 for _ in range(5 ): __lowercase : List[str] = random.randrange(2 , num - 1 ) __lowercase : Optional[int] = pow(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if v != 1: __lowercase : Any = 0 while v != (num - 1): if i == t - 1: return False else: __lowercase : Union[str, Any] = i + 1 __lowercase : str = (v**2) % num return True def snake_case_ ( lowerCAmelCase_ : int ): if num < 2: return False __lowercase : int = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(lowerCAmelCase_ ) def snake_case_ ( lowerCAmelCase_ : int = 1024 ): while True: __lowercase : int = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(lowerCAmelCase_ ): return num if __name__ == "__main__": lowerCamelCase : List[str] = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
306
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def snake_case_ ( lowerCAmelCase_ : Tuple ): if isinstance(lowerCAmelCase_ , collections.abc.Iterable ): return x return (x, x) @require_flax class lowerCAmelCase : '''simple docstring''' def lowerCAmelCase ( self : Any , __a : Any , __a : List[Any] ) -> Optional[Any]: """simple docstring""" pass def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass def lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" pass def lowerCAmelCase ( self : Tuple , __a : np.ndarray , __a : np.ndarray , __a : float ) -> List[Any]: """simple docstring""" __lowercase : List[str] = np.abs((a - b) ).max() self.assertLessEqual(__a , __a , F"Difference between torch and flax is {diff} (>= {tol})." ) def lowerCAmelCase ( self : Tuple , __a : int , __a : str , __a : Union[str, Any] , __a : Optional[Any] , __a : Optional[Any]=None , **__a : Tuple ) -> Optional[Any]: """simple docstring""" __lowercase : str = VisionTextDualEncoderConfig.from_vision_text_configs(__a , __a ) __lowercase : str = FlaxVisionTextDualEncoderModel(__a ) __lowercase : Optional[Any] = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], config.projection_dim) ) def lowerCAmelCase ( self : Optional[int] , __a : Optional[int] , __a : Dict , __a : Dict , __a : List[str] , __a : Optional[Any]=None , **__a : str ) -> str: """simple docstring""" __lowercase , __lowercase : List[str] = self.get_vision_text_model(__a , __a ) __lowercase : Union[str, Any] = {"""vision_model""": vision_model, """text_model""": text_model} __lowercase : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__a ) __lowercase : Any = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) self.assertEqual(output["""text_embeds"""].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["""image_embeds"""].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCAmelCase ( self : Tuple , __a : Union[str, Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : Dict , __a : int=None , **__a : int ) -> List[Any]: """simple docstring""" __lowercase , __lowercase : Tuple = self.get_vision_text_model(__a , __a ) __lowercase : Union[str, Any] = {"""vision_model""": vision_model, """text_model""": text_model} __lowercase : List[str] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__a ) __lowercase : List[Any] = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) __lowercase : int = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__a ) __lowercase : int = FlaxVisionTextDualEncoderModel.from_pretrained(__a ) __lowercase : Tuple = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) __lowercase : int = after_output[0] __lowercase : int = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__a , 1E-3 ) def lowerCAmelCase ( self : List[Any] , __a : Any , __a : Tuple , __a : Optional[int] , __a : str , __a : Optional[Any]=None , **__a : Optional[Any] ) -> List[Any]: """simple docstring""" __lowercase , __lowercase : str = self.get_vision_text_model(__a , __a ) __lowercase : Optional[Any] = {"""vision_model""": vision_model, """text_model""": text_model} __lowercase : Dict = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__a ) __lowercase : Union[str, Any] = model( input_ids=__a , pixel_values=__a , attention_mask=__a , output_attentions=__a ) __lowercase : Optional[int] = output.vision_model_output.attentions self.assertEqual(len(__a ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __lowercase : Optional[int] = to_atuple(vision_model.config.image_size ) __lowercase : List[str] = to_atuple(vision_model.config.patch_size ) __lowercase : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __lowercase : int = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __lowercase : Dict = output.text_model_output.attentions self.assertEqual(len(__a ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCAmelCase ( self : Optional[int] , __a : List[str] , __a : List[Any] , __a : Optional[Any] ) -> Optional[int]: """simple docstring""" pt_model.to(__a ) pt_model.eval() # prepare inputs __lowercase : Union[str, Any] = inputs_dict __lowercase : List[Any] = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): __lowercase : Union[str, Any] = pt_model(**__a ).to_tuple() __lowercase : Tuple = fx_model(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(__a , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__a ) __lowercase : Any = FlaxVisionTextDualEncoderModel.from_pretrained(__a , from_pt=__a ) __lowercase : Dict = fx_model_loaded(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(__a , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__a ) __lowercase : str = VisionTextDualEncoderModel.from_pretrained(__a , from_flax=__a ) pt_model_loaded.to(__a ) pt_model_loaded.eval() with torch.no_grad(): __lowercase : List[Any] = pt_model_loaded(**__a ).to_tuple() self.assertEqual(len(__a ) , len(__a ) , """Output lengths differ between Flax and PyTorch""" ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(__a , pt_output_loaded.numpy() , 4E-2 ) def lowerCAmelCase ( self : Optional[int] , __a : List[Any] , __a : int , __a : Optional[int] ) -> Optional[int]: """simple docstring""" __lowercase : Union[str, Any] = VisionTextDualEncoderConfig.from_vision_text_configs(__a , __a ) __lowercase : str = VisionTextDualEncoderModel(__a ) __lowercase : Union[str, Any] = FlaxVisionTextDualEncoderModel(__a ) __lowercase : List[str] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , __a ) __lowercase : Any = fx_state self.check_pt_flax_equivalence(__a , __a , __a ) def lowerCAmelCase ( self : Any , __a : Any , __a : Dict , __a : Tuple ) -> str: """simple docstring""" __lowercase : int = VisionTextDualEncoderConfig.from_vision_text_configs(__a , __a ) __lowercase : Union[str, Any] = VisionTextDualEncoderModel(__a ) __lowercase : Dict = FlaxVisionTextDualEncoderModel(__a ) __lowercase : Tuple = load_flax_weights_in_pytorch_model(__a , fx_model.params ) self.check_pt_flax_equivalence(__a , __a , __a ) def lowerCAmelCase ( self : str ) -> Optional[Any]: """simple docstring""" __lowercase : Optional[Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**__a ) def lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __lowercase : int = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**__a ) def lowerCAmelCase ( self : List[Any] ) -> Dict: """simple docstring""" __lowercase : List[str] = self.prepare_config_and_inputs() self.check_save_load(**__a ) def lowerCAmelCase ( self : Any ) -> Dict: """simple docstring""" __lowercase : str = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**__a ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" __lowercase : Optional[Any] = self.prepare_config_and_inputs() __lowercase : Optional[int] = config_inputs_dict.pop("""vision_config""" ) __lowercase : Optional[int] = config_inputs_dict.pop("""text_config""" ) __lowercase : Dict = config_inputs_dict self.check_equivalence_pt_to_flax(__a , __a , __a ) self.check_equivalence_flax_to_pt(__a , __a , __a ) @slow def lowerCAmelCase ( self : Union[str, Any] ) -> str: """simple docstring""" __lowercase , __lowercase : List[Any] = self.get_pretrained_model_and_inputs() __lowercase : Dict = model_a(**__a ) __lowercase : Any = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(__a ) __lowercase : Tuple = FlaxVisionTextDualEncoderModel.from_pretrained(__a ) __lowercase : Optional[int] = model_a(**__a ) __lowercase : Tuple = after_outputs[0] __lowercase : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__a , 1E-5 ) @require_flax class lowerCAmelCase ( __a , unittest.TestCase ): '''simple docstring''' def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" __lowercase : int = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-vit""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=__a , text_from_pt=__a , ) __lowercase : int = 13 __lowercase : Union[str, Any] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __lowercase : Dict = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __lowercase : Tuple = random_attention_mask([batch_size, 4] ) __lowercase : str = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def lowerCAmelCase ( self : Optional[Any] , __a : Union[str, Any] , __a : int ) -> Dict: """simple docstring""" __lowercase : int = FlaxViTModel(__a ) __lowercase : List[Any] = FlaxBertModel(__a ) return vision_model, text_model def lowerCAmelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" __lowercase : Tuple = FlaxViTModelTester(self ) __lowercase : str = FlaxBertModelTester(self ) __lowercase : List[str] = vit_model_tester.prepare_config_and_inputs() __lowercase : Union[str, Any] = bert_model_tester.prepare_config_and_inputs() __lowercase , __lowercase : Optional[int] = vision_config_and_inputs __lowercase , __lowercase , __lowercase , __lowercase : Any = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class lowerCAmelCase ( __a , unittest.TestCase ): '''simple docstring''' def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __lowercase : List[Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( """hf-internal-testing/tiny-random-clip""" , """hf-internal-testing/tiny-bert""" , vision_from_pt=__a , text_from_pt=__a , ) __lowercase : Tuple = 13 __lowercase : Optional[Any] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __lowercase : Tuple = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __lowercase : List[Any] = random_attention_mask([batch_size, 4] ) __lowercase : int = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask} return model, inputs def lowerCAmelCase ( self : str , __a : str , __a : Union[str, Any] ) -> Any: """simple docstring""" __lowercase : Dict = FlaxCLIPVisionModel(__a ) __lowercase : Optional[Any] = FlaxBertModel(__a ) return vision_model, text_model def lowerCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" __lowercase : List[Any] = FlaxCLIPVisionModelTester(self ) __lowercase : Optional[Any] = FlaxBertModelTester(self ) __lowercase : Any = clip_model_tester.prepare_config_and_inputs() __lowercase : Optional[Any] = bert_model_tester.prepare_config_and_inputs() __lowercase , __lowercase : Dict = vision_config_and_inputs __lowercase , __lowercase , __lowercase , __lowercase : Optional[int] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def lowerCAmelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" __lowercase : Any = FlaxVisionTextDualEncoderModel.from_pretrained("""clip-italian/clip-italian""" , logit_scale_init_value=1.0 ) __lowercase : int = VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian""" ) __lowercase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) __lowercase : Tuple = processor( text=["""una foto di un gatto""", """una foto di un cane"""] , images=__a , padding=__a , return_tensors="""np""" ) __lowercase : Optional[int] = model(**__a ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __lowercase : Optional[Any] = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , __a , atol=1E-3 ) )
306
1
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a__: str = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , unittest.TestCase ): __SCREAMING_SNAKE_CASE = XLMProphetNetTokenizer __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True def UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing A__ = XLMProphetNetTokenizer(__lowerCamelCase,keep_accents=__lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self ): A__ = '''[PAD]''' A__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ),__lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ),__lowerCamelCase ) def UpperCamelCase ( self ): A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0],'''[PAD]''' ) self.assertEqual(vocab_keys[1],'''[CLS]''' ) self.assertEqual(vocab_keys[-1],'''j''' ) self.assertEqual(len(__lowerCamelCase ),1012 ) def UpperCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size,1012 ) def UpperCamelCase ( self ): A__ = XLMProphetNetTokenizer(__lowerCamelCase,keep_accents=__lowerCamelCase ) A__ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__lowerCamelCase,['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ),[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]],) A__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __lowerCamelCase,[ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ],) A__ = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase,[ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ],) A__ = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase,[ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''[UNK]''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''[UNK]''', '''.''', ],) @cached_property def UpperCamelCase ( self ): return XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased''' ) @slow def UpperCamelCase ( self ): A__ = '''Hello World!''' A__ = [3_5389, 6672, 49, 2] self.assertListEqual(__lowerCamelCase,self.big_tokenizer.encode(__lowerCamelCase ) ) @slow def UpperCamelCase ( self ): # fmt: off A__ = {'''input_ids''': [[1_1073, 8_2783, 18, 26, 8_2783, 549, 5_1540, 248, 1_7209, 1301, 217, 20, 21_5186, 1325, 147, 1_7209, 1301, 217, 20, 5_6370, 53, 12_2020, 20, 1_6477, 27, 8_7355, 4548, 20, 4728, 7_8392, 17, 15_9969, 18, 26, 2_4491, 629, 15, 538, 2_2704, 5439, 15, 2788, 2_4491, 9885, 15, 4_3534, 605, 15, 814, 1_8403, 3_3200, 29, 15, 4_3534, 2_4458, 1_2410, 111, 2_4966, 8_3669, 9637, 14_4068, 26, 850, 2_2346, 27, 147, 2_4966, 8_3669, 8_3490, 26, 3_9113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 12_2020, 11_5785, 34, 816, 1339, 4_6887, 18, 147, 5_3905, 1951, 4_2238, 4_1170, 1_7732, 834, 436, 15, 2_7523, 9_8733, 217, 147, 5542, 4981, 930, 1_7347, 16, 2], [2_0091, 629, 94, 8_2786, 58, 490, 20, 1528, 84, 5_3905, 344, 8_0592, 11_0128, 1_8822, 5267, 1306, 62, 15_2537, 308, 7997, 401, 12_4427, 549, 3_5442, 225, 109, 1_5055, 2_5748, 147, 7119, 4_3712, 34, 767, 13_5366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 6_3784, 11_9466, 17, 14_7808, 8_8214, 18, 656, 81, 32, 3296, 1_0280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase,model_name='''microsoft/xprophetnet-large-wiki100-cased''',revision='''1acad1643ddd54a44df6a1b797ada8373685d90e''',)
193
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer a__: Optional[int] = logging.get_logger(__name__) a__: int = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} a__: Optional[Any] = { 'vocab_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt' ), 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt' ), 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt', 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json', 'bert-base-multilingual-uncased': ( 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json' ), 'bert-base-multilingual-cased': ( 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json' ), 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json' ), 'bert-base-cased-finetuned-mrpc': ( 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-cased': ( 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json' ), 'bert-base-german-dbmdz-uncased': ( 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json' ), 'wietsedv/bert-base-dutch-cased': ( 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json' ), }, } a__: List[str] = { 'bert-base-uncased': 512, 'bert-large-uncased': 512, 'bert-base-cased': 512, 'bert-large-cased': 512, 'bert-base-multilingual-uncased': 512, 'bert-base-multilingual-cased': 512, 'bert-base-chinese': 512, 'bert-base-german-cased': 512, 'bert-large-uncased-whole-word-masking': 512, 'bert-large-cased-whole-word-masking': 512, 'bert-large-uncased-whole-word-masking-finetuned-squad': 512, 'bert-large-cased-whole-word-masking-finetuned-squad': 512, 'bert-base-cased-finetuned-mrpc': 512, 'bert-base-german-dbmdz-cased': 512, 'bert-base-german-dbmdz-uncased': 512, 'TurkuNLP/bert-base-finnish-cased-v1': 512, 'TurkuNLP/bert-base-finnish-uncased-v1': 512, 'wietsedv/bert-base-dutch-cased': 512, } a__: Optional[Any] = { 'bert-base-uncased': {'do_lower_case': True}, 'bert-large-uncased': {'do_lower_case': True}, 'bert-base-cased': {'do_lower_case': False}, 'bert-large-cased': {'do_lower_case': False}, 'bert-base-multilingual-uncased': {'do_lower_case': True}, 'bert-base-multilingual-cased': {'do_lower_case': False}, 'bert-base-chinese': {'do_lower_case': False}, 'bert-base-german-cased': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking': {'do_lower_case': False}, 'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True}, 'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False}, 'bert-base-cased-finetuned-mrpc': {'do_lower_case': False}, 'bert-base-german-dbmdz-cased': {'do_lower_case': False}, 'bert-base-german-dbmdz-uncased': {'do_lower_case': True}, 'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False}, 'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True}, 'wietsedv/bert-base-dutch-cased': {'do_lower_case': False}, } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = PRETRAINED_INIT_CONFIGURATION __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE = BertTokenizer def __init__( self,__lowerCamelCase=None,__lowerCamelCase=None,__lowerCamelCase=True,__lowerCamelCase="[UNK]",__lowerCamelCase="[SEP]",__lowerCamelCase="[PAD]",__lowerCamelCase="[CLS]",__lowerCamelCase="[MASK]",__lowerCamelCase=True,__lowerCamelCase=None,**__lowerCamelCase,): super().__init__( __lowerCamelCase,tokenizer_file=__lowerCamelCase,do_lower_case=__lowerCamelCase,unk_token=__lowerCamelCase,sep_token=__lowerCamelCase,pad_token=__lowerCamelCase,cls_token=__lowerCamelCase,mask_token=__lowerCamelCase,tokenize_chinese_chars=__lowerCamelCase,strip_accents=__lowerCamelCase,**__lowerCamelCase,) A__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''',__lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''',__lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''',__lowerCamelCase ) != tokenize_chinese_chars ): A__ = getattr(__lowerCamelCase,normalizer_state.pop('''type''' ) ) A__ = do_lower_case A__ = strip_accents A__ = tokenize_chinese_chars A__ = normalizer_class(**__lowerCamelCase ) A__ = do_lower_case def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase=None ): A__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): A__ = [self.sep_token_id] A__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): A__ = self._tokenizer.model.save(__lowerCamelCase,name=__lowerCamelCase ) return tuple(__lowerCamelCase )
193
1
"""simple docstring""" import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging UpperCAmelCase__ = logging.get_logger(__name__) class lowerCAmelCase__ ( A_ ): __a = ["""input_features"""] def __init__( self : List[str] , _lowerCamelCase : Optional[Any]=80 , _lowerCamelCase : List[str]=16000 , _lowerCamelCase : Dict=160 , _lowerCamelCase : Optional[int]=30 , _lowerCamelCase : List[Any]=400 , _lowerCamelCase : str=0.0 , _lowerCamelCase : Union[str, Any]=False , **_lowerCamelCase : Tuple , ): super().__init__( feature_size=_lowerCamelCase , sampling_rate=_lowerCamelCase , padding_value=_lowerCamelCase , return_attention_mask=_lowerCamelCase , **_lowerCamelCase , ) _snake_case = n_fft _snake_case = hop_length _snake_case = chunk_length _snake_case = chunk_length * sampling_rate _snake_case = self.n_samples // hop_length _snake_case = sampling_rate _snake_case = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=_lowerCamelCase , min_frequency=0.0 , max_frequency=8_0_0_0.0 , sampling_rate=_lowerCamelCase , norm='''slaney''' , mel_scale='''slaney''' , ) def lowercase ( self : List[Any] , _lowerCamelCase : np.array ): _snake_case = spectrogram( _lowerCamelCase , window_function(self.n_fft , '''hann''' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel='''log10''' , ) _snake_case = log_spec[:, :-1] _snake_case = np.maximum(_lowerCamelCase , log_spec.max() - 8.0 ) _snake_case = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def lowercase ( _lowerCamelCase : List[np.ndarray] , _lowerCamelCase : List[np.ndarray] , _lowerCamelCase : float = 0.0 ): if attention_mask is not None: _snake_case = np.array(_lowerCamelCase , np.intaa ) _snake_case = [] for vector, length in zip(_lowerCamelCase , attention_mask.sum(-1 ) ): _snake_case = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7 ) if length < normed_slice.shape[0]: _snake_case = padding_value normed_input_values.append(_lowerCamelCase ) else: _snake_case = [(x - x.mean()) / np.sqrt(x.var() + 1e-7 ) for x in input_values] return normed_input_values def __call__( self : Union[str, Any] , _lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , _lowerCamelCase : bool = True , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[Union[str, TensorType]] = None , _lowerCamelCase : Optional[bool] = None , _lowerCamelCase : Optional[str] = "max_length" , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[int] = None , _lowerCamelCase : Optional[bool] = None , **_lowerCamelCase : Optional[int] , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' f''' was sampled with {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.''' ) _snake_case = isinstance(_lowerCamelCase , 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}''' ) _snake_case = is_batched_numpy or ( isinstance(_lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: _snake_case = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(_lowerCamelCase , np.ndarray ): _snake_case = np.asarray(_lowerCamelCase , dtype=np.floataa ) elif isinstance(_lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): _snake_case = raw_speech.astype(np.floataa ) # always return batch if not is_batched: _snake_case = [np.asarray([raw_speech] ).T] _snake_case = BatchFeature({'''input_features''': raw_speech} ) # convert into correct format for padding _snake_case = self.pad( _lowerCamelCase , padding=_lowerCamelCase , max_length=max_length if max_length else self.n_samples , truncation=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: _snake_case = self.zero_mean_unit_var_norm( padded_inputs['''input_features'''] , attention_mask=padded_inputs['''attention_mask'''] , padding_value=self.padding_value , ) _snake_case = np.stack(padded_inputs['''input_features'''] , axis=0 ) # make sure list is in array format _snake_case = padded_inputs.get('''input_features''' ).transpose(2 , 0 , 1 ) _snake_case = [self._np_extract_fbank_features(_lowerCamelCase ) for waveform in input_features[0]] if isinstance(input_features[0] , _lowerCamelCase ): _snake_case = [np.asarray(_lowerCamelCase , dtype=np.floataa ) for feature in input_features] else: _snake_case = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) _snake_case = padded_inputs['''attention_mask'''][:, :: self.hop_length] if return_tensors is not None: _snake_case = padded_inputs.convert_to_tensors(_lowerCamelCase ) return padded_inputs def lowercase ( self : List[str] ): _snake_case = copy.deepcopy(self.__dict__ ) _snake_case = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
40
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, 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 MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class lowerCAmelCase__ : def __init__( self : List[Any] , _lowerCamelCase : Optional[int] , _lowerCamelCase : List[Any]=2 , _lowerCamelCase : List[str]=True , _lowerCamelCase : Optional[Any]=False , _lowerCamelCase : Optional[Any]=10 , _lowerCamelCase : Dict=3 , _lowerCamelCase : Optional[int]=32 * 8 , _lowerCamelCase : Optional[int]=32 * 8 , _lowerCamelCase : Dict=4 , _lowerCamelCase : Optional[int]=64 , ): _snake_case = parent _snake_case = batch_size _snake_case = is_training _snake_case = use_auxiliary_loss _snake_case = num_queries _snake_case = num_channels _snake_case = min_size _snake_case = max_size _snake_case = num_labels _snake_case = hidden_dim _snake_case = hidden_dim def lowercase ( self : List[str] ): _snake_case = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) _snake_case = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) _snake_case = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() _snake_case = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() _snake_case = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowercase ( self : Optional[Any] ): _snake_case = MaskaFormerConfig( hidden_size=self.hidden_dim , ) _snake_case = self.num_queries _snake_case = self.num_labels _snake_case = [1, 1, 1, 1] _snake_case = self.num_channels _snake_case = 64 _snake_case = 128 _snake_case = self.hidden_dim _snake_case = self.hidden_dim _snake_case = self.hidden_dim return config def lowercase ( self : Any ): _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = self.prepare_config_and_inputs() _snake_case = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def lowercase ( self : Union[str, Any] , _lowerCamelCase : List[Any] , _lowerCamelCase : int ): _snake_case = output.encoder_hidden_states _snake_case = output.pixel_decoder_hidden_states _snake_case = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_layers ) def lowercase ( self : List[Any] , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : Any , _lowerCamelCase : List[Any] , _lowerCamelCase : Dict=False ): with torch.no_grad(): _snake_case = MaskaFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _snake_case = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) _snake_case = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # 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(_lowerCamelCase , _lowerCamelCase ) def lowercase ( self : int , _lowerCamelCase : Dict , _lowerCamelCase : List[Any] , _lowerCamelCase : Any , _lowerCamelCase : str , _lowerCamelCase : Union[str, Any] ): _snake_case = MaskaFormerForUniversalSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase : List[str] ): # 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(): _snake_case = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) _snake_case = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) _snake_case = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class lowerCAmelCase__ ( A_ , A_ , unittest.TestCase ): __a = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __a = {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {} __a = False __a = False __a = False __a = False def lowercase ( self : int ): _snake_case = MaskaFormerModelTester(self ) _snake_case = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def lowercase ( self : Dict ): self.config_tester.run_common_tests() def lowercase ( self : Tuple ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def lowercase ( self : Any ): _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''Mask2Former does not use inputs_embeds''' ) def lowercase ( self : Optional[int] ): pass @unittest.skip(reason='''Mask2Former does not have a get_input_embeddings method''' ) def lowercase ( self : Dict ): pass @unittest.skip(reason='''Mask2Former is not a generative model''' ) def lowercase ( self : int ): pass @unittest.skip(reason='''Mask2Former does not use token embeddings''' ) def lowercase ( self : List[str] ): pass @require_torch_multi_gpu @unittest.skip( reason='''Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def lowercase ( self : Optional[int] ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowercase ( self : str ): pass def lowercase ( self : Optional[int] ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = model_class(_lowerCamelCase ) _snake_case = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case = [*signature.parameters.keys()] _snake_case = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def lowercase ( self : Optional[int] ): for model_name in ["facebook/mask2former-swin-small-coco-instance"]: _snake_case = MaskaFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowercase ( self : List[Any] ): _snake_case = (self.model_tester.min_size,) * 2 _snake_case = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 10, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 10 , device=_lowerCamelCase ).long(), } _snake_case = self.model_tester.get_config() _snake_case = MaskaFormerForUniversalSegmentation(_lowerCamelCase ).to(_lowerCamelCase ) _snake_case = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def lowercase ( self : Union[str, Any] ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def lowercase ( self : str ): _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case = model_class(_lowerCamelCase ).to(_lowerCamelCase ) _snake_case = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def lowercase ( self : str ): if not self.model_tester.is_training: return _snake_case = self.all_model_classes[1] _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs() _snake_case = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() _snake_case = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def lowercase ( self : Optional[int] ): _snake_case = self.all_model_classes[1] _snake_case , _snake_case , _snake_case , _snake_case , _snake_case = self.model_tester.prepare_config_and_inputs() _snake_case = True _snake_case = True _snake_case = model_class(_lowerCamelCase ).to(_lowerCamelCase ) model.train() _snake_case = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) _snake_case = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() _snake_case = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() _snake_case = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() _snake_case = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) 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 _UpperCAmelCase ( ) -> Tuple: _snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class lowerCAmelCase__ ( unittest.TestCase ): @cached_property def lowercase ( self : Optional[Any] ): return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowercase ( self : int ): return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowercase ( self : Any ): _snake_case = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ) _snake_case = self.default_image_processor _snake_case = prepare_img() _snake_case = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) _snake_case = 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(_lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): _snake_case = model(**_lowerCamelCase ) _snake_case = torch.tensor( [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) _snake_case = torch.tensor( [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) _snake_case = torch.tensor( [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def lowercase ( self : str ): _snake_case = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ).eval() _snake_case = self.default_image_processor _snake_case = prepare_img() _snake_case = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) _snake_case = 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(_lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): _snake_case = model(**_lowerCamelCase ) # masks_queries_logits _snake_case = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) _snake_case = [ [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1], [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1], [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5], ] _snake_case = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits _snake_case = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) _snake_case = torch.tensor( [ [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2], [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3], [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def lowercase ( self : Optional[int] ): _snake_case = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(_lowerCamelCase ).eval() _snake_case = self.default_image_processor _snake_case = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , ) _snake_case = inputs['''pixel_values'''].to(_lowerCamelCase ) _snake_case = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] _snake_case = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): _snake_case = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
40
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __magic_name__ ( _UpperCamelCase ): def __init__( self : int ,_UpperCAmelCase : Optional[NestedDataStructureLike[PathLike]] = None ,_UpperCAmelCase : Optional[NamedSplit] = None ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,_UpperCAmelCase : bool = False ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Union[str, Any] ,): _a : int = path_or_paths _a : List[Any] = split if split or isinstance(_UpperCAmelCase ,_UpperCAmelCase ) else 'train' _a : Tuple = features _a : Optional[Any] = cache_dir _a : List[str] = keep_in_memory _a : Tuple = streaming _a : str = num_proc _a : int = kwargs @abstractmethod def __lowercase ( self : Tuple ): pass class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[Any] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,_UpperCAmelCase : bool = False ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Optional[int] ,): _a : Union[str, Any] = features _a : List[str] = cache_dir _a : Optional[Any] = keep_in_memory _a : int = streaming _a : int = num_proc _a : List[str] = kwargs @abstractmethod def __lowercase ( self : List[Any] ): pass
89
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image lowercase__ =['text', 'image', 'audio'] def __UpperCamelCase ( lowerCAmelCase__ : List[str] ): __a : Optional[int] = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((5_1_2, 5_1_2) ) ) elif input_type == "audio": inputs.append(torch.ones(3_0_0_0 ) ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): inputs.append(create_inputs(lowerCAmelCase__ ) ) else: raise ValueError(f"Invalid type requested: {input_type}" ) return inputs def __UpperCamelCase ( lowerCAmelCase__ : List ): __a : List[str] = [] for output in outputs: if isinstance(lowerCAmelCase__ , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(lowerCAmelCase__ , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(lowerCAmelCase__ , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(f"Invalid output: {output}" ) return output_types @is_tool_test class UpperCamelCase__ : def lowerCAmelCase (self : Any ): self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) __a : Any = self.tool.inputs for _input in inputs: if isinstance(_input , snake_case_ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) __a : Optional[int] = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCAmelCase (self : List[Any] ): __a : Union[str, Any] = create_inputs(self.tool.inputs ) __a : List[Any] = self.tool(*snake_case_ ) # There is a single output if len(self.tool.outputs ) == 1: __a : Tuple = [outputs] self.assertListEqual(output_types(snake_case_ ) , self.tool.outputs ) def lowerCAmelCase (self : List[Any] ): self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def lowerCAmelCase (self : Any ): __a : Any = create_inputs(self.tool.inputs ) __a : Union[str, Any] = self.tool(*snake_case_ ) if not isinstance(snake_case_ , snake_case_ ): __a : Tuple = [outputs] self.assertEqual(len(snake_case_ ) , len(self.tool.outputs ) ) for output, output_type in zip(snake_case_ , self.tool.outputs ): __a : List[Any] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(snake_case_ , snake_case_ ) ) def lowerCAmelCase (self : Optional[int] ): __a : Any = create_inputs(self.tool.inputs ) __a : Dict = [] for _input, input_type in zip(snake_case_ , self.tool.inputs ): if isinstance(snake_case_ , snake_case_ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error __a : Optional[Any] = self.tool(*snake_case_ ) if not isinstance(snake_case_ , snake_case_ ): __a : Dict = [outputs] self.assertEqual(len(snake_case_ ) , len(self.tool.outputs ) )
216
0
'''simple docstring''' from __future__ import annotations def UpperCAmelCase ( lowerCamelCase_ :list[int] ): # This function is recursive '''simple docstring''' snake_case_ : Tuple = len(lowerCamelCase_ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else snake_case_ : Optional[Any] = array[0] snake_case_ : int = False snake_case_ : Tuple = 1 snake_case_ : list[int] = [] while not is_found and i < array_length: if array[i] < pivot: snake_case_ : Tuple = True snake_case_ : int = [element for element in array[i:] if element >= array[i]] snake_case_ : str = longest_subsequence(lowerCamelCase_ ) if len(lowerCamelCase_ ) > len(lowerCamelCase_ ): snake_case_ : Dict = temp_array else: i += 1 snake_case_ : List[str] = [element for element in array[1:] if element >= pivot] snake_case_ : Any = [pivot, *longest_subsequence(lowerCamelCase_ )] if len(lowerCamelCase_ ) > len(lowerCamelCase_ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
8
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __A : List[Any] = logging.get_logger(__name__) __A : str = { 'google/canine-s': 'https://huggingface.co/google/canine-s/resolve/main/config.json', # See all CANINE models at https://huggingface.co/models?filter=canine } class __UpperCamelCase ( lowercase__ ): lowercase : List[Any] = 'canine' def __init__( self :Optional[int] ,_UpperCamelCase :Dict=7_6_8 ,_UpperCamelCase :Union[str, Any]=1_2 ,_UpperCamelCase :int=1_2 ,_UpperCamelCase :int=3_0_7_2 ,_UpperCamelCase :int="gelu" ,_UpperCamelCase :Any=0.1 ,_UpperCamelCase :int=0.1 ,_UpperCamelCase :Any=1_6_3_8_4 ,_UpperCamelCase :Tuple=1_6 ,_UpperCamelCase :List[str]=0.02 ,_UpperCamelCase :Any=1E-1_2 ,_UpperCamelCase :Tuple=0 ,_UpperCamelCase :List[str]=0xE_0_0_0 ,_UpperCamelCase :Optional[Any]=0xE_0_0_1 ,_UpperCamelCase :str=4 ,_UpperCamelCase :Optional[int]=4 ,_UpperCamelCase :str=8 ,_UpperCamelCase :int=1_6_3_8_4 ,_UpperCamelCase :int=1_2_8 ,**_UpperCamelCase :str ,): super().__init__(pad_token_id=_UpperCamelCase ,bos_token_id=_UpperCamelCase ,eos_token_id=_UpperCamelCase ,**_UpperCamelCase ) snake_case_ : List[str] = max_position_embeddings snake_case_ : Union[str, Any] = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : Optional[int] = num_attention_heads snake_case_ : Tuple = intermediate_size snake_case_ : str = hidden_act snake_case_ : Union[str, Any] = hidden_dropout_prob snake_case_ : Dict = attention_probs_dropout_prob snake_case_ : Optional[Any] = initializer_range snake_case_ : Optional[int] = type_vocab_size snake_case_ : List[str] = layer_norm_eps # Character config: snake_case_ : Any = downsampling_rate snake_case_ : List[str] = upsampling_kernel_size snake_case_ : int = num_hash_functions snake_case_ : Tuple = num_hash_buckets snake_case_ : Tuple = local_transformer_stride
8
1
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = 42 UpperCAmelCase__ = None UpperCAmelCase__ = None _lowerCamelCase : int = namedtuple("""CoinsDistribResult""", """moves excess""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" if root is None: return 0 # Validation def count_nodes(lowercase_ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(lowercase_ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(lowercase_ ) != count_coins(lowercase_ ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(lowercase_ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) A__ , A__ = get_distrib(node.left ) A__ , A__ = get_distrib(node.right ) A__ = 1 - left_distrib_excess A__ = 1 - right_distrib_excess A__ = ( left_distrib_moves + right_distrib_moves + abs(lowercase_ ) + abs(lowercase_ ) ) A__ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(lowercase_ , lowercase_ ) return get_distrib(lowercase_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
14
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCamelCase__ ( ) -> tuple[list[int], int]: UpperCamelCase_ = [randint(-1000 , 1000 ) for i in range(10 )] UpperCamelCase_ = randint(-5000 , 5000 ) return (arr, r) _A = make_dataset() def lowerCamelCase__ ( a__ : list[int] , a__ : int ) -> tuple[int, ...]: for triplet in permutations(a__ , 3 ): if sum(a__ ) == target: return tuple(sorted(a__ ) ) return (0, 0, 0) def lowerCamelCase__ ( a__ : list[int] , a__ : int ) -> tuple[int, int, int]: arr.sort() UpperCamelCase_ = len(a__ ) for i in range(n - 1 ): UpperCamelCase_ , UpperCamelCase_ = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowerCamelCase__ ( ) -> tuple[float, float]: UpperCamelCase_ = """ from __main__ import dataset, triplet_sum1, triplet_sum2 """ UpperCamelCase_ = """ triplet_sum1(*dataset) """ UpperCamelCase_ = """ triplet_sum2(*dataset) """ UpperCamelCase_ = repeat(setup=a__ , stmt=a__ , repeat=5 , number=1_0000 ) UpperCamelCase_ = repeat(setup=a__ , stmt=a__ , repeat=5 , number=1_0000 ) return (min(a__ ), min(a__ )) if __name__ == "__main__": from doctest import testmod testmod() _A = solution_times() print(F'''The time for naive implementation is {times[0]}.''') print(F'''The time for optimized implementation is {times[1]}.''')
122
0
"""simple docstring""" from math import ceil, sqrt def __UpperCAmelCase ( UpperCAmelCase_ : int = 1_00_00_00 ) -> int: '''simple docstring''' __snake_case : int = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __snake_case : Optional[Any] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: __snake_case : str = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f'''{solution() = }''')
95
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _a : Optional[int]= logging.get_logger() @dataclass class UpperCamelCase : UpperCAmelCase : nn.Module UpperCAmelCase : List[nn.Module] = field(default_factory=lowercase ) UpperCAmelCase : list = field(default_factory=lowercase ) def _lowercase (self : str , _A : Optional[Any] , _A : Tensor , _A : Tensor) -> Any: __snake_case : str = len(list(m.modules())) == 1 or isinstance(_A , nn.Convad) or isinstance(_A , nn.BatchNormad) if has_not_submodules: self.traced.append(_A) def __call__(self : Dict , _A : Tensor) -> Optional[Any]: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook)) self.module(_A) [x.remove() for x in self.handles] return self @property def _lowercase (self : Union[str, Any]) -> List[str]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda _A: len(list(x.state_dict().keys())) > 0 , self.traced)) @dataclass class UpperCamelCase : UpperCAmelCase : nn.Module UpperCAmelCase : nn.Module UpperCAmelCase : int = 0 UpperCAmelCase : List = field(default_factory=lowercase ) UpperCAmelCase : List = field(default_factory=lowercase ) def __call__(self : List[str] , _A : Tensor) -> List[Any]: __snake_case : Any = Tracker(self.dest)(_A).parametrized __snake_case : int = Tracker(self.src)(_A).parametrized __snake_case : List[Any] = list(filter(lambda _A: type(_A) not in self.src_skip , _A)) __snake_case : Any = list(filter(lambda _A: type(_A) not in self.dest_skip , _A)) if len(_A) != len(_A): raise Exception( f"Numbers of operations are different. Source module has {len(_A)} operations while" f" destination module has {len(_A)}.") for dest_m, src_m in zip(_A , _A): dest_m.load_state_dict(src_m.state_dict()) if self.verbose == 1: print(f"Transfered from={src_m} to={dest_m}") def __UpperCAmelCase ( UpperCAmelCase_ : str , UpperCAmelCase_ : ResNetConfig , UpperCAmelCase_ : Path , UpperCAmelCase_ : bool = True ) -> List[str]: '''simple docstring''' print(F"Converting {name}..." ) with torch.no_grad(): __snake_case : Dict = timm.create_model(UpperCAmelCase_ , pretrained=UpperCAmelCase_ ).eval() __snake_case : List[Any] = ResNetForImageClassification(UpperCAmelCase_ ).eval() __snake_case : int = ModuleTransfer(src=UpperCAmelCase_ , dest=UpperCAmelCase_ ) __snake_case : Optional[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(UpperCAmelCase_ ) assert torch.allclose(from_model(UpperCAmelCase_ ) , our_model(UpperCAmelCase_ ).logits ), "The model logits don't match the original one." __snake_case : str = F"resnet{'-'.join(name.split('resnet' ) )}" print(UpperCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add model' , use_temp_dir=UpperCAmelCase_ , ) # we can use the convnext one __snake_case : int = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message='Add image processor' , use_temp_dir=UpperCAmelCase_ , ) print(F"Pushed {checkpoint_name}" ) def __UpperCAmelCase ( UpperCAmelCase_ : Path , UpperCAmelCase_ : str = None , UpperCAmelCase_ : bool = True ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = 'imagenet-1k-id2label.json' __snake_case : Optional[Any] = 10_00 __snake_case : Any = (1, num_labels) __snake_case : List[Any] = 'huggingface/label-files' __snake_case : Dict = num_labels __snake_case : Any = json.load(open(hf_hub_download(UpperCAmelCase_ , UpperCAmelCase_ , repo_type='dataset' ) , 'r' ) ) __snake_case : Any = {int(UpperCAmelCase_ ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : Optional[Any] = {v: k for k, v in idalabel.items()} __snake_case : Optional[int] = partial(UpperCAmelCase_ , num_labels=UpperCAmelCase_ , idalabel=UpperCAmelCase_ , labelaid=UpperCAmelCase_ ) __snake_case : str = { 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 1_28, 2_56, 5_12] , layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[2_56, 5_12, 10_24, 20_48] , layer_type='bottleneck' ), } if model_name: convert_weight_and_push(UpperCAmelCase_ , names_to_config[model_name] , UpperCAmelCase_ , UpperCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _a : Optional[Any]= argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _a : Union[str, Any]= parser.parse_args() _a : Path= args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
95
1
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCamelCase = ''' Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)["depth"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline("depth-estimation") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to("cuda") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to("cuda") >>> img = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/cat.png" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda") >>> prompt = "A robot, 4k photo" >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature" >>> generator = torch.Generator(device="cuda").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save("robot_cat.png") ``` ''' def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__=8 ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class __UpperCAmelCase (_UpperCAmelCase ): def __init__( self: List[str] , UpperCAmelCase_: UNetaDConditionModel , UpperCAmelCase_: DDPMScheduler , UpperCAmelCase_: VQModel , ): '''simple docstring''' super().__init__() self.register_modules( unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , movq=UpperCAmelCase_ , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCamelCase ( self: Optional[int] , UpperCAmelCase_: Optional[Any] , UpperCAmelCase_: List[Any] , UpperCAmelCase_: List[Any] , UpperCAmelCase_: Optional[int] , UpperCAmelCase_: List[Any] , UpperCAmelCase_: int ): '''simple docstring''' if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_ ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def UpperCamelCase ( self: Any , UpperCAmelCase_: Optional[int]=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(F'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCAmelCase_ , UpperCAmelCase_ ) def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: Dict=0 ): '''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.""" ) _SCREAMING_SNAKE_CASE = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=UpperCAmelCase_ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(UpperCAmelCase_ , UpperCAmelCase_ , prev_module_hook=UpperCAmelCase_ ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCamelCase ( self: Any ): '''simple docstring''' if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(UpperCAmelCase_ , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(UpperCAmelCase_ ) def __call__( self: Union[str, Any] , UpperCAmelCase_: Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase_: Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCAmelCase_: torch.FloatTensor , UpperCAmelCase_: int = 512 , UpperCAmelCase_: int = 512 , UpperCAmelCase_: int = 100 , UpperCAmelCase_: float = 4.0 , UpperCAmelCase_: int = 1 , UpperCAmelCase_: Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_: Optional[torch.FloatTensor] = None , UpperCAmelCase_: Optional[str] = "pil" , UpperCAmelCase_: bool = True , ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase_ , dim=0 ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase_ , dim=0 ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _SCREAMING_SNAKE_CASE = torch.cat(UpperCAmelCase_ , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(UpperCAmelCase_ , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(UpperCAmelCase_ , dim=0 ) _SCREAMING_SNAKE_CASE = hint.repeat_interleave(UpperCAmelCase_ , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=UpperCAmelCase_ ) self.scheduler.set_timesteps(UpperCAmelCase_ , device=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.movq.config.latent_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(UpperCAmelCase_ , UpperCAmelCase_ , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.scheduler , ) for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds, """hint""": hint} _SCREAMING_SNAKE_CASE = self.unet( sample=UpperCAmelCase_ , timestep=UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , added_cond_kwargs=UpperCAmelCase_ , return_dict=UpperCAmelCase_ , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = 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"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_ , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(UpperCAmelCase_ , force_not_quantize=UpperCAmelCase_ )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase_ )
306
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DPMSolverMultistepScheduler, TextToVideoSDPipeline, UNetaDConditionModel, ) from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __UpperCAmelCase (_UpperCAmelCase ,unittest.TestCase ): __snake_case : List[Any] = TextToVideoSDPipeline __snake_case : Optional[int] = TEXT_TO_IMAGE_PARAMS __snake_case : Dict = TEXT_TO_IMAGE_BATCH_PARAMS # No `output_type`. __snake_case : Optional[int] = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def UpperCamelCase ( self: int ): '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""") , up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""") , cross_attention_dim=32 , attention_head_dim=4 , ) _SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) _SCREAMING_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 ) _SCREAMING_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 , ) _SCREAMING_SNAKE_CASE = CLIPTextModel(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, } return components def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: Tuple , UpperCAmelCase_: Dict=0 ): '''simple docstring''' if str(UpperCAmelCase_ ).startswith("""mps""" ): _SCREAMING_SNAKE_CASE = torch.manual_seed(UpperCAmelCase_ ) else: _SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = { """prompt""": """A painting of a squirrel eating a burger""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """pt""", } return inputs def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = TextToVideoSDPipeline(**UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase_ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = """np""" _SCREAMING_SNAKE_CASE = sd_pipe(**UpperCAmelCase_ ).frames _SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (64, 64, 3) _SCREAMING_SNAKE_CASE = np.array([1_58.0, 1_60.0, 1_53.0, 1_25.0, 1_00.0, 1_21.0, 1_11.0, 93.0, 1_13.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' self._test_attention_slicing_forward_pass(test_mean_pixel_difference=UpperCAmelCase_ , expected_max_diff=3E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def UpperCamelCase ( self: List[Any] ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase_ , expected_max_diff=1E-2 ) @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' pass @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline.""" ) def UpperCamelCase ( self: int ): '''simple docstring''' pass @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline.""" ) def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' pass def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' return super().test_progress_bar() @slow @skip_mps class __UpperCAmelCase (unittest.TestCase ): def UpperCamelCase ( self: List[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy""" ) _SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) _SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) _SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) _SCREAMING_SNAKE_CASE = """Spiderman is surfing""" _SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe(UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=25 , output_type="""pt""" ).frames _SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2 def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy""" ) _SCREAMING_SNAKE_CASE = TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b""" ) _SCREAMING_SNAKE_CASE = pipe.to("""cuda""" ) _SCREAMING_SNAKE_CASE = """Spiderman is surfing""" _SCREAMING_SNAKE_CASE = torch.Generator(device="""cpu""" ).manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe(UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=2 , output_type="""pt""" ).frames _SCREAMING_SNAKE_CASE = video_frames.cpu().numpy() assert np.abs(expected_video - video ).mean() < 5E-2
306
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( UpperCamelCase = 1000 ): """simple docstring""" lowerCAmelCase__ : Union[str, Any] = -1 lowerCAmelCase__ : Optional[Any] = 0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c lowerCAmelCase__ : Optional[Any] = (n * n - 2 * a * n) // (2 * n - 2 * a) lowerCAmelCase__ : Tuple = n - a - b if c * c == (a * a + b * b): lowerCAmelCase__ : int = a * b * c if candidate >= product: lowerCAmelCase__ : Any = candidate return product if __name__ == "__main__": print(F"""{solution() = }""")
353
'''simple docstring''' import math import random from typing import Any from .hill_climbing import SearchProblem def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase = True , UpperCamelCase = math.inf , UpperCamelCase = -math.inf , UpperCamelCase = math.inf , UpperCamelCase = -math.inf , UpperCamelCase = False , UpperCamelCase = 100 , UpperCamelCase = 0.01 , UpperCamelCase = 1 , ): """simple docstring""" lowerCAmelCase__ : int = False lowerCAmelCase__ : Optional[Any] = search_prob lowerCAmelCase__ : Tuple = start_temperate lowerCAmelCase__ : Optional[Any] = [] lowerCAmelCase__ : str = 0 lowerCAmelCase__ : Tuple = None while not search_end: lowerCAmelCase__ : List[str] = current_state.score() if best_state is None or current_score > best_state.score(): lowerCAmelCase__ : List[str] = current_state scores.append(UpperCamelCase ) iterations += 1 lowerCAmelCase__ : Dict = None lowerCAmelCase__ : List[Any] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to lowerCAmelCase__ : Tuple = random.randint(0 , len(UpperCamelCase ) - 1 ) # picking a random neighbor lowerCAmelCase__ : str = neighbors.pop(UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: lowerCAmelCase__ : Union[str, Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution lowerCAmelCase__ : Tuple = picked_neighbor else: lowerCAmelCase__ : List[Any] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability lowerCAmelCase__ : List[Any] = picked_neighbor lowerCAmelCase__ : Optional[int] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor lowerCAmelCase__ : str = True else: lowerCAmelCase__ : Optional[int] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(UpperCamelCase ) , UpperCamelCase ) plt.xlabel("""Iterations""" ) plt.ylabel("""Function values""" ) plt.show() return best_state if __name__ == "__main__": def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) _lowerCAmelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) _lowerCAmelCase = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( '''The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ''' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase ): """simple docstring""" return (3 * x**2) - (6 * y) _lowerCAmelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing(prob, find_max=False, visualization=True) print( '''The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" ) _lowerCAmelCase = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) _lowerCAmelCase = simulated_annealing(prob, find_max=True, visualization=True) print( '''The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ''' F"""{local_min.score()}""" )
184
0
"""simple docstring""" import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = """▁""" __lowercase = {"""vocab_file""": """vocab.txt""", """sentencepiece_model_ckpt""": """sentencepiece.bpe.model"""} __lowercase = { """sentencepiece_model_file""": """sentencepiece.bpe.model""", """vocab_file""": """vocab.txt""", } __lowercase = { """vocab_file""": { """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""", """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt""", }, """sentencepiece_model_file""": { """ernie-m-base""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""", """ernie-m-large""": """https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model""", }, } __lowercase = { """ernie-m-base""": 514, """ernie-m-large""": 514, } __lowercase = { """ernie-m-base""": {"""do_lower_case""": False}, """ernie-m-large""": {"""do_lower_case""": False}, } class _A ( _a ): """simple docstring""" UpperCAmelCase : List[str] = ["input_ids"] UpperCAmelCase : Union[str, Any] = VOCAB_FILES_NAMES UpperCAmelCase : Optional[Any] = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase : int = RESOURCE_FILES_NAMES def __init__( self : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int=None , __UpperCAmelCase : Union[str, Any]=False , __UpperCAmelCase : Tuple="utf8" , __UpperCAmelCase : List[str]="[UNK]" , __UpperCAmelCase : Dict="[SEP]" , __UpperCAmelCase : Any="[PAD]" , __UpperCAmelCase : str="[CLS]" , __UpperCAmelCase : Optional[Any]="[MASK]" , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : Dict , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , vocab_file=__UpperCAmelCase , encoding=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a : str = do_lower_case a : Dict = sentencepiece_model_ckpt a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(__UpperCAmelCase) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: a : Any = self.load_vocab(filepath=__UpperCAmelCase) else: a : int = {self.sp_model.id_to_piece(__UpperCAmelCase): id for id in range(self.sp_model.get_piece_size())} a : int = {v: k for k, v in self.vocab.items()} def __snake_case ( self : Any , __UpperCAmelCase : List[Any]): if text is None: return None a : Any = self.tokenize(__UpperCAmelCase) a , a : str = "", [] for i, ch in enumerate(__UpperCAmelCase): if ch in self.SP_CHAR_MAPPING: a : List[Any] = self.SP_CHAR_MAPPING.get(__UpperCAmelCase) else: a : Union[str, Any] = unicodedata.normalize("NFKC" , __UpperCAmelCase) if self.is_whitespace(__UpperCAmelCase): continue normalized_text += ch char_mapping.extend([i] * len(__UpperCAmelCase)) a , a , a : Optional[int] = normalized_text, [], 0 if self.do_lower_case: a : List[str] = text.lower() for token in split_tokens: if token[:1] == "▁": a : int = token[1:] a : Tuple = text[offset:].index(__UpperCAmelCase) + offset a : List[str] = start + len(__UpperCAmelCase) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)) a : List[Any] = end return token_mapping @property def __snake_case ( self : str): return len(self.vocab) def __snake_case ( self : Optional[Any]): return dict(self.vocab , **self.added_tokens_encoder) def __getstate__( self : int): a : str = self.__dict__.copy() a : Optional[Any] = None return state def __setstate__( self : str , __UpperCAmelCase : str): a : Tuple = d # for backward compatibility if not hasattr(self , "sp_model_kwargs"): a : Optional[int] = {} a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.sentencepiece_model_ckpt) def __snake_case ( self : Dict , __UpperCAmelCase : List[Any]): return "".join((self.SP_CHAR_MAPPING.get(__UpperCAmelCase , __UpperCAmelCase) for c in text)) def __snake_case ( self : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : Optional[Any]=64 , __UpperCAmelCase : Any=0.1): if self.sp_model_kwargs.get("enable_sampling") is True: a : Union[str, Any] = True if self.sp_model_kwargs.get("alpha") is not None: a : Optional[int] = self.sp_model_kwargs.get("alpha") if self.sp_model_kwargs.get("nbest_size") is not None: a : Dict = self.sp_model_kwargs.get("nbest_size") if not enable_sampling: a : int = self.sp_model.EncodeAsPieces(__UpperCAmelCase) else: a : List[Any] = self.sp_model.SampleEncodeAsPieces(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) a : Optional[Any] = [] for pi, piece in enumerate(__UpperCAmelCase): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__UpperCAmelCase) and pi != 0: new_pieces.append(__UpperCAmelCase) continue else: continue a : Any = 0 for i, chunk in enumerate(__UpperCAmelCase): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__UpperCAmelCase) or self.is_punct(__UpperCAmelCase): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) new_pieces.append(__UpperCAmelCase) a : Optional[int] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) a : int = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i]) a : Tuple = i if len(__UpperCAmelCase) > lst_i: new_pieces.append(piece[lst_i:]) return new_pieces def __snake_case ( self : List[str] , __UpperCAmelCase : Union[str, Any]): a : str = "".join(__UpperCAmelCase).replace(__UpperCAmelCase , " ").strip() return out_string def __snake_case ( self : Optional[int] , __UpperCAmelCase : Union[str, Any]): a : Tuple = self.convert_ids_to_tokens(__UpperCAmelCase) a : str = "".join(__UpperCAmelCase).replace(__UpperCAmelCase , " ").strip() return out_string def __snake_case ( self : Union[str, Any] , __UpperCAmelCase : Optional[int]): return self.vocab.get(__UpperCAmelCase , self.vocab.get(self.unk_token)) def __snake_case ( self : Any , __UpperCAmelCase : Tuple): return self.reverse_vocab.get(__UpperCAmelCase , self.unk_token) def __snake_case ( self : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any]=None): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] a : int = [self.cls_token_id] a : Optional[int] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def __snake_case ( self : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict=None): if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def __snake_case ( self : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : str=None , __UpperCAmelCase : int=False): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model.") return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__UpperCAmelCase)) + [1, 1] + ([0] * len(__UpperCAmelCase)) + [1] return [1] + ([0] * len(__UpperCAmelCase)) + [1] def __snake_case ( self : str , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None): # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(__UpperCAmelCase) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__UpperCAmelCase) + 1) + [1] * (len(__UpperCAmelCase) + 3) def __snake_case ( self : int , __UpperCAmelCase : Optional[int]): if "\u4e00" <= char <= "\u9fff": return True return False def __snake_case ( self : Tuple , __UpperCAmelCase : Union[str, Any]): if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def __snake_case ( self : int , __UpperCAmelCase : List[Any]): if char in ",;:.?!~,;:。?!《》【】": return True return False def __snake_case ( self : str , __UpperCAmelCase : Optional[Any]): if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__UpperCAmelCase) == 1: a : Optional[Any] = unicodedata.category(__UpperCAmelCase) if cat == "Zs": return True return False def __snake_case ( self : Optional[int] , __UpperCAmelCase : Optional[Any]): a : Optional[int] = {} with io.open(__UpperCAmelCase , "r" , encoding="utf-8") as f: for index, line in enumerate(__UpperCAmelCase): a : Tuple = line.rstrip("\n") a : Any = int(__UpperCAmelCase) return token_to_idx def __snake_case ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None): a : int = 0 if os.path.isdir(__UpperCAmelCase): a : Union[str, Any] = os.path.join( __UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]) else: a : Tuple = (filename_prefix + "-" if filename_prefix else "") + save_directory with open(__UpperCAmelCase , "w" , encoding="utf-8") as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __UpperCAmelCase: kv[1]): if index != token_index: logger.warning( f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.''' " Please check that the vocabulary is not corrupted!") a : Union[str, Any] = token_index writer.write(token + "\n") index += 1 a : Union[str, Any] = os.path.join(__UpperCAmelCase , "sentencepiece.bpe.model") with open(__UpperCAmelCase , "wb") as fi: a : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase) return (vocab_file,)
40
"""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. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class _A ( _a ): """simple docstring""" UpperCAmelCase : str = """naver-clova-ix/donut-base-finetuned-docvqa""" UpperCAmelCase : Tuple = ( """This is a tool that answers a question about an document (pdf). It takes an input named `document` which """ """should be the document containing the information, as well as a `question` that is the question about the """ """document. It returns a text that contains the answer to the question.""" ) UpperCAmelCase : List[str] = """document_qa""" UpperCAmelCase : str = AutoProcessor UpperCAmelCase : Optional[int] = VisionEncoderDecoderModel UpperCAmelCase : int = ["""image""", """text"""] UpperCAmelCase : int = ["""text"""] def __init__( self : Tuple , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Any): if not is_vision_available(): raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool.") super().__init__(*__UpperCAmelCase , **__UpperCAmelCase) def __snake_case ( self : Tuple , __UpperCAmelCase : "Image" , __UpperCAmelCase : str): a : Any = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" a : Union[str, Any] = task_prompt.replace("{user_input}" , __UpperCAmelCase) a : Optional[Any] = self.pre_processor.tokenizer( __UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_tensors="pt").input_ids a : Any = self.pre_processor(__UpperCAmelCase , return_tensors="pt").pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def __snake_case ( self : int , __UpperCAmelCase : int): return self.model.generate( inputs["pixel_values"].to(self.device) , decoder_input_ids=inputs["decoder_input_ids"].to(self.device) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__UpperCAmelCase , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__UpperCAmelCase , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__UpperCAmelCase , ).sequences def __snake_case ( self : str , __UpperCAmelCase : List[Any]): a : Union[str, Any] = self.pre_processor.batch_decode(__UpperCAmelCase)[0] a : Optional[Any] = sequence.replace(self.pre_processor.tokenizer.eos_token , "") a : Any = sequence.replace(self.pre_processor.tokenizer.pad_token , "") a : Optional[Any] = re.sub(r"<.*?>" , "" , __UpperCAmelCase , count=1).strip() # remove first task start token a : List[str] = self.pre_processor.tokenajson(__UpperCAmelCase) return sequence["answer"]
40
1
"""simple docstring""" from __future__ import annotations __UpperCamelCase = list[list[int]] # assigning initial values to the grid __UpperCamelCase = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution __UpperCamelCase = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def UpperCAmelCase ( UpperCAmelCase ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def UpperCAmelCase ( UpperCAmelCase ) -> Matrix | None: if location := find_empty_location(UpperCAmelCase ): snake_case_ , snake_case_ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): snake_case_ = digit if sudoku(UpperCAmelCase ) is not None: return grid snake_case_ = 0 return None def UpperCAmelCase ( UpperCAmelCase ) -> None: for row in grid: for cell in row: print(UpperCAmelCase , end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 20) print_solution(example_grid) print('''\nExample grid solution:''') __UpperCamelCase = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
312
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = "resnet" SCREAMING_SNAKE_CASE_ = ["basic", "bottleneck"] def __init__( self, lowerCAmelCase__=3, lowerCAmelCase__=64, lowerCAmelCase__=[256, 512, 1024, 2048], lowerCAmelCase__=[3, 4, 6, 3], lowerCAmelCase__="bottleneck", lowerCAmelCase__="relu", lowerCAmelCase__=False, lowerCAmelCase__=None, lowerCAmelCase__=None, **lowerCAmelCase__, ) -> Dict: super().__init__(**lowerCAmelCase__) if layer_type not in self.layer_types: raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types)}') snake_case_ = num_channels snake_case_ = embedding_size snake_case_ = hidden_sizes snake_case_ = depths snake_case_ = layer_type snake_case_ = hidden_act snake_case_ = downsample_in_first_stage snake_case_ = ['stem'] + [f'stage{idx}' for idx in range(1, len(lowerCAmelCase__) + 1)] snake_case_ , snake_case_ = get_aligned_output_features_output_indices( out_features=lowerCAmelCase__, out_indices=lowerCAmelCase__, stage_names=self.stage_names) class UpperCamelCase ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ = version.parse("1.11" ) @property def a_ ( self) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ]) @property def a_ ( self) -> float: return 1e-3
312
1
from __future__ import annotations def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ ): # This function is recursive snake_case_ = len(SCREAMING_SNAKE_CASE__ ) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else snake_case_ = array[0] snake_case_ = False snake_case_ = 1 snake_case_ = [] while not is_found and i < array_length: if array[i] < pivot: snake_case_ = True snake_case_ = [element for element in array[i:] if element >= array[i]] snake_case_ = longest_subsequence(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ): snake_case_ = temp_array else: i += 1 snake_case_ = [element for element in array[1:] if element >= pivot] snake_case_ = [pivot, *longest_subsequence(SCREAMING_SNAKE_CASE__ )] if len(SCREAMING_SNAKE_CASE__ ) > len(SCREAMING_SNAKE_CASE__ ): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
8
from __future__ import annotations from math import pi, sqrt def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
8
1
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "geglu" , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = "layer_norm" , _SCREAMING_SNAKE_CASE = False , ): super().__init__() __lowerCAmelCase : List[str] = only_cross_attention __lowerCAmelCase : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' __lowerCAmelCase : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to" f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}." ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: __lowerCAmelCase : List[Any] = AdaLayerNorm(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.use_ada_layer_norm_zero: __lowerCAmelCase : int = AdaLayerNormZero(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: __lowerCAmelCase : Any = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = Attention( query_dim=_SCREAMING_SNAKE_CASE , heads=_SCREAMING_SNAKE_CASE , dim_head=_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_SCREAMING_SNAKE_CASE , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. __lowerCAmelCase : List[str] = ( AdaLayerNorm(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm else nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Tuple = Attention( query_dim=_SCREAMING_SNAKE_CASE , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_SCREAMING_SNAKE_CASE , dim_head=_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE , upcast_attention=_SCREAMING_SNAKE_CASE , ) # is self-attn if encoder_hidden_states is none else: __lowerCAmelCase : Dict = None __lowerCAmelCase : Optional[int] = None # 3. Feed-forward __lowerCAmelCase : int = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = FeedForward(_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , activation_fn=_SCREAMING_SNAKE_CASE , final_dropout=_SCREAMING_SNAKE_CASE ) # let chunk size default to None __lowerCAmelCase : List[Any] = None __lowerCAmelCase : List[str] = 0 def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Sets chunk feed-forward __lowerCAmelCase : str = chunk_size __lowerCAmelCase : Tuple = dim def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , ): # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: __lowerCAmelCase : Dict = self.norma(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.use_ada_layer_norm_zero: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : List[str] = self.norma( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hidden_dtype=hidden_states.dtype ) else: __lowerCAmelCase : Dict = self.norma(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = cross_attention_kwargs if cross_attention_kwargs is not None else {} __lowerCAmelCase : List[str] = self.attna( _SCREAMING_SNAKE_CASE , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) if self.use_ada_layer_norm_zero: __lowerCAmelCase : Any = gate_msa.unsqueeze(1 ) * attn_output __lowerCAmelCase : str = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: __lowerCAmelCase : List[str] = ( self.norma(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm else self.norma(_SCREAMING_SNAKE_CASE ) ) __lowerCAmelCase : Dict = self.attna( _SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : List[str] = attn_output + hidden_states # 3. Feed-forward __lowerCAmelCase : List[Any] = self.norma(_SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm_zero: __lowerCAmelCase : Any = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`." ) __lowerCAmelCase : Dict = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size __lowerCAmelCase : List[Any] = torch.cat( [self.ff(_SCREAMING_SNAKE_CASE ) for hid_slice in norm_hidden_states.chunk(_SCREAMING_SNAKE_CASE , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: __lowerCAmelCase : int = self.ff(_SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm_zero: __lowerCAmelCase : str = gate_mlp.unsqueeze(1 ) * ff_output __lowerCAmelCase : Optional[Any] = ff_output + hidden_states return hidden_states class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 4 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = "geglu" , _SCREAMING_SNAKE_CASE = False , ): super().__init__() __lowerCAmelCase : str = int(dim * mult ) __lowerCAmelCase : str = dim_out if dim_out is not None else dim if activation_fn == "gelu": __lowerCAmelCase : int = GELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if activation_fn == "gelu-approximate": __lowerCAmelCase : Optional[Any] = GELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , approximate='tanh' ) elif activation_fn == "geglu": __lowerCAmelCase : str = GEGLU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif activation_fn == "geglu-approximate": __lowerCAmelCase : List[str] = ApproximateGELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Union[str, Any] = nn.ModuleList([] ) # project in self.net.append(_SCREAMING_SNAKE_CASE ) # project dropout self.net.append(nn.Dropout(_SCREAMING_SNAKE_CASE ) ) # project out self.net.append(nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(_SCREAMING_SNAKE_CASE ) ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): for module in self.net: __lowerCAmelCase : Dict = module(_SCREAMING_SNAKE_CASE ) return hidden_states class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "none" ): super().__init__() __lowerCAmelCase : List[Any] = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : int = approximate def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): if gate.device.type != "mps": return F.gelu(_SCREAMING_SNAKE_CASE , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : Union[str, Any] = self.proj(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.gelu(_SCREAMING_SNAKE_CASE ) return hidden_states class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): super().__init__() __lowerCAmelCase : str = nn.Linear(_SCREAMING_SNAKE_CASE , dim_out * 2 ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): if gate.device.type != "mps": return F.gelu(_SCREAMING_SNAKE_CASE ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase , __lowerCAmelCase : int = self.proj(_SCREAMING_SNAKE_CASE ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(_SCREAMING_SNAKE_CASE ) class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): super().__init__() __lowerCAmelCase : List[Any] = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : int = self.proj(_SCREAMING_SNAKE_CASE ) return x * torch.sigmoid(1.702 * x ) class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): super().__init__() __lowerCAmelCase : Optional[Any] = nn.Embedding(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[int] = nn.SiLU() __lowerCAmelCase : Any = nn.Linear(_SCREAMING_SNAKE_CASE , embedding_dim * 2 ) __lowerCAmelCase : List[str] = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): __lowerCAmelCase : str = self.linear(self.silu(self.emb(_SCREAMING_SNAKE_CASE ) ) ) __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = torch.chunk(_SCREAMING_SNAKE_CASE , 2 ) __lowerCAmelCase : List[Any] = self.norm(_SCREAMING_SNAKE_CASE ) * (1 + scale) + shift return x class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): super().__init__() __lowerCAmelCase : List[str] = CombinedTimestepLabelEmbeddings(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[str] = nn.SiLU() __lowerCAmelCase : Optional[Any] = nn.Linear(_SCREAMING_SNAKE_CASE , 6 * embedding_dim , bias=_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE , eps=1E-6 ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ): __lowerCAmelCase : List[str] = self.linear(self.silu(self.emb(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hidden_dtype=_SCREAMING_SNAKE_CASE ) ) ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Dict = emb.chunk(6 , dim=1 ) __lowerCAmelCase : Any = self.norm(_SCREAMING_SNAKE_CASE ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class A__ ( nn.Module): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1E-5 ): super().__init__() __lowerCAmelCase : Any = num_groups __lowerCAmelCase : Optional[int] = eps if act_fn is None: __lowerCAmelCase : Dict = None else: __lowerCAmelCase : Optional[Any] = get_activation(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Any = nn.Linear(_SCREAMING_SNAKE_CASE , out_dim * 2 ) def __lowerCamelCase ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if self.act: __lowerCAmelCase : str = self.act(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = self.linear(_SCREAMING_SNAKE_CASE ) __lowerCAmelCase : List[Any] = emb[:, :, None, None] __lowerCAmelCase , __lowerCAmelCase : str = emb.chunk(2 , dim=1 ) __lowerCAmelCase : Tuple = F.group_norm(_SCREAMING_SNAKE_CASE , self.num_groups , eps=self.eps ) __lowerCAmelCase : int = x * (1 + scale) + shift return x
182
"""simple docstring""" # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : str = { 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, oder?', } # BLUE scores as follows: # "pair": [fairseq, transformers] __lowerCAmelCase : Union[str, Any] = { 'ru-en': ['[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)', '39.20'], 'en-ru': ['[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)', '33.47'], 'en-de': ['[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)', '42.83'], 'de-en': ['[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)', '41.35'], } __lowerCAmelCase : List[str] = F"{src_lang}-{tgt_lang}" __lowerCAmelCase : Tuple = F"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) __lowerCAmelCase : Any = os.path.join(_UpperCamelCase , 'README.md' ) print(F"Generating {path}" ) with open(_UpperCamelCase , 'w' , encoding='utf-8' ) as f: f.write(_UpperCamelCase ) # make sure we are under the root of the project lowerCamelCase__ = Path(__file__).resolve().parent.parent.parent lowerCamelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = model_name.split("""-""") lowerCamelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
182
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : str = { """configuration_nezha""": ["""NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NezhaConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ """NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST""", """NezhaForNextSentencePrediction""", """NezhaForMaskedLM""", """NezhaForPreTraining""", """NezhaForMultipleChoice""", """NezhaForQuestionAnswering""", """NezhaForSequenceClassification""", """NezhaForTokenClassification""", """NezhaModel""", """NezhaPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nezha import ( NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, NezhaPreTrainedModel, ) else: import sys UpperCAmelCase : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
95
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer UpperCAmelCase : int = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCAmelCase : List[Any] = [ """small""", """small-base""", """medium""", """medium-base""", """intermediate""", """intermediate-base""", """large""", """large-base""", """xlarge""", """xlarge-base""", ] UpperCAmelCase : Optional[int] = { """vocab_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt""", """funnel-transformer/small-base""": """https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt""", """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt""", """funnel-transformer/large-base""": """https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt""", """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """funnel-transformer/small""": """https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json""", """funnel-transformer/small-base""": ( """https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json""" ), """funnel-transformer/medium""": """https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json""", """funnel-transformer/medium-base""": ( """https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate""": ( """https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json""" ), """funnel-transformer/intermediate-base""": ( """https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json""" ), """funnel-transformer/large""": """https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json""", """funnel-transformer/large-base""": ( """https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json""" ), """funnel-transformer/xlarge""": """https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json""", """funnel-transformer/xlarge-base""": ( """https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json""" ), }, } UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": 512 for name in _model_names} UpperCAmelCase : Optional[int] = {F"""funnel-transformer/{name}""": {"""do_lower_case""": True} for name in _model_names} class __lowerCAmelCase ( UpperCamelCase__): _lowercase : str = VOCAB_FILES_NAMES _lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = PRETRAINED_INIT_CONFIGURATION _lowercase : Union[str, Any] = FunnelTokenizer _lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = 2 def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=True , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=None , lowerCAmelCase__="##" , **lowerCAmelCase__ , ) -> Optional[int]: '''simple docstring''' super().__init__( lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , clean_text=lowerCAmelCase__ , tokenize_chinese_chars=lowerCAmelCase__ , strip_accents=lowerCAmelCase__ , wordpieces_prefix=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCAmelCase__ ) != tokenize_chinese_chars ): a__ : List[str] =getattr(lowerCAmelCase__ , normalizer_state.pop("type" ) ) a__ : Union[str, Any] =do_lower_case a__ : Any =strip_accents a__ : Optional[Any] =tokenize_chinese_chars a__ : Dict =normalizer_class(**lowerCAmelCase__ ) a__ : Any =do_lower_case def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__=None ) -> str: '''simple docstring''' a__ : Dict =[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 _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] =[self.sep_token_id] a__ : Union[str, Any] =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Tuple =self._tokenizer.model.save(lowerCAmelCase__ , name=lowerCAmelCase__ ) return tuple(lowerCAmelCase__ )
95
1
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__) class lowerCAmelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): '''simple docstring''' __snake_case = "maskformer-swin" __snake_case = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , _UpperCAmelCase=2_24 , _UpperCAmelCase=4 , _UpperCAmelCase=3 , _UpperCAmelCase=96 , _UpperCAmelCase=[2, 2, 6, 2] , _UpperCAmelCase=[3, 6, 12, 24] , _UpperCAmelCase=7 , _UpperCAmelCase=4.0 , _UpperCAmelCase=True , _UpperCAmelCase=0.0 , _UpperCAmelCase=0.0 , _UpperCAmelCase=0.1 , _UpperCAmelCase="gelu" , _UpperCAmelCase=False , _UpperCAmelCase=0.02 , _UpperCAmelCase=1E-5 , _UpperCAmelCase=None , _UpperCAmelCase=None , **_UpperCAmelCase , ): super().__init__(**_UpperCAmelCase ) snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = embed_dim snake_case_ = depths snake_case_ = len(_UpperCAmelCase ) snake_case_ = num_heads snake_case_ = window_size snake_case_ = mlp_ratio snake_case_ = qkv_bias snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = drop_path_rate snake_case_ = hidden_act snake_case_ = use_absolute_embeddings snake_case_ = layer_norm_eps snake_case_ = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case_ = int(embed_dim * 2 ** (len(_UpperCAmelCase ) - 1) ) snake_case_ = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(_UpperCAmelCase ) + 1 )] snake_case_ , snake_case_ = get_aligned_output_features_output_indices( out_features=_UpperCAmelCase , out_indices=_UpperCAmelCase , stage_names=self.stage_names )
267
import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ ( self ): snake_case_ = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None snake_case_ , snake_case_ = get_aligned_output_features_output_indices(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , ['''c'''] ) self.assertEqual(_UpperCAmelCase , [2] ) # Out indices set to match out features snake_case_ , snake_case_ = get_aligned_output_features_output_indices(['''a''', '''c'''] , _UpperCAmelCase , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''] ) self.assertEqual(_UpperCAmelCase , [0, 2] ) # Out features set to match out indices snake_case_ , snake_case_ = get_aligned_output_features_output_indices(_UpperCAmelCase , [0, 2] , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''] ) self.assertEqual(_UpperCAmelCase , [0, 2] ) # Out features selected from negative indices snake_case_ , snake_case_ = get_aligned_output_features_output_indices(_UpperCAmelCase , [-3, -1] , _UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , ['''a''', '''c'''] ) self.assertEqual(_UpperCAmelCase , [-3, -1] ) def UpperCamelCase__ ( self ): # Stage names must be set with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , _UpperCAmelCase ) # Out features must be a list with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(_UpperCAmelCase , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(_UpperCAmelCase , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(_UpperCAmelCase ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def UpperCamelCase__ ( self ): snake_case_ = BackboneMixin() snake_case_ = ['''a''', '''b''', '''c'''] snake_case_ = ['''a''', '''c'''] snake_case_ = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly snake_case_ = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) snake_case_ = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
267
1
from __future__ import annotations import requests def lowerCAmelCase_ ( _lowercase : str) -> Optional[int]: """simple docstring""" a__ : str = F'''https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty''' return requests.get(_A).json() def lowerCAmelCase_ ( _lowercase : int = 10) -> Optional[Any]: """simple docstring""" a__ : Optional[Any] = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" a__ : Union[str, Any] = requests.get(_A).json()[:max_stories] return [get_hackernews_story(_A) for story_id in story_ids] def lowerCAmelCase_ ( _lowercase : int = 10) -> Any: """simple docstring""" a__ : Optional[Any] = hackernews_top_stories(_A) return "\n".join("""* [{title}]({url})""".format(**_A) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
170
import math import os import sys def lowercase_ ( _A : str ): """simple docstring""" lowerCamelCase__ : str = "" try: with open(_A , "rb" ) as binary_file: lowerCamelCase__ : Union[str, Any] = binary_file.read() for dat in data: lowerCamelCase__ : Optional[Any] = F"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible" ) sys.exit() def lowercase_ ( _A : dict[str, str] , _A : str , _A : int , _A : str ): """simple docstring""" lexicon.pop(_A ) lowerCamelCase__ : List[Any] = last_match_id if math.loga(_A ).is_integer(): for curr_key in lexicon: lowerCamelCase__ : Any = "0" + lexicon[curr_key] lowerCamelCase__ : Tuple = bin(_A )[2:] def lowercase_ ( _A : str ): """simple docstring""" lowerCamelCase__ : Tuple = {"0": "0", "1": "1"} lowerCamelCase__ , lowerCamelCase__ : int = "", "" lowerCamelCase__ : int = len(_A ) for i in range(len(_A ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowerCamelCase__ : Optional[Any] = lexicon[curr_string] result += last_match_id add_key_to_lexicon(_A , _A , _A , _A ) index += 1 lowerCamelCase__ : Dict = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": lowerCamelCase__ : int = lexicon[curr_string] result += last_match_id return result def lowercase_ ( _A : str , _A : str ): """simple docstring""" lowerCamelCase__ : List[str] = os.path.getsize(_A ) lowerCamelCase__ : Dict = bin(_A )[2:] lowerCamelCase__ : List[Any] = len(_A ) return "0" * (length_length - 1) + file_length_binary + compressed def lowercase_ ( _A : str , _A : str ): """simple docstring""" lowerCamelCase__ : Dict = 8 try: with open(_A , "wb" ) as opened_file: lowerCamelCase__ : Any = [ to_write[i : i + byte_length] for i in range(0 , len(_A ) , _A ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append("10000000" ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array: opened_file.write(int(_A , 2 ).to_bytes(1 , byteorder="big" ) ) except OSError: print("File not accessible" ) sys.exit() def lowercase_ ( _A : str , _A : str ): """simple docstring""" lowerCamelCase__ : Dict = read_file_binary(_A ) lowerCamelCase__ : List[Any] = compress_data(_A ) lowerCamelCase__ : str = add_file_length(_A , _A ) write_file_binary(_A , _A ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
184
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu lowercase_ = False class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : int )-> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] )-> Tuple: """simple docstring""" return 12 @property def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Union[str, Any]: """simple docstring""" return 12 @property def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Tuple: """simple docstring""" return 32 @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) lowercase__ = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Dict: """simple docstring""" lowercase__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Optional[int]: """simple docstring""" torch.manual_seed(0 ) lowercase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(__lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] )-> List[Any]: """simple docstring""" torch.manual_seed(0 ) lowercase__ = 12 lowercase__ = 12 lowercase__ = { '''attention_bias''': True, '''cross_attention_dim''': 32, '''attention_head_dim''': height * width, '''num_attention_heads''': 1, '''num_vector_embeds''': self.num_embed, '''num_embeds_ada_norm''': self.num_embeds_ada_norm, '''norm_num_groups''': 32, '''sample_size''': width, '''activation_fn''': '''geglu-approximate''', } lowercase__ = TransformeraDModel(**__lowerCamelCase ) return model def SCREAMING_SNAKE_CASE_ ( self : Tuple )-> Union[str, Any]: """simple docstring""" lowercase__ = '''cpu''' lowercase__ = self.dummy_vqvae lowercase__ = self.dummy_text_encoder lowercase__ = self.dummy_tokenizer lowercase__ = self.dummy_transformer lowercase__ = VQDiffusionScheduler(self.num_embed ) lowercase__ = LearnedClassifierFreeSamplingEmbeddings(learnable=__lowerCamelCase ) lowercase__ = VQDiffusionPipeline( vqvae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , transformer=__lowerCamelCase , scheduler=__lowerCamelCase , learned_classifier_free_sampling_embeddings=__lowerCamelCase , ) lowercase__ = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) lowercase__ = '''teddy bear playing in the pool''' lowercase__ = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) lowercase__ = pipe([prompt] , generator=__lowerCamelCase , num_inference_steps=2 , output_type='np' ) lowercase__ = output.images lowercase__ = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) lowercase__ = pipe( [prompt] , generator=__lowerCamelCase , output_type='np' , return_dict=__lowerCamelCase , num_inference_steps=2 )[0] lowercase__ = image[0, -3:, -3:, -1] lowercase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) lowercase__ = np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def SCREAMING_SNAKE_CASE_ ( self : List[Any] )-> int: """simple docstring""" lowercase__ = '''cpu''' lowercase__ = self.dummy_vqvae lowercase__ = self.dummy_text_encoder lowercase__ = self.dummy_tokenizer lowercase__ = self.dummy_transformer lowercase__ = VQDiffusionScheduler(self.num_embed ) lowercase__ = LearnedClassifierFreeSamplingEmbeddings( learnable=__lowerCamelCase , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) lowercase__ = VQDiffusionPipeline( vqvae=__lowerCamelCase , text_encoder=__lowerCamelCase , tokenizer=__lowerCamelCase , transformer=__lowerCamelCase , scheduler=__lowerCamelCase , learned_classifier_free_sampling_embeddings=__lowerCamelCase , ) lowercase__ = pipe.to(__lowerCamelCase ) pipe.set_progress_bar_config(disable=__lowerCamelCase ) lowercase__ = '''teddy bear playing in the pool''' lowercase__ = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) lowercase__ = pipe([prompt] , generator=__lowerCamelCase , num_inference_steps=2 , output_type='np' ) lowercase__ = output.images lowercase__ = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) lowercase__ = pipe( [prompt] , generator=__lowerCamelCase , output_type='np' , return_dict=__lowerCamelCase , num_inference_steps=2 )[0] lowercase__ = image[0, -3:, -3:, -1] lowercase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) lowercase__ = np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class SCREAMING_SNAKE_CASE (unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self : Dict )-> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self : Dict )-> Union[str, Any]: """simple docstring""" lowercase__ = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy' ) lowercase__ = VQDiffusionPipeline.from_pretrained('microsoft/vq-diffusion-ithq' ) lowercase__ = pipeline.to(__lowerCamelCase ) pipeline.set_progress_bar_config(disable=__lowerCamelCase ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though lowercase__ = torch.Generator(device=__lowerCamelCase ).manual_seed(0 ) lowercase__ = pipeline( 'teddy bear playing in the pool' , num_images_per_prompt=1 , generator=__lowerCamelCase , output_type='np' , ) lowercase__ = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
356
from typing import TYPE_CHECKING from ..utils import _LazyModule lowercase_ = { """config""": [ """EXTERNAL_DATA_FORMAT_SIZE_LIMIT""", """OnnxConfig""", """OnnxConfigWithPast""", """OnnxSeq2SeqConfigWithPast""", """PatchingSpec""", ], """convert""": ["""export""", """validate_model_outputs"""], """features""": ["""FeaturesManager"""], """utils""": ["""ParameterFormat""", """compute_serialized_parameters_size"""], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
269
0
from __future__ import annotations __a :List[str] = list[list[int]] # assigning initial values to the grid __a :Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution __a :Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __snake_case ( __UpperCamelCase : Matrix ,__UpperCamelCase : int ,__UpperCamelCase : int ,__UpperCamelCase : int ): """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" if location := find_empty_location(__UpperCamelCase ): A_ , A_ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ): A_ = digit if sudoku(__UpperCamelCase ) is not None: return grid A_ = 0 return None def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" for row in grid: for cell in row: print(__UpperCamelCase ,end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') __a :Optional[Any] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
312
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def __snake_case ( ): """simple docstring""" A_ = { "repo_name": ["test_repo1", "test_repo2", "test_repo3"], "path": ["test_1.py", "test_2.py", "unit_test.py"], "content": ["a " * 20, "a " * 30, "b " * 7], } A_ = Dataset.from_dict(__UpperCamelCase ) return dataset class _a ( snake_case_ ): """simple docstring""" def __A ( self : Union[str, Any] ): A_ = get_dataset() A_ = make_duplicate_clusters(UpperCAmelCase , 0.85 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def __A ( self : List[Any] ): A_ = get_dataset() A_ , A_ = deduplicate_dataset(UpperCAmelCase ) self.assertEqual(len(UpperCAmelCase ) , 2 ) print(UpperCAmelCase ) self.assertEqual(duplicate_clusters[0][0]["copies"] , 2 ) self.assertEqual(duplicate_clusters[0][0]["is_extreme"] , UpperCAmelCase )
312
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _A = { '''configuration_ernie''': ['''ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ErnieConfig''', '''ErnieOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ErnieForCausalLM''', '''ErnieForMaskedLM''', '''ErnieForMultipleChoice''', '''ErnieForNextSentencePrediction''', '''ErnieForPreTraining''', '''ErnieForQuestionAnswering''', '''ErnieForSequenceClassification''', '''ErnieForTokenClassification''', '''ErnieModel''', '''ErniePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
369
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging _A = logging.get_logger(__name__) def __UpperCamelCase ( _A , _A , _A , _A=False ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a PyTorch model in Flax, 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 if not is_sharded: lowerCAmelCase_ = os.path.abspath(_A ) logger.info(f"Loading PyTorch weights from {pt_path}" ) lowerCAmelCase_ = torch.load(_A , map_location='''cpu''' ) logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters." ) lowerCAmelCase_ = convert_pytorch_state_dict_to_flax(_A , _A ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files lowerCAmelCase_ = convert_pytorch_sharded_state_dict_to_flax(_A , _A ) return flax_state_dict def __UpperCamelCase ( _A , _A , _A , _A , ): def is_key_or_prefix_key_in_dict(_A ) -> bool: return len(set(_A ) & {key, (model_prefix,) + key} ) > 0 # layer norm lowerCAmelCase_ = pt_tuple_key[:-1] + ('''scale''',) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(_A ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean lowerCAmelCase_ = pt_tuple_key[:-1] + ('''mean''',) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(_A ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var lowerCAmelCase_ = pt_tuple_key[:-1] + ('''var''',) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(_A ): return renamed_pt_tuple_key, pt_tensor # embedding lowerCAmelCase_ = pt_tuple_key[:-1] + ('''embedding''',) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(_A ): return renamed_pt_tuple_key, pt_tensor # conv layer lowerCAmelCase_ = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(_A ): lowerCAmelCase_ = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer lowerCAmelCase_ = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(_A ): lowerCAmelCase_ = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight lowerCAmelCase_ = pt_tuple_key[:-1] + ('''weight''',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias lowerCAmelCase_ = pt_tuple_key[:-1] + ('''bias''',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 lowerCAmelCase_ = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): lowerCAmelCase_ = pt_tuple_key[-2] + '''_g''' elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): lowerCAmelCase_ = pt_tuple_key[-2] + '''_v''' if name is not None: lowerCAmelCase_ = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def __UpperCamelCase ( _A , _A ): # convert pytorch tensor to numpy lowerCAmelCase_ = {k: v.numpy() for k, v in pt_state_dict.items()} lowerCAmelCase_ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: lowerCAmelCase_ = flax_model.params['''params'''] else: lowerCAmelCase_ = flax_model.params lowerCAmelCase_ = flatten_dict(_A ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: lowerCAmelCase_ = flatten_dict(flax_model.params['''batch_stats'''] ) random_flax_state_dict.update(_A ) lowerCAmelCase_ = {} lowerCAmelCase_ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) lowerCAmelCase_ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): lowerCAmelCase_ = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary lowerCAmelCase_ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase_ = pt_tuple_key[1:] # Correctly rename weight parameters lowerCAmelCase_ , lowerCAmelCase_ = rename_key_and_reshape_tensor( _A , _A , _A , _A ) # add model prefix if necessary lowerCAmelCase_ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase_ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: lowerCAmelCase_ = jnp.asarray(_A ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_A , _A ) continue # also add unexpected weight so that warning is thrown lowerCAmelCase_ = jnp.asarray(_A ) else: # also add unexpected weight so that warning is thrown lowerCAmelCase_ = jnp.asarray(_A ) return unflatten_dict(_A ) def __UpperCamelCase ( _A , _A ): import torch # Load the index lowerCAmelCase_ = {} for shard_file in shard_filenames: # load using msgpack utils lowerCAmelCase_ = torch.load(_A ) lowerCAmelCase_ = {k: v.numpy() for k, v in pt_state_dict.items()} lowerCAmelCase_ = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: lowerCAmelCase_ = flax_model.params['''params'''] lowerCAmelCase_ = flatten_dict(_A ) random_flax_state_dict.update(flatten_dict(flax_model.params['''batch_stats'''] ) ) else: lowerCAmelCase_ = flax_model.params lowerCAmelCase_ = flatten_dict(_A ) lowerCAmelCase_ = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) lowerCAmelCase_ = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): lowerCAmelCase_ = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary lowerCAmelCase_ = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase_ = pt_tuple_key[1:] # Correctly rename weight parameters lowerCAmelCase_ , lowerCAmelCase_ = rename_key_and_reshape_tensor( _A , _A , _A , _A ) # add model prefix if necessary lowerCAmelCase_ = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase_ = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}." ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: lowerCAmelCase_ = jnp.asarray(_A ) continue if "var" in flax_key[-1]: lowerCAmelCase_ = jnp.asarray(_A ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_A , _A ) continue # also add unexpected weight so that warning is thrown lowerCAmelCase_ = jnp.asarray(_A ) else: # also add unexpected weight so that warning is thrown lowerCAmelCase_ = jnp.asarray(_A ) return unflatten_dict(_A ) def __UpperCamelCase ( _A , _A ): lowerCAmelCase_ = os.path.abspath(_A ) logger.info(f"Loading Flax weights from {flax_checkpoint_path}" ) # import correct flax class lowerCAmelCase_ = getattr(_A , '''Flax''' + model.__class__.__name__ ) # load flax weight dict with open(_A , '''rb''' ) as state_f: try: lowerCAmelCase_ = from_bytes(_A , state_f.read() ) except UnpicklingError: raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. " ) return load_flax_weights_in_pytorch_model(_A , _A ) def __UpperCamelCase ( _A , _A ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a 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 lowerCAmelCase_ = flatten_dict(jax.tree_util.tree_map(lambda _A : x.dtype == jnp.bfloataa , _A ) ).values() if any(_A ): # convert all weights to fp32 if the 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.''' ) lowerCAmelCase_ = jax.tree_util.tree_map( lambda _A : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _A ) lowerCAmelCase_ = flatten_dict(_A ) lowerCAmelCase_ = pt_model.state_dict() lowerCAmelCase_ = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) lowerCAmelCase_ = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys lowerCAmelCase_ = [] lowerCAmelCase_ = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): lowerCAmelCase_ = flax_key_tuple[0] == pt_model.base_model_prefix lowerCAmelCase_ = '''.'''.join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: lowerCAmelCase_ = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: lowerCAmelCase_ = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(_A ) not in pt_model_dict: # conv layer lowerCAmelCase_ = flax_key_tuple[:-1] + ('''weight''',) lowerCAmelCase_ = jnp.transpose(_A , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(_A ) not in pt_model_dict: # linear layer lowerCAmelCase_ = flax_key_tuple[:-1] + ('''weight''',) lowerCAmelCase_ = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: lowerCAmelCase_ = flax_key_tuple[:-1] + ('''weight''',) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: lowerCAmelCase_ = flax_key_tuple[:-1] + ('''running_mean''',) elif "var" in flax_key_tuple[-1]: lowerCAmelCase_ = flax_key_tuple[:-1] + ('''running_var''',) if "batch_stats" in flax_state: lowerCAmelCase_ = '''.'''.join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: lowerCAmelCase_ = '''.'''.join(_A ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. lowerCAmelCase_ = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: lowerCAmelCase_ = key.split('''.''' ) lowerCAmelCase_ = None if key_components[-3::2] == ["parametrizations", "original0"]: lowerCAmelCase_ = key_components[-2] + '''_g''' elif key_components[-3::2] == ["parametrizations", "original1"]: lowerCAmelCase_ = key_components[-2] + '''_v''' if name is not None: lowerCAmelCase_ = key_components[:-3] + [name] lowerCAmelCase_ = '''.'''.join(_A ) lowerCAmelCase_ = key if flax_key in special_pt_names: lowerCAmelCase_ = special_pt_names[flax_key] 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 lowerCAmelCase_ = np.asarray(_A ) if not isinstance(_A , np.ndarray ) else flax_tensor lowerCAmelCase_ = torch.from_numpy(_A ) # remove from missing keys missing_keys.remove(_A ) else: # weight is not expected by PyTorch model unexpected_keys.append(_A ) pt_model.load_state_dict(_A ) # re-transform missing_keys to list lowerCAmelCase_ = list(_A ) if len(_A ) > 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).''' ) else: logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n" ) if len(_A ) > 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.''' ) else: logger.warning( f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" '''If your task is similar to the task the model of the checkpoint was trained on, ''' f"you can already use {pt_model.__class__.__name__} for predictions without further training." ) return pt_model
167
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class lowercase__ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase): UpperCamelCase_ = VQModel UpperCamelCase_ = """sample""" @property def __A ( self : Tuple , UpperCamelCase__ : Any=(32, 32) ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 4 SCREAMING_SNAKE_CASE : Optional[Any] = 3 SCREAMING_SNAKE_CASE : Tuple = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCamelCase__ ) return {"sample": image} @property def __A ( self : List[Any] ): '''simple docstring''' return (3, 32, 32) @property def __A ( self : Union[str, Any] ): '''simple docstring''' return (3, 32, 32) def __A ( self : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 3, } SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_input return init_dict, inputs_dict def __A ( self : Optional[int] ): '''simple docstring''' pass def __A ( self : List[Any] ): '''simple docstring''' pass def __A ( self : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = VQModel.from_pretrained('''fusing/vqgan-dummy''' , output_loading_info=UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(UpperCamelCase__ ) SCREAMING_SNAKE_CASE : List[str] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __A ( self : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = VQModel.from_pretrained('''fusing/vqgan-dummy''' ) model.to(UpperCamelCase__ ).eval() torch.manual_seed(0 ) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0 ) SCREAMING_SNAKE_CASE : Any = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) SCREAMING_SNAKE_CASE : Tuple = image.to(UpperCamelCase__ ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCamelCase__ ).sample SCREAMING_SNAKE_CASE : Dict = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off SCREAMING_SNAKE_CASE : Dict = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1E-3 ) )
182
import pytest import datasets.config from datasets.utils.info_utils import is_small_dataset @pytest.mark.parametrize('''dataset_size''' , [None, 400 * 2**20, 600 * 2**20] ) @pytest.mark.parametrize('''input_in_memory_max_size''' , ['''default''', 0, 100 * 2**20, 900 * 2**20] ) def A ( _lowercase , _lowercase , _lowercase ): if input_in_memory_max_size != "default": monkeypatch.setattr(datasets.config , '''IN_MEMORY_MAX_SIZE''' , _lowercase ) SCREAMING_SNAKE_CASE : Tuple = datasets.config.IN_MEMORY_MAX_SIZE if input_in_memory_max_size == "default": assert in_memory_max_size == 0 else: assert in_memory_max_size == input_in_memory_max_size if dataset_size and in_memory_max_size: SCREAMING_SNAKE_CASE : str = dataset_size < in_memory_max_size else: SCREAMING_SNAKE_CASE : Union[str, Any] = False SCREAMING_SNAKE_CASE : Any = is_small_dataset(_lowercase ) assert result == expected
182
1
"""simple docstring""" import unittest from transformers import DebertaVaConfig, 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 ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class A_ (lowercase__ ): '''simple docstring''' def __init__( self , lowercase_ , lowercase_=13 , lowercase_=7 , lowercase_=True , lowercase_=True , lowercase_=True , lowercase_=True , lowercase_=99 , lowercase_=32 , lowercase_=5 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=512 , lowercase_=16 , lowercase_=2 , lowercase_=0.02 , lowercase_=False , lowercase_=True , lowercase_="None" , lowercase_=3 , lowercase_=4 , lowercase_=None , ): """simple docstring""" UpperCAmelCase_ : Dict = parent UpperCAmelCase_ : Dict = batch_size UpperCAmelCase_ : str = seq_length UpperCAmelCase_ : Tuple = is_training UpperCAmelCase_ : Dict = use_input_mask UpperCAmelCase_ : Optional[Any] = use_token_type_ids UpperCAmelCase_ : Optional[int] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Union[str, Any] = num_hidden_layers UpperCAmelCase_ : List[str] = num_attention_heads UpperCAmelCase_ : Optional[Any] = intermediate_size UpperCAmelCase_ : str = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Union[str, Any] = attention_probs_dropout_prob UpperCAmelCase_ : List[str] = max_position_embeddings UpperCAmelCase_ : Union[str, Any] = type_vocab_size UpperCAmelCase_ : Any = type_sequence_label_size UpperCAmelCase_ : List[str] = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : int = relative_attention UpperCAmelCase_ : str = position_biased_input UpperCAmelCase_ : Tuple = pos_att_type UpperCAmelCase_ : Union[str, Any] = scope def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Optional[int] = None if self.use_input_mask: UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : List[str] = None if self.use_token_type_ids: UpperCAmelCase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : List[Any] = None UpperCAmelCase_ : Optional[int] = None if self.use_labels: UpperCAmelCase_ : Union[str, 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_ : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : str = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self ): """simple docstring""" return DebertaVaConfig( 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 UpperCamelCase__ ( self , lowercase_ ): """simple docstring""" self.parent.assertListEqual(list(result.loss.size() ) , [] ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[Any] = DebertaVaModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : str = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ )[0] UpperCAmelCase_ : Union[str, Any] = model(lowercase_ , token_type_ids=lowercase_ )[0] UpperCAmelCase_ : List[str] = model(lowercase_ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = DebertaVaForMaskedLM(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : Dict = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.num_labels UpperCAmelCase_ : List[str] = DebertaVaForSequenceClassification(lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[Any] = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(lowercase_ ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = self.num_labels UpperCAmelCase_ : str = DebertaVaForTokenClassification(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[str] = model(lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = DebertaVaForQuestionAnswering(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : Tuple = model( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , start_positions=lowercase_ , end_positions=lowercase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ ( self , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ): """simple docstring""" UpperCAmelCase_ : Optional[int] = DebertaVaForMultipleChoice(config=lowercase_ ) model.to(lowercase_ ) model.eval() UpperCAmelCase_ : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : int = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ : Optional[int] = model( lowercase_ , attention_mask=lowercase_ , token_type_ids=lowercase_ , labels=lowercase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Any = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : List[Any] = config_and_inputs UpperCAmelCase_ : Optional[int] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A_ (lowercase__ ,lowercase__ ,unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) SCREAMING_SNAKE_CASE__ : List[str] = ( { """feature-extraction""": DebertaVaModel, """fill-mask""": DebertaVaForMaskedLM, """question-answering""": DebertaVaForQuestionAnswering, """text-classification""": DebertaVaForSequenceClassification, """token-classification""": DebertaVaForTokenClassification, """zero-shot""": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : Optional[int] = False SCREAMING_SNAKE_CASE__ : Optional[int] = False def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : int = DebertaVaModelTester(self ) UpperCAmelCase_ : List[str] = ConfigTester(self , config_class=lowercase_ , hidden_size=37 ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*lowercase_ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[Any] = DebertaVaModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @require_torch @require_sentencepiece @require_tokenizers class A_ (unittest.TestCase ): '''simple docstring''' @unittest.skip(reason="Model not available yet" ) def UpperCamelCase__ ( self ): """simple docstring""" pass @slow def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : str = DebertaVaModel.from_pretrained("microsoft/deberta-v2-xlarge" ) UpperCAmelCase_ : Union[str, Any] = torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) UpperCAmelCase_ : Tuple = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(lowercase_ , attention_mask=lowercase_ )[0] # compare the actual values for a slice. UpperCAmelCase_ : str = torch.tensor( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowercase_ , atol=1E-4 ) , F"""{output[:, 1:4, 1:4]}""" )
23
"""simple docstring""" import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef _a = ( 'This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ' 'library. You can have a look at this example script for pointers: ' 'https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py' ) def __a ( __lowerCamelCase, __lowerCamelCase ): warnings.warn(__lowerCamelCase, __lowerCamelCase ) requires_backends(__lowerCamelCase, "sklearn" ) return (preds == labels).mean() def __a ( __lowerCamelCase, __lowerCamelCase ): warnings.warn(__lowerCamelCase, __lowerCamelCase ) requires_backends(__lowerCamelCase, "sklearn" ) UpperCAmelCase_ : Optional[Any] = simple_accuracy(__lowerCamelCase, __lowerCamelCase ) UpperCAmelCase_ : List[Any] = fa_score(y_true=__lowerCamelCase, y_pred=__lowerCamelCase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def __a ( __lowerCamelCase, __lowerCamelCase ): warnings.warn(__lowerCamelCase, __lowerCamelCase ) requires_backends(__lowerCamelCase, "sklearn" ) UpperCAmelCase_ : Any = pearsonr(__lowerCamelCase, __lowerCamelCase )[0] UpperCAmelCase_ : Optional[Any] = spearmanr(__lowerCamelCase, __lowerCamelCase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): warnings.warn(__lowerCamelCase, __lowerCamelCase ) requires_backends(__lowerCamelCase, "sklearn" ) assert len(__lowerCamelCase ) == len(__lowerCamelCase ), f"""Predictions and labels have mismatched lengths {len(__lowerCamelCase )} and {len(__lowerCamelCase )}""" if task_name == "cola": return {"mcc": matthews_corrcoef(__lowerCamelCase, __lowerCamelCase )} elif task_name == "sst-2": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "mrpc": return acc_and_fa(__lowerCamelCase, __lowerCamelCase ) elif task_name == "sts-b": return pearson_and_spearman(__lowerCamelCase, __lowerCamelCase ) elif task_name == "qqp": return acc_and_fa(__lowerCamelCase, __lowerCamelCase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "qnli": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "rte": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "wnli": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} elif task_name == "hans": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} else: raise KeyError(__lowerCamelCase ) def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): warnings.warn(__lowerCamelCase, __lowerCamelCase ) requires_backends(__lowerCamelCase, "sklearn" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError(f"""Predictions and labels have mismatched lengths {len(__lowerCamelCase )} and {len(__lowerCamelCase )}""" ) if task_name == "xnli": return {"acc": simple_accuracy(__lowerCamelCase, __lowerCamelCase )} else: raise KeyError(__lowerCamelCase )
23
1
'''simple docstring''' def a__ ( a__ , a__ ): """simple docstring""" return x if y == 0 else greatest_common_divisor(a__ , x % y ) def a__ ( a__ , a__ ): """simple docstring""" return (x * y) // greatest_common_divisor(a__ , a__ ) def a__ ( a__ = 20 ): """simple docstring""" __SCREAMING_SNAKE_CASE = 1 for i in range(1 , n + 1 ): __SCREAMING_SNAKE_CASE = lcm(a__ , a__ ) return g if __name__ == "__main__": print(f"""{solution() = }""")
267
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on __SCREAMING_SNAKE_CASE = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) __SCREAMING_SNAKE_CASE = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] __SCREAMING_SNAKE_CASE = {"""unk_token""": """<unk>"""} __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) __SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48145466, 0.4578275, 0.40821073], """image_std""": [0.26862954, 0.26130258, 0.27577711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any ) -> int: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[Any] , **__SCREAMING_SNAKE_CASE : Optional[int] ) -> List[str]: """simple docstring""" return CLIPImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self : Optional[int] ) -> Any: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = CLIPProcessor.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 , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.tokenizer , __SCREAMING_SNAKE_CASE ) 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 , __SCREAMING_SNAKE_CASE ) self.assertIsInstance(processor_fast.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : Optional[int] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) __SCREAMING_SNAKE_CASE = processor(images=__SCREAMING_SNAKE_CASE , 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 UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self : List[str] ) -> Union[str, Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = CLIPProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = """lower newer""" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
267
1
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets __snake_case : List[str] = '\\n@inproceedings{snover-etal-2006-study,\n title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n author = \"Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John\",\n booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n month = aug # \" 8-12\",\n year = \"2006\",\n address = \"Cambridge, Massachusetts, USA\",\n publisher = \"Association for Machine Translation in the Americas\",\n url = \"https://aclanthology.org/2006.amta-papers.25\",\n pages = \"223--231\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n' __snake_case : List[Any] = '\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' __snake_case : Optional[int] = '\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = [\"does this sentence match??\",\n ... \"what about this sentence?\",\n ... \"What did the TER metric user say to the developer?\"]\n >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n ... [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n ... [\"Your jokes are...\", \"...TERrible\"]]\n >>> ter = datasets.load_metric(\"ter\")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCamelCase ( datasets.Metric ): '''simple docstring''' def lowercase__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' if version.parse(scb.__version__ ) < version.parse("""1.4.12""" ): raise ImportWarning( """To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n""" """You can install it with `pip install \"sacrebleu>=1.4.12\"`.""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""http://www.cs.umd.edu/~snover/tercom/""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ), } ) , codebase_urls=["""https://github.com/mjpost/sacreBLEU#ter"""] , reference_urls=[ """https://github.com/jhclark/tercom""", ] , ) def lowercase__ ( self : List[str] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , lowerCAmelCase_ : bool = False , ) -> Dict: '''simple docstring''' A__ : int =len(references[0] ) if any(len(_A ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) A__ : List[Any] =[[refs[i] for refs in references] for i in range(_A )] A__ : Dict =TER( normalized=_A , no_punct=_A , asian_support=_A , case_sensitive=_A , ) A__ : int =sb_ter.corpus_score(_A , _A ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
350
'''simple docstring''' import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class lowerCamelCase : '''simple docstring''' def lowercase__ ( self : Any ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) A__ : str =TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) A__ : int =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) A__ : Union[str, Any] =UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) A__ : Dict =DDPMScheduler( num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0001 , beta_end=0.02 , thresholding=lowerCAmelCase_ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) A__ : Union[str, Any] =IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowercase__ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) A__ : List[Any] =TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) A__ : str =AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) A__ : Dict =UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ """ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D""", ] , mid_block_type="""UNetMidBlock2DSimpleCrossAttn""" , up_block_types=["""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="""text""" , addition_embed_type_num_heads=2 , cross_attention_norm="""group_norm""" , resnet_time_scale_shift="""scale_shift""" , act_fn="""gelu""" , class_embed_type="""timestep""" , mid_block_scale_factor=1.414 , time_embedding_act_fn="""gelu""" , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) A__ : Optional[int] =DDPMScheduler( num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0001 , beta_end=0.02 , thresholding=lowerCAmelCase_ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) A__ : int =DDPMScheduler( num_train_timesteps=10_00 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0001 , beta_end=0.02 , ) torch.manual_seed(0 ) A__ : List[str] =IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowercase__ ( self : str ) -> Tuple: '''simple docstring''' A__ : Tuple =self.get_dummy_components() A__ : str =self.pipeline_class(**lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : Optional[int] =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : str =inputs["""prompt"""] A__ : Optional[int] =inputs["""generator"""] A__ : Optional[Any] =inputs["""num_inference_steps"""] A__ : Union[str, Any] =inputs["""output_type"""] if "image" in inputs: A__ : Union[str, Any] =inputs["""image"""] else: A__ : List[Any] =None if "mask_image" in inputs: A__ : Union[str, Any] =inputs["""mask_image"""] else: A__ : Tuple =None if "original_image" in inputs: A__ : Optional[Any] =inputs["""original_image"""] else: A__ : Tuple =None A__ , A__ : Optional[Any] =pipe.encode_prompt(lowerCAmelCase_ ) # inputs with prompt converted to embeddings A__ : Optional[int] ={ """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: A__ : int =image if mask_image is not None: A__ : Tuple =mask_image if original_image is not None: A__ : Optional[int] =original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) A__ : Any =pipe(**lowerCAmelCase_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCAmelCase_ ) A__ : int =self.pipeline_class.from_pretrained(lowerCAmelCase_ ) pipe_loaded.to(lowerCAmelCase_ ) pipe_loaded.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(lowerCAmelCase_ , lowerCAmelCase_ ) is None , f"`{optional_component}` did not stay set to None after loading." , ) A__ : Dict =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : int =inputs["""generator"""] A__ : str =inputs["""num_inference_steps"""] A__ : Optional[Any] =inputs["""output_type"""] # inputs with prompt converted to embeddings A__ : List[Any] ={ """prompt_embeds""": prompt_embeds, """negative_prompt_embeds""": negative_prompt_embeds, """generator""": generator, """num_inference_steps""": num_inference_steps, """output_type""": output_type, } if image is not None: A__ : int =image if mask_image is not None: A__ : int =mask_image if original_image is not None: A__ : Optional[int] =original_image A__ : List[str] =pipe_loaded(**lowerCAmelCase_ )[0] A__ : Union[str, Any] =np.abs(to_np(lowerCAmelCase_ ) - to_np(lowerCAmelCase_ ) ).max() self.assertLess(lowerCAmelCase_ , 1e-4 ) def lowercase__ ( self : List[str] ) -> Dict: '''simple docstring''' A__ : Union[str, Any] =self.get_dummy_components() A__ : int =self.pipeline_class(**lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) A__ : int =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : List[Any] =pipe(**lowerCAmelCase_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(lowerCAmelCase_ ) A__ : List[Any] =self.pipeline_class.from_pretrained(lowerCAmelCase_ ) pipe_loaded.to(lowerCAmelCase_ ) pipe_loaded.set_progress_bar_config(disable=lowerCAmelCase_ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests A__ : int =self.get_dummy_inputs(lowerCAmelCase_ ) A__ : Tuple =pipe_loaded(**lowerCAmelCase_ )[0] A__ : Tuple =np.abs(to_np(lowerCAmelCase_ ) - to_np(lowerCAmelCase_ ) ).max() self.assertLess(lowerCAmelCase_ , 1e-4 )
136
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class snake_case_ ( unittest.TestCase ): def __UpperCamelCase ( self : str ) -> List[str]: lowercase__ : List[str] = "ZinengTang/tvlt-base" lowercase__ : str = tempfile.mkdtemp() def __UpperCamelCase ( self : str , **lowercase_ : int ) -> Optional[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **lowercase_ ) def __UpperCamelCase ( self : List[str] , **lowercase_ : Optional[Any] ) -> Tuple: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **lowercase_ ) def __UpperCamelCase ( self : str ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self : int ) -> Optional[int]: lowercase__ : int = self.get_image_processor() lowercase__ : Optional[int] = self.get_feature_extractor() lowercase__ : List[Any] = TvltProcessor(image_processor=lowercase_ , feature_extractor=lowercase_ ) processor.save_pretrained(self.tmpdirname ) lowercase__ : Optional[Any] = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , lowercase_ ) self.assertIsInstance(processor.image_processor , lowercase_ ) def __UpperCamelCase ( self : List[str] ) -> List[Any]: lowercase__ : Optional[int] = self.get_image_processor() lowercase__ : Tuple = self.get_feature_extractor() lowercase__ : List[Any] = TvltProcessor(image_processor=lowercase_ , feature_extractor=lowercase_ ) lowercase__ : List[str] = np.ones([1_20_00] ) lowercase__ : int = feature_extractor(lowercase_ , return_tensors="np" ) lowercase__ : Any = processor(audio=lowercase_ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: lowercase__ : Dict = self.get_image_processor() lowercase__ : Union[str, Any] = self.get_feature_extractor() lowercase__ : Tuple = TvltProcessor(image_processor=lowercase_ , feature_extractor=lowercase_ ) lowercase__ : Optional[int] = np.ones([3, 2_24, 2_24] ) lowercase__ : Optional[Any] = image_processor(lowercase_ , return_tensors="np" ) lowercase__ : Optional[int] = processor(images=lowercase_ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __UpperCamelCase ( self : Optional[int] ) -> List[Any]: lowercase__ : Optional[Any] = self.get_image_processor() lowercase__ : List[Any] = self.get_feature_extractor() lowercase__ : Tuple = TvltProcessor(image_processor=lowercase_ , feature_extractor=lowercase_ ) lowercase__ : str = np.ones([1_20_00] ) lowercase__ : Dict = np.ones([3, 2_24, 2_24] ) lowercase__ : Any = processor(audio=lowercase_ , images=lowercase_ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(lowercase_ ): processor() def __UpperCamelCase ( self : List[Any] ) -> Optional[int]: lowercase__ : str = self.get_image_processor() lowercase__ : Dict = self.get_feature_extractor() lowercase__ : List[str] = TvltProcessor(image_processor=lowercase_ , feature_extractor=lowercase_ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
87
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Tuple , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: List[str]=13 , _SCREAMING_SNAKE_CASE: Tuple=7 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Optional[Any]=True , _SCREAMING_SNAKE_CASE: str=False , _SCREAMING_SNAKE_CASE: Optional[Any]=True , _SCREAMING_SNAKE_CASE: int=99 , _SCREAMING_SNAKE_CASE: int=32 , _SCREAMING_SNAKE_CASE: List[str]=5 , _SCREAMING_SNAKE_CASE: Union[str, Any]=4 , _SCREAMING_SNAKE_CASE: int=64 , _SCREAMING_SNAKE_CASE: List[str]="gelu" , _SCREAMING_SNAKE_CASE: str=0.1 , _SCREAMING_SNAKE_CASE: Any=0.1 , _SCREAMING_SNAKE_CASE: Optional[int]=512 , _SCREAMING_SNAKE_CASE: Tuple=16 , _SCREAMING_SNAKE_CASE: Any=2 , _SCREAMING_SNAKE_CASE: List[str]=0.02 , _SCREAMING_SNAKE_CASE: Tuple=3 , _SCREAMING_SNAKE_CASE: Optional[Any]=4 , _SCREAMING_SNAKE_CASE: int=None , _SCREAMING_SNAKE_CASE: int=2 , _SCREAMING_SNAKE_CASE: str=2 , _SCREAMING_SNAKE_CASE: Union[str, Any]=2 , _SCREAMING_SNAKE_CASE: List[Any]=2 , _SCREAMING_SNAKE_CASE: int=4 , _SCREAMING_SNAKE_CASE: List[str]=1 , ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[str] = parent __lowerCAmelCase : Optional[Any] = batch_size __lowerCAmelCase : Union[str, Any] = seq_length __lowerCAmelCase : Optional[Any] = is_training __lowerCAmelCase : Optional[int] = use_input_mask __lowerCAmelCase : Dict = use_token_type_ids __lowerCAmelCase : Dict = use_labels __lowerCAmelCase : Dict = vocab_size __lowerCAmelCase : Tuple = hidden_size __lowerCAmelCase : List[Any] = num_hidden_layers __lowerCAmelCase : Union[str, Any] = num_attention_heads __lowerCAmelCase : Tuple = intermediate_size __lowerCAmelCase : List[Any] = hidden_act __lowerCAmelCase : Optional[Any] = hidden_dropout_prob __lowerCAmelCase : Optional[Any] = attention_probs_dropout_prob __lowerCAmelCase : Optional[int] = max_position_embeddings __lowerCAmelCase : Union[str, Any] = type_vocab_size __lowerCAmelCase : Optional[int] = type_sequence_label_size __lowerCAmelCase : Dict = initializer_range __lowerCAmelCase : Tuple = num_labels __lowerCAmelCase : Optional[Any] = num_choices __lowerCAmelCase : Union[str, Any] = scope __lowerCAmelCase : Optional[Any] = q_groups __lowerCAmelCase : Optional[int] = k_groups __lowerCAmelCase : Any = v_groups __lowerCAmelCase : int = post_attention_groups __lowerCAmelCase : List[str] = intermediate_groups __lowerCAmelCase : Optional[Any] = output_groups def _SCREAMING_SNAKE_CASE ( self: Dict) -> List[str]: """simple docstring""" __lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __lowerCAmelCase : Union[str, Any] = None if self.use_input_mask: __lowerCAmelCase : Tuple = random_attention_mask([self.batch_size, self.seq_length]) __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : List[Any] = None __lowerCAmelCase : str = None if self.use_labels: __lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size) __lowerCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __lowerCAmelCase : str = ids_tensor([self.batch_size] , self.num_choices) __lowerCAmelCase : Any = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _SCREAMING_SNAKE_CASE ( self: Tuple) -> int: """simple docstring""" return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Tuple) -> Tuple: """simple docstring""" __lowerCAmelCase : List[Any] = SqueezeBertModel(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : List[Any] = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = model(_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: str , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: Tuple) -> Dict: """simple docstring""" __lowerCAmelCase : int = SqueezeBertForMaskedLM(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : Dict = 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 _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Dict , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> int: """simple docstring""" __lowerCAmelCase : str = SqueezeBertForQuestionAnswering(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : Union[str, Any] = model( _SCREAMING_SNAKE_CASE , attention_mask=_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 _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Tuple) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = self.num_labels __lowerCAmelCase : Union[str, Any] = SqueezeBertForSequenceClassification(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : int = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int]) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : Dict = self.num_labels __lowerCAmelCase : Optional[int] = SqueezeBertForTokenClassification(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : List[str] = model(_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Optional[int] , _SCREAMING_SNAKE_CASE: Union[str, Any] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any] , _SCREAMING_SNAKE_CASE: int) -> Tuple: """simple docstring""" __lowerCAmelCase : List[str] = self.num_choices __lowerCAmelCase : str = SqueezeBertForMultipleChoice(config=_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() __lowerCAmelCase : int = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() __lowerCAmelCase : Union[str, Any] = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() __lowerCAmelCase : str = model( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def _SCREAMING_SNAKE_CASE ( self: str) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() ((__lowerCAmelCase) , (__lowerCAmelCase) , (__lowerCAmelCase) , (__lowerCAmelCase) , (__lowerCAmelCase) , (__lowerCAmelCase)) : Union[str, Any] = config_and_inputs __lowerCAmelCase : int = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) SCREAMING_SNAKE_CASE = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) SCREAMING_SNAKE_CASE = False SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False def _SCREAMING_SNAKE_CASE ( self: Dict) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Any = SqueezeBertModelTester(self) __lowerCAmelCase : Optional[int] = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , dim=37) def _SCREAMING_SNAKE_CASE ( self: Any) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def _SCREAMING_SNAKE_CASE ( self: Optional[int]) -> Any: """simple docstring""" __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> List[Any]: """simple docstring""" __lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Tuple) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> int: """simple docstring""" __lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Any) -> int: """simple docstring""" __lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> str: """simple docstring""" __lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*_SCREAMING_SNAKE_CASE) @slow def _SCREAMING_SNAKE_CASE ( self: Any) -> Dict: """simple docstring""" for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase : Optional[Any] = SqueezeBertModel.from_pretrained(_SCREAMING_SNAKE_CASE) self.assertIsNotNone(_SCREAMING_SNAKE_CASE) @require_sentencepiece @require_tokenizers @require_torch class A__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self: int) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli") __lowerCAmelCase : List[Any] = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]]) __lowerCAmelCase : List[Any] = model(_SCREAMING_SNAKE_CASE)[0] __lowerCAmelCase : Any = torch.Size((1, 3)) self.assertEqual(output.shape , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = torch.tensor([[0.6401, -0.0349, -0.6041]]) self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-4))
269
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Any = logging.get_logger(__name__) lowercase : str = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class A ( __lowerCAmelCase ): __magic_name__ = '''realm''' def __init__( self , SCREAMING_SNAKE_CASE=30522 , SCREAMING_SNAKE_CASE=768 , SCREAMING_SNAKE_CASE=128 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=12 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=3072 , SCREAMING_SNAKE_CASE="gelu_new" , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1e-12 , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=1e-3 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=320 , SCREAMING_SNAKE_CASE=13353718 , SCREAMING_SNAKE_CASE=5000 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=0 , SCREAMING_SNAKE_CASE=2 , **SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) # Common config A : Union[str, Any] = vocab_size A : Dict = max_position_embeddings A : str = hidden_size A : List[str] = retriever_proj_size A : Optional[Any] = num_hidden_layers A : Union[str, Any] = num_attention_heads A : Tuple = num_candidates A : str = intermediate_size A : Optional[int] = hidden_act A : List[Any] = hidden_dropout_prob A : Union[str, Any] = attention_probs_dropout_prob A : Union[str, Any] = initializer_range A : Union[str, Any] = type_vocab_size A : List[Any] = layer_norm_eps # Reader config A : List[str] = span_hidden_size A : str = max_span_width A : Optional[Any] = reader_layer_norm_eps A : Union[str, Any] = reader_beam_size A : Union[str, Any] = reader_seq_len # Retrieval config A : Union[str, Any] = num_block_records A : int = searcher_beam_size
365
'''simple docstring''' import argparse import os from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_task_guides.py lowercase : Any = 'src/transformers' lowercase : str = 'docs/source/en/tasks' def lowerCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: A : Union[str, Any] = f.readlines() # Find the start prompt. A : List[Any] = 0 while not lines[start_index].startswith(snake_case__ ): start_index += 1 start_index += 1 A : List[str] = start_index while not lines[end_index].startswith(snake_case__ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # This is to make sure the transformers module imported is the one in the repo. lowercase : int = direct_transformers_import(TRANSFORMERS_PATH) lowercase : str = { 'asr.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CTC_MAPPING_NAMES, 'audio_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, 'language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, 'image_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, 'masked_language_modeling.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MASKED_LM_MAPPING_NAMES, 'multiple_choice.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, 'object_detection.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, 'question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, 'semantic_segmentation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, 'sequence_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, 'summarization.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'token_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, 'translation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, 'video_classification.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, 'document_question_answering.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, 'monocular_depth_estimation.md': transformers_module.models.auto.modeling_auto.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, } # This list contains model types used in some task guides that are not in `CONFIG_MAPPING_NAMES` (therefore not in any # `MODEL_MAPPING_NAMES` or any `MODEL_FOR_XXX_MAPPING_NAMES`). lowercase : Optional[int] = { 'summarization.md': ('nllb',), 'translation.md': ('nllb',), } def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' A : int = TASK_GUIDE_TO_MODELS[task_guide] A : List[str] = SPECIAL_TASK_GUIDE_TO_MODEL_TYPES.get(snake_case__ , set() ) A : Union[str, Any] = { code: name for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if (code in model_maping_names or code in special_model_types) } return ", ".join([F'[{name}](../model_doc/{code})' for code, name in model_names.items()] ) + "\n" def lowerCAmelCase_ ( snake_case__ , snake_case__=False ): '''simple docstring''' A, A, A, A : Optional[int] = _find_text_in_file( filename=os.path.join(snake_case__ , snake_case__ ) , start_prompt='''<!--This tip is automatically generated by `make fix-copies`, do not fill manually!-->''' , end_prompt='''<!--End of the generated tip-->''' , ) A : Optional[int] = get_model_list_for_task(snake_case__ ) if current_list != new_list: if overwrite: with open(os.path.join(snake_case__ , snake_case__ ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lines[:start_index] + [new_list] + lines[end_index:] ) else: raise ValueError( F'The list of models that can be used in the {task_guide} guide needs an update. Run `make fix-copies`' ''' to fix this.''' ) if __name__ == "__main__": lowercase : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowercase : List[Any] = parser.parse_args() for task_guide in TASK_GUIDE_TO_MODELS.keys(): check_model_list_for_task(task_guide, args.fix_and_overwrite)
311
0
import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) _UpperCAmelCase : List[str] =logging.getLogger(__name__) @dataclass(frozen=__UpperCAmelCase ) class snake_case__: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str SCREAMING_SNAKE_CASE__ : str SCREAMING_SNAKE_CASE__ : Optional[str] = None SCREAMING_SNAKE_CASE__ : Optional[str] = None SCREAMING_SNAKE_CASE__ : Optional[str] = None @dataclass(frozen=__UpperCAmelCase ) class snake_case__: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[int] SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None SCREAMING_SNAKE_CASE__ : Optional[Union[int, float]] = None SCREAMING_SNAKE_CASE__ : Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class snake_case__( __UpperCAmelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[InputFeatures] def __init__( self , __lowercase , __lowercase , __lowercase , __lowercase = None , __lowercase=False , __lowercase = False , ) -> List[str]: lowerCAmelCase_ : Any = hans_processors[task]() lowerCAmelCase_ : Optional[Any] = os.path.join( _lowerCamelCase , '''cached_{}_{}_{}_{}'''.format( '''dev''' if evaluate else '''train''' , tokenizer.__class__.__name__ , str(_lowerCamelCase ) , _lowerCamelCase , ) , ) lowerCAmelCase_ : List[str] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowerCAmelCase_ : List[Any] = label_list[2], label_list[1] lowerCAmelCase_ : List[str] = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowerCAmelCase_ : Dict = cached_features_file + '''.lock''' with FileLock(_lowerCamelCase ): if os.path.exists(_lowerCamelCase ) and not overwrite_cache: logger.info(f"""Loading features from cached file {cached_features_file}""" ) lowerCAmelCase_ : Optional[Any] = torch.load(_lowerCamelCase ) else: logger.info(f"""Creating features from dataset file at {data_dir}""" ) lowerCAmelCase_ : Tuple = ( processor.get_dev_examples(_lowerCamelCase ) if evaluate else processor.get_train_examples(_lowerCamelCase ) ) logger.info('''Training examples: %s''' , len(_lowerCamelCase ) ) lowerCAmelCase_ : Optional[Any] = hans_convert_examples_to_features(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) logger.info('''Saving features into cached file %s''' , _lowerCamelCase ) torch.save(self.features , _lowerCamelCase ) def __len__( self ) -> Tuple: return len(self.features ) def __getitem__( self , __lowercase ) -> Optional[int]: return self.features[i] def lowercase_ ( self ) -> Any: return self.label_list if is_tf_available(): import tensorflow as tf class snake_case__: '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[InputFeatures] def __init__( self , __lowercase , __lowercase , __lowercase , __lowercase = 1_2_8 , __lowercase=False , __lowercase = False , ) -> str: lowerCAmelCase_ : Optional[Any] = hans_processors[task]() lowerCAmelCase_ : Optional[Any] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) lowerCAmelCase_ : Optional[Any] = label_list[2], label_list[1] lowerCAmelCase_ : Optional[Any] = label_list lowerCAmelCase_ : str = processor.get_dev_examples(_lowerCamelCase ) if evaluate else processor.get_train_examples(_lowerCamelCase ) lowerCAmelCase_ : str = hans_convert_examples_to_features(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc='''convert examples to features''' ): if ex_index % 1_0_0_0_0 == 0: logger.info('''Writing example %d of %d''' % (ex_index, len(_lowerCamelCase )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) lowerCAmelCase_ : Any = tf.data.Dataset.from_generator( _lowerCamelCase , ( { '''example_id''': tf.intaa, '''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa, }, tf.intaa, ) , ( { '''example_id''': tf.TensorShape([] ), '''input_ids''': tf.TensorShape([None, None] ), '''attention_mask''': tf.TensorShape([None, None] ), '''token_type_ids''': tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def lowercase_ ( self ) -> int: return self.dataset def __len__( self ) -> List[str]: return len(self.features ) def __getitem__( self , __lowercase ) -> List[str]: return self.features[i] def lowercase_ ( self ) -> Optional[int]: return self.label_list class snake_case__( __UpperCAmelCase ): '''simple docstring''' def lowercase_ ( self , __lowercase ) -> Dict: return self._create_examples(self._read_tsv(os.path.join(_lowerCamelCase , '''heuristics_train_set.txt''' ) ) , '''train''' ) def lowercase_ ( self , __lowercase ) -> Any: return self._create_examples(self._read_tsv(os.path.join(_lowerCamelCase , '''heuristics_evaluation_set.txt''' ) ) , '''dev''' ) def lowercase_ ( self ) -> Tuple: return ["contradiction", "entailment", "neutral"] def lowercase_ ( self , __lowercase , __lowercase ) -> str: lowerCAmelCase_ : Dict = [] for i, line in enumerate(_lowerCamelCase ): if i == 0: continue lowerCAmelCase_ : Tuple = '''%s-%s''' % (set_type, line[0]) lowerCAmelCase_ : Union[str, Any] = line[5] lowerCAmelCase_ : Optional[Any] = line[6] lowerCAmelCase_ : Optional[int] = line[7][2:] if line[7].startswith('''ex''' ) else line[7] lowerCAmelCase_ : List[Any] = line[0] examples.append(InputExample(guid=_lowerCamelCase , text_a=_lowerCamelCase , text_b=_lowerCamelCase , label=_lowerCamelCase , pairID=_lowerCamelCase ) ) return examples def lowerCAmelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , )-> Dict: lowerCAmelCase_ : Optional[Any] = {label: i for i, label in enumerate(_UpperCAmelCase )} lowerCAmelCase_ : List[str] = [] for ex_index, example in tqdm.tqdm(enumerate(_UpperCAmelCase ) , desc='''convert examples to features''' ): if ex_index % 10_000 == 0: logger.info('''Writing example %d''' % (ex_index) ) lowerCAmelCase_ : List[Any] = tokenizer( example.text_a , example.text_b , add_special_tokens=_UpperCAmelCase , max_length=_UpperCAmelCase , padding='''max_length''' , truncation=_UpperCAmelCase , return_overflowing_tokens=_UpperCAmelCase , ) lowerCAmelCase_ : List[str] = label_map[example.label] if example.label in label_map else 0 lowerCAmelCase_ : Any = int(example.pairID ) features.append(InputFeatures(**_UpperCAmelCase , label=_UpperCAmelCase , pairID=_UpperCAmelCase ) ) for i, example in enumerate(examples[:5] ): logger.info('''*** Example ***''' ) logger.info(f"""guid: {example}""" ) logger.info(f"""features: {features[i]}""" ) return features _UpperCAmelCase : Dict ={ 'hans': 3, } _UpperCAmelCase : List[str] ={ 'hans': HansProcessor, }
262
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : Dict = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = ['model.decoder.embed_positions.weights'] def lowercase_ ( _UpperCAmelCase ): """simple docstring""" if "emb" in name: A_ : Tuple = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: A_ : Optional[int] = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: A_ : Optional[Any] = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: A_ : int = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: A_ : Optional[int] = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: A_ : Any = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: A_ : Any = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: A_ : Dict = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: A_ : Tuple = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: A_ : Union[str, Any] = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: A_ : Tuple = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : List[Any] = list(state_dict.keys() ) A_ : List[Any] = {} for key in keys: A_ : List[str] = state_dict.pop(_UpperCAmelCase ) A_ : Tuple = rename_keys(_UpperCAmelCase ) if "in_proj_weight" in key: # split fused qkv proj A_ : Any = val[:hidden_size, :] A_ : Optional[int] = val[hidden_size : 2 * hidden_size, :] A_ : Union[str, Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: A_ : List[str] = val else: A_ : int = val return state_dict, enc_dec_proj_state_dict def lowercase_ ( _UpperCAmelCase ): """simple docstring""" if checkpoint == "small": # default config values A_ : Optional[Any] = 1024 A_ : Tuple = 24 A_ : int = 16 elif checkpoint == "medium": A_ : Any = 1536 A_ : Union[str, Any] = 48 A_ : List[Any] = 24 elif checkpoint == "large": A_ : Optional[int] = 2048 A_ : Optional[int] = 48 A_ : Tuple = 32 else: raise ValueError(f"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) A_ : Tuple = MusicgenDecoderConfig( hidden_size=_UpperCAmelCase , ffn_dim=hidden_size * 4 , num_hidden_layers=_UpperCAmelCase , num_attention_heads=_UpperCAmelCase , ) return config @torch.no_grad() def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase="cpu" ): """simple docstring""" A_ : Any = MusicGen.get_pretrained(_UpperCAmelCase , device=_UpperCAmelCase ) A_ : str = decoder_config_from_checkpoint(_UpperCAmelCase ) A_ : Optional[int] = fairseq_model.lm.state_dict() A_ , A_ : str = rename_state_dict( _UpperCAmelCase , hidden_size=decoder_config.hidden_size ) A_ : List[str] = TaEncoderModel.from_pretrained('''t5-base''' ) A_ : Tuple = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) A_ : Union[str, Any] = MusicgenForCausalLM(_UpperCAmelCase ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection A_ , A_ : Tuple = decoder.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: raise ValueError(f"""Missing key(s) in state_dict: {missing_keys}""" ) if len(_UpperCAmelCase ) > 0: raise ValueError(f"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model A_ : Tuple = MusicgenForConditionalGeneration(text_encoder=_UpperCAmelCase , audio_encoder=_UpperCAmelCase , decoder=_UpperCAmelCase ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(_UpperCAmelCase ) # check we can do a forward pass A_ : List[str] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) A_ : Union[str, Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): A_ : Tuple = model(input_ids=_UpperCAmelCase , decoder_input_ids=_UpperCAmelCase ).logits if logits.shape != (8, 1, 2048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor A_ : str = AutoTokenizer.from_pretrained('''t5-base''' ) A_ : int = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) A_ : Optional[int] = MusicgenProcessor(feature_extractor=_UpperCAmelCase , tokenizer=_UpperCAmelCase ) # set the appropriate bos/pad token ids A_ : Tuple = 2048 A_ : Union[str, Any] = 2048 # set other default generation config params A_ : Union[str, Any] = int(30 * audio_encoder.config.frame_rate ) A_ : List[str] = True A_ : List[str] = 3.0 if pytorch_dump_folder is not None: Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) logger.info(f"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(_UpperCAmelCase ) processor.save_pretrained(_UpperCAmelCase ) if repo_id: logger.info(f"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(_UpperCAmelCase ) processor.push_to_hub(_UpperCAmelCase ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint', default='small', type=str, help='Checkpoint size of the MusicGen model you\'d like to convert. Can be one of: `[\'small\', \'medium\', \'large\']`.', ) parser.add_argument( '--pytorch_dump_folder', required=True, default=None, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) parser.add_argument( '--device', default='cpu', type=str, help='Torch device to run the conversion, either cpu or cuda.' ) _lowerCamelCase : Optional[Any] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
167
0
'''simple docstring''' import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ :Optional[Any] = RoCBertTokenizer lowerCamelCase_ :Dict = None lowerCamelCase_ :List[Any] = False lowerCamelCase_ :Any = True lowerCamelCase_ :Union[str, Any] = filter_non_english def _UpperCamelCase ( self ): '''simple docstring''' super().setUp() UpperCAmelCase_ : Optional[Any] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] UpperCAmelCase_ : Tuple = {} UpperCAmelCase_ : Union[str, Any] = {} for i, value in enumerate(snake_case_ ): UpperCAmelCase_ : List[Any] = i UpperCAmelCase_ : Union[str, Any] = i UpperCAmelCase_ : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) UpperCAmelCase_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(snake_case_ , snake_case_ , ensure_ascii=snake_case_ ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(snake_case_ , snake_case_ , ensure_ascii=snake_case_ ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCAmelCase_ : Dict = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(snake_case_ , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(snake_case_ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(snake_case_ ) , [5, 6, 2, 5, 7, 8] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Optional[Any] = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : List[str] = RoCBertBasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = RoCBertBasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : str = RoCBertBasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : int = RoCBertBasicTokenizer(do_lower_case=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Any = RoCBertBasicTokenizer(do_lower_case=snake_case_ , strip_accents=snake_case_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : List[Any] = RoCBertBasicTokenizer(do_lower_case=snake_case_ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Dict = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] UpperCAmelCase_ : Tuple = {} for i, token in enumerate(snake_case_ ): UpperCAmelCase_ : str = i UpperCAmelCase_ : Tuple = RoCBertWordpieceTokenizer(vocab=snake_case_ , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def _UpperCamelCase ( self ): '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def _UpperCamelCase ( self ): '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def _UpperCamelCase ( self ): '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : int = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(snake_case_ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: UpperCAmelCase_ : Union[str, Any] = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(snake_case_ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def _UpperCamelCase ( self ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase_ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) UpperCAmelCase_ : Tuple = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' UpperCAmelCase_ : Any = tokenizer_r.encode_plus( snake_case_ , return_attention_mask=snake_case_ , return_token_type_ids=snake_case_ , return_offsets_mapping=snake_case_ , add_special_tokens=snake_case_ , ) UpperCAmelCase_ : List[str] = tokenizer_r.do_lower_case if hasattr(snake_case_ , 'do_lower_case' ) else False UpperCAmelCase_ : int = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), 'Allen'), ((2_1, 2_3), '##NL'), ((2_3, 2_4), '##P'), ((2_5, 3_3), 'sentence'), ((3_3, 3_4), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), 'allen'), ((2_1, 2_3), '##nl'), ((2_3, 2_4), '##p'), ((2_5, 3_3), 'sentence'), ((3_3, 3_4), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : List[Any] = ['的', '人', '有'] UpperCAmelCase_ : Any = ''.join(snake_case_ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): UpperCAmelCase_ : List[Any] = True UpperCAmelCase_ : Optional[int] = self.tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) UpperCAmelCase_ : Tuple = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) UpperCAmelCase_ : Dict = tokenizer_p.encode(snake_case_ , add_special_tokens=snake_case_ ) UpperCAmelCase_ : Tuple = tokenizer_r.encode(snake_case_ , add_special_tokens=snake_case_ ) UpperCAmelCase_ : Tuple = tokenizer_r.convert_ids_to_tokens(snake_case_ ) UpperCAmelCase_ : str = tokenizer_p.convert_ids_to_tokens(snake_case_ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) UpperCAmelCase_ : List[Any] = False UpperCAmelCase_ : List[Any] = self.rust_tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) UpperCAmelCase_ : int = self.tokenizer_class.from_pretrained(snake_case_ , **snake_case_ ) UpperCAmelCase_ : str = tokenizer_r.encode(snake_case_ , add_special_tokens=snake_case_ ) UpperCAmelCase_ : List[str] = tokenizer_p.encode(snake_case_ , add_special_tokens=snake_case_ ) UpperCAmelCase_ : List[Any] = tokenizer_r.convert_ids_to_tokens(snake_case_ ) UpperCAmelCase_ : Optional[Any] = tokenizer_p.convert_ids_to_tokens(snake_case_ ) # it is expected that only the first Chinese character is not preceded by "##". UpperCAmelCase_ : Dict = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(snake_case_ ) ] self.assertListEqual(snake_case_ , snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) @slow def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) UpperCAmelCase_ : Optional[Any] = tokenizer.encode('你好' , add_special_tokens=snake_case_ ) UpperCAmelCase_ : Tuple = tokenizer.encode('你是谁' , add_special_tokens=snake_case_ ) UpperCAmelCase_ : List[Any] = tokenizer.build_inputs_with_special_tokens(snake_case_ ) UpperCAmelCase_ : Optional[Any] = tokenizer.build_inputs_with_special_tokens(snake_case_ , snake_case_ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : str = self.get_tokenizers(do_lower_case=snake_case_ ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): UpperCAmelCase_ : Union[str, Any] = '你好,你是谁' UpperCAmelCase_ : str = tokenizer.tokenize(snake_case_ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.convert_tokens_to_ids(snake_case_ ) UpperCAmelCase_ : Dict = tokenizer.convert_tokens_to_shape_ids(snake_case_ ) UpperCAmelCase_ : Dict = tokenizer.convert_tokens_to_pronunciation_ids(snake_case_ ) UpperCAmelCase_ : int = tokenizer.prepare_for_model( snake_case_ , snake_case_ , snake_case_ , add_special_tokens=snake_case_ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.encode_plus(snake_case_ , add_special_tokens=snake_case_ ) self.assertEqual(snake_case_ , snake_case_ )
274
'''simple docstring''' from manim import * class __SCREAMING_SNAKE_CASE ( lowerCamelCase_ ): '''simple docstring''' def _UpperCamelCase ( self ): '''simple docstring''' UpperCAmelCase_ : Dict = Rectangle(height=0.5 , width=0.5 ) UpperCAmelCase_ : Any = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCAmelCase_ : List[str] = Rectangle(height=0.25 , width=0.25 ) UpperCAmelCase_ : Any = [mem.copy() for i in range(6 )] UpperCAmelCase_ : Union[str, Any] = [mem.copy() for i in range(6 )] UpperCAmelCase_ : Optional[int] = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : Any = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : str = VGroup(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : Any = Text('CPU' , font_size=2_4 ) UpperCAmelCase_ : Tuple = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(snake_case_ ) UpperCAmelCase_ : str = [mem.copy() for i in range(4 )] UpperCAmelCase_ : Dict = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : List[str] = Text('GPU' , font_size=2_4 ) UpperCAmelCase_ : Optional[int] = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) gpu.move_to([-1, -1, 0] ) self.add(snake_case_ ) UpperCAmelCase_ : str = [mem.copy() for i in range(6 )] UpperCAmelCase_ : Tuple = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : str = Text('Model' , font_size=2_4 ) UpperCAmelCase_ : Optional[int] = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) model.move_to([3, -1.0, 0] ) self.add(snake_case_ ) UpperCAmelCase_ : str = [] UpperCAmelCase_ : Optional[Any] = [] for i, rect in enumerate(snake_case_ ): UpperCAmelCase_ : str = fill.copy().set_fill(snake_case_ , opacity=0.8 ) target.move_to(snake_case_ ) model_arr.append(snake_case_ ) UpperCAmelCase_ : int = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(snake_case_ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(snake_case_ ) self.add(*snake_case_ , *snake_case_ ) UpperCAmelCase_ : List[Any] = [meta_mem.copy() for i in range(6 )] UpperCAmelCase_ : List[str] = [meta_mem.copy() for i in range(6 )] UpperCAmelCase_ : Tuple = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : Dict = VGroup(*snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : Optional[Any] = VGroup(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0 ) UpperCAmelCase_ : Tuple = Text('Disk' , font_size=2_4 ) UpperCAmelCase_ : Union[str, Any] = Group(snake_case_ , snake_case_ ).arrange(snake_case_ , buff=0.5 , aligned_edge=snake_case_ ) disk.move_to([-4, -1.25, 0] ) self.add(snake_case_ , snake_case_ ) UpperCAmelCase_ : List[Any] = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCAmelCase_ : Any = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) self.add(snake_case_ , snake_case_ ) UpperCAmelCase_ : Dict = MarkupText( F'''<span fgcolor=\'{BLUE}\'>●</span> Checkpoint''' , font_size=1_8 , ) blue_text.next_to(snake_case_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(snake_case_ ) UpperCAmelCase_ : Optional[Any] = MarkupText( F'''Now watch as an input is passed through the model\nand how the memory is utilized and handled.''' , font_size=2_4 , ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case_ ) ) UpperCAmelCase_ : Tuple = Square(0.3 ) input.set_fill(snake_case_ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , snake_case_ , buff=0.5 ) self.play(Write(snake_case_ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=snake_case_ , buff=0.02 ) self.play(MoveToTarget(snake_case_ ) ) self.play(FadeOut(snake_case_ ) ) UpperCAmelCase_ : Any = Arrow(start=snake_case_ , end=snake_case_ , color=snake_case_ , buff=0.5 ) a.next_to(model_arr[0].get_left() , snake_case_ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) UpperCAmelCase_ : List[str] = MarkupText( F'''As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.''' , font_size=2_4 , ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case_ , run_time=3 ) ) UpperCAmelCase_ : List[Any] = {'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.02} self.play( Write(snake_case_ ) , Circumscribe(model_arr[0] , color=snake_case_ , **snake_case_ ) , Circumscribe(model_cpu_arr[0] , color=snake_case_ , **snake_case_ ) , Circumscribe(gpu_rect[0] , color=snake_case_ , **snake_case_ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) UpperCAmelCase_ : Union[str, Any] = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , snake_case_ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) UpperCAmelCase_ : Tuple = AnimationGroup( FadeOut(snake_case_ , run_time=0.5 ) , MoveToTarget(snake_case_ , run_time=0.5 ) , FadeIn(snake_case_ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(snake_case_ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: UpperCAmelCase_ : Any = 0.7 self.play( Circumscribe(model_arr[i] , **snake_case_ ) , Circumscribe(cpu_left_col_base[i] , **snake_case_ ) , Circumscribe(cpu_left_col_base[i + 1] , color=snake_case_ , **snake_case_ ) , Circumscribe(gpu_rect[0] , color=snake_case_ , **snake_case_ ) , Circumscribe(model_arr[i + 1] , color=snake_case_ , **snake_case_ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=snake_case_ , **snake_case_ ) , Circumscribe(cpu_left_col_base[-1] , color=snake_case_ , **snake_case_ ) , Circumscribe(gpu_rect[0] , color=snake_case_ , **snake_case_ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) UpperCAmelCase_ : Any = a_c UpperCAmelCase_ : int = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(snake_case_ ) , FadeOut(snake_case_ , run_time=0.5 ) , ) UpperCAmelCase_ : Optional[Any] = MarkupText(F'''Inference on a model too large for GPU memory\nis successfully completed.''' , font_size=2_4 ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case_ , run_time=3 ) , MoveToTarget(snake_case_ ) ) self.wait()
274
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class SCREAMING_SNAKE_CASE( A__ ): """simple docstring""" lowerCamelCase__ = 42 lowerCamelCase__ = 42 def __init__( self : Union[str, Any] , __snake_case : UNetaDModel , __snake_case : ScoreSdeVeScheduler ) -> int: super().__init__() self.register_modules(unet=__snake_case , scheduler=__snake_case ) @torch.no_grad() def __call__( self : Optional[int] , __snake_case : int = 1 , __snake_case : int = 2000 , __snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , **__snake_case : Optional[int] , ) -> Union[ImagePipelineOutput, Tuple]: UpperCAmelCase : str = self.unet.config.sample_size UpperCAmelCase : Union[str, Any] = (batch_size, 3, img_size, img_size) UpperCAmelCase : int = self.unet UpperCAmelCase : Any = randn_tensor(__snake_case , generator=__snake_case ) * self.scheduler.init_noise_sigma UpperCAmelCase : List[Any] = sample.to(self.device ) self.scheduler.set_timesteps(__snake_case ) self.scheduler.set_sigmas(__snake_case ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): UpperCAmelCase : Any = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): UpperCAmelCase : Union[str, Any] = self.unet(__snake_case , __snake_case ).sample UpperCAmelCase : Optional[Any] = self.scheduler.step_correct(__snake_case , __snake_case , generator=__snake_case ).prev_sample # prediction step UpperCAmelCase : Optional[Any] = model(__snake_case , __snake_case ).sample UpperCAmelCase : List[str] = self.scheduler.step_pred(__snake_case , __snake_case , __snake_case , generator=__snake_case ) UpperCAmelCase , UpperCAmelCase : Optional[Any] = output.prev_sample, output.prev_sample_mean UpperCAmelCase : int = sample_mean.clamp(0 , 1 ) UpperCAmelCase : Union[str, Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": UpperCAmelCase : Optional[Any] = self.numpy_to_pil(__snake_case ) if not return_dict: return (sample,) return ImagePipelineOutput(images=__snake_case )
23
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase__: Optional[int] = logging.get_logger(__name__) def snake_case_ ( _lowerCAmelCase : Optional[int] ) -> Optional[int]: UpperCAmelCase : Tuple = DPTConfig(embedding_type='''hybrid''' ) if "large" in checkpoint_url: UpperCAmelCase : Tuple = 1024 UpperCAmelCase : List[Any] = 4096 UpperCAmelCase : str = 24 UpperCAmelCase : List[Any] = 16 UpperCAmelCase : str = [5, 11, 17, 23] UpperCAmelCase : List[Any] = [256, 512, 1024, 1024] UpperCAmelCase : Tuple = (1, 384, 384) if "nyu" or "midas" in checkpoint_url: UpperCAmelCase : Optional[Any] = 768 UpperCAmelCase : Tuple = [1, 1, 1, 0.5] UpperCAmelCase : int = [256, 512, 768, 768] UpperCAmelCase : Any = 150 UpperCAmelCase : Tuple = 16 UpperCAmelCase : Any = (1, 384, 384) UpperCAmelCase : Optional[Any] = False UpperCAmelCase : Tuple = '''project''' if "ade" in checkpoint_url: UpperCAmelCase : Any = True UpperCAmelCase : str = 768 UpperCAmelCase : Optional[int] = [1, 1, 1, 0.5] UpperCAmelCase : List[Any] = 150 UpperCAmelCase : List[Any] = 16 UpperCAmelCase : str = '''huggingface/label-files''' UpperCAmelCase : Tuple = '''ade20k-id2label.json''' UpperCAmelCase : Any = json.load(open(cached_download(hf_hub_url(_lowerCAmelCase , _lowerCAmelCase , repo_type='''dataset''' ) ) , '''r''' ) ) UpperCAmelCase : Optional[Any] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} UpperCAmelCase : List[Any] = idalabel UpperCAmelCase : Optional[int] = {v: k for k, v in idalabel.items()} UpperCAmelCase : Union[str, Any] = [1, 150, 480, 480] return config, expected_shape def snake_case_ ( _lowerCAmelCase : Union[str, Any] ) -> int: UpperCAmelCase : List[str] = ['''pretrained.model.head.weight''', '''pretrained.model.head.bias'''] for k in ignore_keys: state_dict.pop(_lowerCAmelCase , _lowerCAmelCase ) def snake_case_ ( _lowerCAmelCase : Tuple ) -> Any: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): UpperCAmelCase : Tuple = name.replace('''pretrained.model''' , '''dpt.encoder''' ) if "pretrained.model" in name: UpperCAmelCase : Union[str, Any] = name.replace('''pretrained.model''' , '''dpt.embeddings''' ) if "patch_embed" in name: UpperCAmelCase : int = name.replace('''patch_embed''' , '''''' ) if "pos_embed" in name: UpperCAmelCase : Tuple = name.replace('''pos_embed''' , '''position_embeddings''' ) if "attn.proj" in name: UpperCAmelCase : Any = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "proj" in name and "project" not in name: UpperCAmelCase : str = name.replace('''proj''' , '''projection''' ) if "blocks" in name: UpperCAmelCase : Any = name.replace('''blocks''' , '''layer''' ) if "mlp.fc1" in name: UpperCAmelCase : Optional[int] = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: UpperCAmelCase : Optional[Any] = name.replace('''mlp.fc2''' , '''output.dense''' ) if "norm1" in name and "backbone" not in name: UpperCAmelCase : Dict = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name and "backbone" not in name: UpperCAmelCase : Tuple = name.replace('''norm2''' , '''layernorm_after''' ) if "scratch.output_conv" in name: UpperCAmelCase : Tuple = name.replace('''scratch.output_conv''' , '''head''' ) if "scratch" in name: UpperCAmelCase : str = name.replace('''scratch''' , '''neck''' ) if "layer1_rn" in name: UpperCAmelCase : Dict = name.replace('''layer1_rn''' , '''convs.0''' ) if "layer2_rn" in name: UpperCAmelCase : int = name.replace('''layer2_rn''' , '''convs.1''' ) if "layer3_rn" in name: UpperCAmelCase : Tuple = name.replace('''layer3_rn''' , '''convs.2''' ) if "layer4_rn" in name: UpperCAmelCase : int = name.replace('''layer4_rn''' , '''convs.3''' ) if "refinenet" in name: UpperCAmelCase : List[str] = int(name[len('''neck.refinenet''' ) : len('''neck.refinenet''' ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 UpperCAmelCase : str = name.replace(f"""refinenet{layer_idx}""" , f"""fusion_stage.layers.{abs(layer_idx-4 )}""" ) if "out_conv" in name: UpperCAmelCase : List[str] = name.replace('''out_conv''' , '''projection''' ) if "resConfUnit1" in name: UpperCAmelCase : Union[str, Any] = name.replace('''resConfUnit1''' , '''residual_layer1''' ) if "resConfUnit2" in name: UpperCAmelCase : Any = name.replace('''resConfUnit2''' , '''residual_layer2''' ) if "conv1" in name: UpperCAmelCase : Optional[int] = name.replace('''conv1''' , '''convolution1''' ) if "conv2" in name: UpperCAmelCase : Tuple = name.replace('''conv2''' , '''convolution2''' ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: UpperCAmelCase : Dict = name.replace('''pretrained.act_postprocess1.0.project.0''' , '''neck.reassemble_stage.readout_projects.0.0''' ) if "pretrained.act_postprocess2.0.project.0" in name: UpperCAmelCase : int = name.replace('''pretrained.act_postprocess2.0.project.0''' , '''neck.reassemble_stage.readout_projects.1.0''' ) if "pretrained.act_postprocess3.0.project.0" in name: UpperCAmelCase : Any = name.replace('''pretrained.act_postprocess3.0.project.0''' , '''neck.reassemble_stage.readout_projects.2.0''' ) if "pretrained.act_postprocess4.0.project.0" in name: UpperCAmelCase : Optional[Any] = name.replace('''pretrained.act_postprocess4.0.project.0''' , '''neck.reassemble_stage.readout_projects.3.0''' ) # resize blocks if "pretrained.act_postprocess1.3" in name: UpperCAmelCase : List[Any] = name.replace('''pretrained.act_postprocess1.3''' , '''neck.reassemble_stage.layers.0.projection''' ) if "pretrained.act_postprocess1.4" in name: UpperCAmelCase : Any = name.replace('''pretrained.act_postprocess1.4''' , '''neck.reassemble_stage.layers.0.resize''' ) if "pretrained.act_postprocess2.3" in name: UpperCAmelCase : Optional[int] = name.replace('''pretrained.act_postprocess2.3''' , '''neck.reassemble_stage.layers.1.projection''' ) if "pretrained.act_postprocess2.4" in name: UpperCAmelCase : str = name.replace('''pretrained.act_postprocess2.4''' , '''neck.reassemble_stage.layers.1.resize''' ) if "pretrained.act_postprocess3.3" in name: UpperCAmelCase : List[str] = name.replace('''pretrained.act_postprocess3.3''' , '''neck.reassemble_stage.layers.2.projection''' ) if "pretrained.act_postprocess4.3" in name: UpperCAmelCase : Tuple = name.replace('''pretrained.act_postprocess4.3''' , '''neck.reassemble_stage.layers.3.projection''' ) if "pretrained.act_postprocess4.4" in name: UpperCAmelCase : int = name.replace('''pretrained.act_postprocess4.4''' , '''neck.reassemble_stage.layers.3.resize''' ) if "pretrained" in name: UpperCAmelCase : Optional[int] = name.replace('''pretrained''' , '''dpt''' ) if "bn" in name: UpperCAmelCase : Dict = name.replace('''bn''' , '''batch_norm''' ) if "head" in name: UpperCAmelCase : Any = name.replace('''head''' , '''head.head''' ) if "encoder.norm" in name: UpperCAmelCase : Optional[int] = name.replace('''encoder.norm''' , '''layernorm''' ) if "auxlayer" in name: UpperCAmelCase : Union[str, Any] = name.replace('''auxlayer''' , '''auxiliary_head.head''' ) if "backbone" in name: UpperCAmelCase : List[Any] = name.replace('''backbone''' , '''backbone.bit.encoder''' ) if ".." in name: UpperCAmelCase : Optional[int] = name.replace('''..''' , '''.''' ) if "stem.conv" in name: UpperCAmelCase : Optional[Any] = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: UpperCAmelCase : Optional[int] = name.replace('''blocks''' , '''layers''' ) if "convolution" in name and "backbone" in name: UpperCAmelCase : List[Any] = name.replace('''convolution''' , '''conv''' ) if "layer" in name and "backbone" in name: UpperCAmelCase : List[str] = name.replace('''layer''' , '''layers''' ) if "backbone.bit.encoder.bit" in name: UpperCAmelCase : List[Any] = name.replace('''backbone.bit.encoder.bit''' , '''backbone.bit''' ) if "embedder.conv" in name: UpperCAmelCase : List[Any] = name.replace('''embedder.conv''' , '''embedder.convolution''' ) if "backbone.bit.encoder.stem.norm" in name: UpperCAmelCase : Tuple = name.replace('''backbone.bit.encoder.stem.norm''' , '''backbone.bit.embedder.norm''' ) return name def snake_case_ ( _lowerCAmelCase : List[str] , _lowerCAmelCase : List[Any] ) -> Optional[Any]: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase : Optional[int] = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.weight""" ) UpperCAmelCase : Tuple = state_dict.pop(f"""dpt.encoder.layer.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase : Tuple = in_proj_weight[: config.hidden_size, :] UpperCAmelCase : int = in_proj_bias[: config.hidden_size] UpperCAmelCase : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase : List[str] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase : str = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase : Union[str, Any] = in_proj_bias[-config.hidden_size :] def snake_case_ ( ) -> List[str]: UpperCAmelCase : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase : Optional[int] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def snake_case_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[str] ) -> Any: UpperCAmelCase , UpperCAmelCase : int = get_dpt_config(_lowerCAmelCase ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") UpperCAmelCase : List[Any] = torch.load(_lowerCAmelCase , map_location='''cpu''' ) # remove certain keys remove_ignore_keys_(_lowerCAmelCase ) # rename keys for key in state_dict.copy().keys(): UpperCAmelCase : Any = state_dict.pop(_lowerCAmelCase ) UpperCAmelCase : List[Any] = val # read in qkv matrices read_in_q_k_v(_lowerCAmelCase , _lowerCAmelCase ) # load HuggingFace model UpperCAmelCase : Optional[Any] = DPTForSemanticSegmentation(_lowerCAmelCase ) if '''ade''' in checkpoint_url else DPTForDepthEstimation(_lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase ) model.eval() # Check outputs on an image UpperCAmelCase : int = 480 if '''ade''' in checkpoint_url else 384 UpperCAmelCase : List[Any] = DPTImageProcessor(size=_lowerCAmelCase ) UpperCAmelCase : Dict = prepare_img() UpperCAmelCase : Optional[int] = image_processor(_lowerCAmelCase , return_tensors='''pt''' ) # forward pass UpperCAmelCase : Any = model(**_lowerCAmelCase ).logits if '''ade''' in checkpoint_url else model(**_lowerCAmelCase ).predicted_depth if show_prediction: UpperCAmelCase : Dict = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode='''bicubic''' , align_corners=_lowerCAmelCase , ) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 255 ).show() if pytorch_dump_folder_path is not None: Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_lowerCAmelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_lowerCAmelCase ) if push_to_hub: model.push_to_hub('''ybelkada/dpt-hybrid-midas''' ) image_processor.push_to_hub('''ybelkada/dpt-hybrid-midas''' ) if __name__ == "__main__": UpperCamelCase__: Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", type=str, help="URL of the original DPT checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", ) parser.add_argument( "--model_name", default="dpt-large", type=str, help="Name of the model, in case you're pushing to the hub.", ) parser.add_argument( "--show_prediction", action="store_true", ) UpperCamelCase__: Tuple = parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
23
1
"""simple docstring""" from decimal import Decimal, getcontext from math import ceil, factorial def __lowercase ( snake_case_ : int ) ->str: '''simple docstring''' if not isinstance(snake_case_ ,snake_case_ ): raise TypeError('''Undefined for non-integers''' ) elif precision < 1: raise ValueError('''Undefined for non-natural numbers''' ) __A : int = precision __A : Tuple = ceil(precision / 14 ) __A : Dict = 426880 * Decimal(10005 ).sqrt() __A : Optional[Any] = 1 __A : int = 13591409 __A : Optional[int] = Decimal(snake_case_ ) for k in range(1 ,snake_case_ ): __A : int = factorial(6 * k ) // (factorial(3 * k ) * factorial(snake_case_ ) ** 3) linear_term += 545140134 exponential_term *= -262537412640768000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": a_ = 50 print(f'''The first {n} digits of pi is: {pi(n)}''')
291
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule a_ = {"""tokenization_tapex""": ["""TapexTokenizer"""]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
291
1
'''simple docstring''' def UpperCamelCase_( snake_case : Optional[int] , snake_case : Optional[int] ): '''simple docstring''' snake_case_ = [0 for i in range(r + 1 )] # nc0 = 1 snake_case_ = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. snake_case_ = min(snake_case , snake_case ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
85
"""simple docstring""" from __future__ import annotations import math def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> list: '''simple docstring''' if len(__lowerCAmelCase ) != 2 or len(a[0] ) != 2 or len(__lowerCAmelCase ) != 2 or len(b[0] ) != 2: raise Exception("""Matrices are not 2x2""" ) lowercase_ = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__lowerCAmelCase ) ) ] def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]: '''simple docstring''' return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(__lowerCAmelCase ) ) ] def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> tuple[list, list, list, list]: '''simple docstring''' if len(__lowerCAmelCase ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception("""Odd matrices are not supported!""" ) lowercase_ = len(__lowerCAmelCase ) lowercase_ = matrix_length // 2 lowercase_ = [[a[i][j] for j in range(__lowerCAmelCase , __lowerCAmelCase )] for i in range(__lowerCAmelCase )] lowercase_ = [ [a[i][j] for j in range(__lowerCAmelCase , __lowerCAmelCase )] for i in range(__lowerCAmelCase , __lowerCAmelCase ) ] lowercase_ = [[a[i][j] for j in range(__lowerCAmelCase )] for i in range(__lowerCAmelCase )] lowercase_ = [[a[i][j] for j in range(__lowerCAmelCase )] for i in range(__lowerCAmelCase , __lowerCAmelCase )] return top_left, top_right, bot_left, bot_right def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> tuple[int, int]: '''simple docstring''' return len(__lowerCAmelCase ), len(matrix[0] ) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> None: '''simple docstring''' print("""\n""".join(str(__lowerCAmelCase ) for line in matrix ) ) def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> list: '''simple docstring''' if matrix_dimensions(__lowerCAmelCase ) == (2, 2): return default_matrix_multiplication(__lowerCAmelCase , __lowerCAmelCase ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = split_matrix(__lowerCAmelCase ) lowercase_ , lowercase_ , lowercase_ , lowercase_ = split_matrix(__lowerCAmelCase ) lowercase_ = actual_strassen(__lowerCAmelCase , matrix_subtraction(__lowerCAmelCase , __lowerCAmelCase ) ) lowercase_ = actual_strassen(matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) , __lowerCAmelCase ) lowercase_ = actual_strassen(matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) , __lowerCAmelCase ) lowercase_ = actual_strassen(__lowerCAmelCase , matrix_subtraction(__lowerCAmelCase , __lowerCAmelCase ) ) lowercase_ = actual_strassen(matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) , matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) ) lowercase_ = actual_strassen(matrix_subtraction(__lowerCAmelCase , __lowerCAmelCase ) , matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) ) lowercase_ = actual_strassen(matrix_subtraction(__lowerCAmelCase , __lowerCAmelCase ) , matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) ) lowercase_ = matrix_addition(matrix_subtraction(matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) , __lowerCAmelCase ) , __lowerCAmelCase ) lowercase_ = matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) lowercase_ = matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) lowercase_ = matrix_subtraction(matrix_subtraction(matrix_addition(__lowerCAmelCase , __lowerCAmelCase ) , __lowerCAmelCase ) , __lowerCAmelCase ) # construct the new matrix from our 4 quadrants lowercase_ = [] for i in range(len(__lowerCAmelCase ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(__lowerCAmelCase ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> list: '''simple docstring''' if matrix_dimensions(__lowerCAmelCase )[1] != matrix_dimensions(__lowerCAmelCase )[0]: lowercase_ = ( """Unable to multiply these matrices, please check the dimensions.\n""" F'''Matrix A: {matrixa}\n''' F'''Matrix B: {matrixa}''' ) raise Exception(__lowerCAmelCase ) lowercase_ = matrix_dimensions(__lowerCAmelCase ) lowercase_ = matrix_dimensions(__lowerCAmelCase ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] lowercase_ = max(*__lowerCAmelCase , *__lowerCAmelCase ) lowercase_ = int(math.pow(2 , math.ceil(math.loga(__lowerCAmelCase ) ) ) ) lowercase_ = matrixa lowercase_ = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , __lowerCAmelCase ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __lowerCAmelCase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , __lowerCAmelCase ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) lowercase_ = actual_strassen(__lowerCAmelCase , __lowerCAmelCase ) # Removing the additional zeros for i in range(0 , __lowerCAmelCase ): if i < dimensiona[0]: for _ in range(dimensiona[1] , __lowerCAmelCase ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": UpperCAmelCase : List[Any] = [ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] UpperCAmelCase : Optional[int] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
136
0
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __SCREAMING_SNAKE_CASE = TypeVar("""KEY""") __SCREAMING_SNAKE_CASE = TypeVar("""VAL""") @dataclass(frozen=_A ,slots=_A ) class lowerCamelCase_ ( Generic[KEY, VAL] ): '''simple docstring''' a__ = 42 a__ = 42 class lowerCamelCase_ ( _Item ): '''simple docstring''' def __init__( self : Dict ) -> None: super().__init__(__lowerCamelCase , __lowerCamelCase ) def __bool__( self : List[str] ) -> bool: return False __SCREAMING_SNAKE_CASE = _DeletedItem() class lowerCamelCase_ ( MutableMapping[KEY, VAL] ): '''simple docstring''' def __init__( self : int , __lowerCamelCase : int = 8 , __lowerCamelCase : float = 0.75 ) -> None: A : List[Any] = initial_block_size A : list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 A : Union[str, Any] = capacity_factor A : Dict = 0 def SCREAMING_SNAKE_CASE__ ( self : List[Any] , __lowerCamelCase : KEY ) -> int: return hash(__lowerCamelCase ) % len(self._buckets ) def SCREAMING_SNAKE_CASE__ ( self : int , __lowerCamelCase : int ) -> int: return (ind + 1) % len(self._buckets ) def SCREAMING_SNAKE_CASE__ ( self : int , __lowerCamelCase : int , __lowerCamelCase : KEY , __lowerCamelCase : VAL ) -> bool: A : Dict = self._buckets[ind] if not stored: A : Union[str, Any] = _Item(__lowerCamelCase , __lowerCamelCase ) self._len += 1 return True elif stored.key == key: A : str = _Item(__lowerCamelCase , __lowerCamelCase ) return True else: return False def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> bool: A : Dict = len(self._buckets ) * self._capacity_factor return len(self ) >= int(__lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ) -> bool: if len(self._buckets ) <= self._initial_block_size: return False A : List[str] = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def SCREAMING_SNAKE_CASE__ ( self : List[Any] , __lowerCamelCase : int ) -> None: A : int = self._buckets A : int = [None] * new_size A : Tuple = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> None: self._resize(len(self._buckets ) * 2 ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> None: self._resize(len(self._buckets ) // 2 ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , __lowerCamelCase : KEY ) -> Iterator[int]: A : str = self._get_bucket_index(__lowerCamelCase ) for _ in range(len(self._buckets ) ): yield ind A : Tuple = self._get_next_ind(__lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , __lowerCamelCase : KEY , __lowerCamelCase : VAL ) -> None: for ind in self._iterate_buckets(__lowerCamelCase ): if self._try_set(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): break def __setitem__( self : Dict , __lowerCamelCase : KEY , __lowerCamelCase : VAL ) -> None: if self._is_full(): self._size_up() self._add_item(__lowerCamelCase , __lowerCamelCase ) def __delitem__( self : Dict , __lowerCamelCase : KEY ) -> None: for ind in self._iterate_buckets(__lowerCamelCase ): A : int = self._buckets[ind] if item is None: raise KeyError(__lowerCamelCase ) if item is _deleted: continue if item.key == key: A : List[str] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Optional[Any] , __lowerCamelCase : KEY ) -> VAL: for ind in self._iterate_buckets(__lowerCamelCase ): A : Optional[int] = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(__lowerCamelCase ) def __len__( self : Tuple ) -> int: return self._len def __iter__( self : Union[str, Any] ) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[int] ) -> str: A : Tuple = " ,".join( F"""{item.key}: {item.val}""" for item in self._buckets if item ) return F"""HashMap({val_string})"""
256
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="""%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s""", datefmt="""%Y-%m-%d %H:%M:%S""", level=os.environ.get("""LOGLEVEL""", """INFO""").upper(), stream=sys.stdout, ) __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) __SCREAMING_SNAKE_CASE = {"""facebook/bart-base""": BartForConditionalGeneration} __SCREAMING_SNAKE_CASE = {"""facebook/bart-base""": BartTokenizer} def UpperCAmelCase ( ): A : List[Any] = argparse.ArgumentParser(description="Export Bart model + Beam Search to ONNX graph." ) parser.add_argument( "--validation_file" , type=_lowerCamelCase , default=_lowerCamelCase , help="A csv or a json file containing the validation data." ) parser.add_argument( "--max_length" , type=_lowerCamelCase , default=5 , help="The maximum total input sequence length after tokenization." , ) parser.add_argument( "--num_beams" , type=_lowerCamelCase , default=_lowerCamelCase , help=( "Number of beams to use for evaluation. This argument will be " "passed to ``model.generate``, which is used during ``evaluate`` and ``predict``." ) , ) parser.add_argument( "--model_name_or_path" , type=_lowerCamelCase , help="Path to pretrained model or model identifier from huggingface.co/models." , required=_lowerCamelCase , ) parser.add_argument( "--config_name" , type=_lowerCamelCase , default=_lowerCamelCase , help="Pretrained config name or path if not the same as model_name" , ) parser.add_argument( "--device" , type=_lowerCamelCase , default="cpu" , help="Device where the model will be run" , ) parser.add_argument("--output_file_path" , type=_lowerCamelCase , default=_lowerCamelCase , help="Where to store the final ONNX file." ) A : Any = parser.parse_args() return args def UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase="cpu" ): A : int = model_dict[model_name].from_pretrained(_lowerCamelCase ).to(_lowerCamelCase ) A : List[Any] = tokenizer_dict[model_name].from_pretrained(_lowerCamelCase ) if model_name in ["facebook/bart-base"]: A : Optional[int] = 0 A : Union[str, Any] = None A : Optional[Any] = 0 return huggingface_model, tokenizer def UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): model.eval() A : Optional[Any] = None A : List[Any] = torch.jit.script(BARTBeamSearchGenerator(_lowerCamelCase ) ) with torch.no_grad(): A : int = "My friends are cool but they eat too many carbs." A : List[Any] = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1024 , return_tensors="pt" ).to(model.device ) A : int = model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , num_beams=_lowerCamelCase , max_length=_lowerCamelCase , early_stopping=_lowerCamelCase , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( _lowerCamelCase , ( inputs["input_ids"], inputs["attention_mask"], num_beams, max_length, model.config.decoder_start_token_id, ) , _lowerCamelCase , opset_version=14 , input_names=["input_ids", "attention_mask", "num_beams", "max_length", "decoder_start_token_id"] , output_names=["output_ids"] , dynamic_axes={ "input_ids": {0: "batch", 1: "seq"}, "output_ids": {0: "batch", 1: "seq_out"}, } , example_outputs=_lowerCamelCase , ) logger.info("Model exported to {}".format(_lowerCamelCase ) ) A : Optional[Any] = remove_dup_initializers(os.path.abspath(_lowerCamelCase ) ) logger.info("Deduplicated and optimized model written to {}".format(_lowerCamelCase ) ) A : List[Any] = onnxruntime.InferenceSession(_lowerCamelCase ) A : Dict = ort_sess.run( _lowerCamelCase , { "input_ids": inputs["input_ids"].cpu().numpy(), "attention_mask": inputs["attention_mask"].cpu().numpy(), "num_beams": np.array(_lowerCamelCase ), "max_length": np.array(_lowerCamelCase ), "decoder_start_token_id": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info("Model outputs from torch and ONNX Runtime are similar." ) logger.info("Success." ) def UpperCAmelCase ( ): A : Union[str, Any] = parse_args() A : List[Any] = 5 A : str = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() A : Union[str, Any] = torch.device(args.device ) A , A : Optional[int] = load_model_tokenizer(args.model_name_or_path , _lowerCamelCase ) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined" ) model.to(_lowerCamelCase ) if args.max_length: A : Optional[int] = args.max_length if args.num_beams: A : List[Any] = args.num_beams if args.output_file_path: A : int = args.output_file_path else: A : int = "BART.onnx" logger.info("Exporting model to ONNX" ) export_and_validate_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) if __name__ == "__main__": main()
256
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class __A ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a ={ '''task_specific_params''': { '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 128, '''min_length''': 12, '''num_beams''': 4}, '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 142, '''min_length''': 56, '''num_beams''': 4}, '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6}, } } a ={ '''task_specific_params.summarization.length_penalty''': 1.0, '''task_specific_params.summarization.max_length''': 128, '''task_specific_params.summarization.min_length''': 12, '''task_specific_params.summarization.num_beams''': 4, '''task_specific_params.summarization_cnn.length_penalty''': 2.0, '''task_specific_params.summarization_cnn.max_length''': 142, '''task_specific_params.summarization_cnn.min_length''': 56, '''task_specific_params.summarization_cnn.num_beams''': 4, '''task_specific_params.summarization_xsum.length_penalty''': 1.0, '''task_specific_params.summarization_xsum.max_length''': 62, '''task_specific_params.summarization_xsum.min_length''': 11, '''task_specific_params.summarization_xsum.num_beams''': 6, } self.assertEqual(flatten_dict(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(__A ) , x.transpose() ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A ) , transpose(__A ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , transpose(__A , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Any: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A ) , np.asarray(transpose(__A ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(transpose(__A , axes=(1, 2, 0) ) , np.asarray(transpose(__A , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.reshape(__A , (4, 3) ) ) ) a =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.reshape(__A , (12, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , reshape(__A , (4, 3) ).numpy() ) ) a =np.random.randn(3 , 4 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , reshape(__A , (12, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (4, 3) ) , np.asarray(reshape(__A , (4, 3) ) ) ) ) a =np.random.randn(3 , 4 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(reshape(__A , (12, 5) ) , np.asarray(reshape(__A , (12, 5) ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(__A ) , np.squeeze(__A ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.squeeze(__A , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(1 , 3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> Tuple: a =np.random.randn(1 , 3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A ) , squeeze(__A ).numpy() ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =tf.constant(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , squeeze(__A , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(1 , 3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A ) , np.asarray(squeeze(__A ) ) ) ) a =np.random.randn(1 , 4 , 1 , 5 ) a =jnp.array(__A ) self.assertTrue(np.allclose(squeeze(__A , axis=2 ) , np.asarray(squeeze(__A , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE ( self ) -> List[Any]: a =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.expand_dims(__A , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE ( self ) -> str: a =np.random.randn(3 , 4 ) a =torch.tensor(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE ( self ) -> int: a =np.random.randn(3 , 4 ) a =tf.constant(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , expand_dims(__A , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =np.random.randn(3 , 4 ) a =jnp.array(__A ) self.assertTrue(np.allclose(expand_dims(__A , axis=1 ) , np.asarray(expand_dims(__A , axis=1 ) ) ) )
81
'''simple docstring''' from collections.abc import Generator from math import sin def lowercase ( __magic_name__ ): '''simple docstring''' if len(__magic_name__ ) != 32: raise ValueError("Input must be of length 32" ) UpperCAmelCase : Union[str, Any] = b"" for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def lowercase ( __magic_name__ ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) UpperCAmelCase : Dict = format(__magic_name__ , "08x" )[-8:] UpperCAmelCase : List[str] = b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8" ) return little_endian_hex def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : int = b"" for char in message: bit_string += format(__magic_name__ , "08b" ).encode("utf-8" ) UpperCAmelCase : List[Any] = format(len(__magic_name__ ) , "064b" ).encode("utf-8" ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__magic_name__ ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def lowercase ( __magic_name__ ): '''simple docstring''' if len(__magic_name__ ) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512" ) for pos in range(0 , len(__magic_name__ ) , 512 ): UpperCAmelCase : Union[str, Any] = bit_string[pos : pos + 512] UpperCAmelCase : Tuple = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def lowercase ( __magic_name__ ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) UpperCAmelCase : Any = format(__magic_name__ , "032b" ) UpperCAmelCase : int = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(__magic_name__ , 2 ) def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' return (a + b) % 2**32 def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' if i < 0: raise ValueError("Input must be non-negative" ) if shift < 0: raise ValueError("Shift must be non-negative" ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : Dict = preprocess(__magic_name__ ) UpperCAmelCase : List[Any] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states UpperCAmelCase : List[str] = 0X67452301 UpperCAmelCase : Tuple = 0XEFCDAB89 UpperCAmelCase : List[Any] = 0X98BADCFE UpperCAmelCase : List[str] = 0X10325476 UpperCAmelCase : Dict = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__magic_name__ ): UpperCAmelCase : Optional[Any] = aa UpperCAmelCase : List[Any] = ba UpperCAmelCase : Optional[Any] = ca UpperCAmelCase : Any = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f UpperCAmelCase : Tuple = d ^ (b & (c ^ d)) UpperCAmelCase : List[str] = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f UpperCAmelCase : int = c ^ (d & (b ^ c)) UpperCAmelCase : Tuple = (5 * i + 1) % 16 elif i <= 47: UpperCAmelCase : Any = b ^ c ^ d UpperCAmelCase : Union[str, Any] = (3 * i + 5) % 16 else: UpperCAmelCase : Dict = c ^ (b | not_aa(__magic_name__ )) UpperCAmelCase : Dict = (7 * i) % 16 UpperCAmelCase : List[str] = (f + a + added_consts[i] + block_words[g]) % 2**32 UpperCAmelCase : List[Any] = d UpperCAmelCase : Any = c UpperCAmelCase : Dict = b UpperCAmelCase : Union[str, Any] = sum_aa(__magic_name__ , left_rotate_aa(__magic_name__ , shift_amounts[i] ) ) # Add hashed chunk to running total UpperCAmelCase : List[str] = sum_aa(__magic_name__ , __magic_name__ ) UpperCAmelCase : Any = sum_aa(__magic_name__ , __magic_name__ ) UpperCAmelCase : List[Any] = sum_aa(__magic_name__ , __magic_name__ ) UpperCAmelCase : Optional[int] = sum_aa(__magic_name__ , __magic_name__ ) UpperCAmelCase : List[str] = reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) + reformat_hex(__magic_name__ ) return digest if __name__ == "__main__": import doctest doctest.testmod()
311
0
"""simple docstring""" def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> int: '''simple docstring''' if collection == []: return [] # get some information about the collection __snake_case : List[str] = len(lowercase__ ) __snake_case : List[str] = max(lowercase__ ) __snake_case : List[str] = min(lowercase__ ) # create the counting array __snake_case : List[Any] = coll_max + 1 - coll_min __snake_case : List[Any] = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowercase__ ): __snake_case : Optional[int] = counting_arr[i] + counting_arr[i - 1] # create the output collection __snake_case : Dict = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowercase__ ) ): __snake_case : Any = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def __UpperCAmelCase ( UpperCAmelCase_ : str ) -> Tuple: '''simple docstring''' return "".join([chr(lowercase__ ) for i in counting_sort([ord(lowercase__ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt" _a : List[str]= input("Enter numbers separated by a comma:\n").strip() _a : int= [int(item) for item in user_input.split(",")] print(counting_sort(unsorted))
362
"""simple docstring""" from __future__ import annotations import math def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(UpperCAmelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True _a : Any= [num for num in range(3, 100_001, 2) if not is_prime(num)] def __UpperCAmelCase ( UpperCAmelCase_ : int ) -> list[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise ValueError('n must be an integer' ) if n <= 0: raise ValueError('n must be >= 0' ) __snake_case : int = [] for num in range(len(UpperCAmelCase_ ) ): __snake_case : List[str] = 0 while 2 * i * i <= odd_composites[num]: __snake_case : List[Any] = odd_composites[num] - 2 * i * i if is_prime(UpperCAmelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(UpperCAmelCase_ ) == n: return list_nums return [] def __UpperCAmelCase ( ) -> int: '''simple docstring''' return compute_nums(1 )[0] if __name__ == "__main__": print(f'''{solution() = }''')
95
0
def __lowerCamelCase ( __a :Optional[Any] ) -> int: """simple docstring""" A__ = 0 A__ = len(__a ) for i in range(n - 1 ): for j in range(i + 1 , __a ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def __lowerCamelCase ( __a :int ) -> Any: """simple docstring""" if len(__a ) <= 1: return arr, 0 A__ = len(__a ) // 2 A__ = arr[0:mid] A__ = arr[mid:] A__ , A__ = count_inversions_recursive(__a ) A__ , A__ = count_inversions_recursive(__a ) A__ , A__ = _count_cross_inversions(__a , __a ) A__ = inversion_p + inversions_q + cross_inversions return c, num_inversions def __lowerCamelCase ( __a :List[str] , __a :Any ) -> Any: """simple docstring""" A__ = [] A__ = A__ = A__ = 0 while i < len(__a ) and j < len(__a ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(__a ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(__a ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def __lowerCamelCase ( ) -> Union[str, Any]: """simple docstring""" A__ = [1_0, 2, 1, 5, 5, 2, 1_1] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) A__ = count_inversions_bf(__a ) A__ , A__ = count_inversions_recursive(__a ) assert num_inversions_bf == num_inversions_recursive == 8 print("""number of inversions = """ , __a ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() A__ = count_inversions_bf(__a ) A__ , A__ = count_inversions_recursive(__a ) assert num_inversions_bf == num_inversions_recursive == 0 print("""number of inversions = """ , __a ) # an empty list should also have zero inversions A__ = [] A__ = count_inversions_bf(__a ) A__ , A__ = count_inversions_recursive(__a ) assert num_inversions_bf == num_inversions_recursive == 0 print("""number of inversions = """ , __a ) if __name__ == "__main__": main()
274
import argparse from collections import defaultdict import yaml A : str = '''docs/source/en/_toctree.yml''' def __lowerCamelCase ( __a :str ) -> List[Any]: """simple docstring""" A__ = defaultdict(__a ) A__ = [] A__ = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"""local""": doc["""local"""], """title""": doc["""title"""]} ) else: new_doc_list.append(__a ) A__ = new_doc_list A__ = [key for key, value in counts.items() if value > 1] A__ = [] for duplicate_key in duplicates: A__ = list({doc["""title"""] for doc in doc_list if doc["""local"""] == duplicate_key} ) if len(__a ) > 1: raise ValueError( F'{duplicate_key} is present several times in the documentation table of content at ' """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if """local""" not in counts or counts[doc["""local"""]] == 1] ) A__ = sorted(__a , key=lambda __a : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__a ) > 1: raise ValueError("""{doc_list} has two 'overview' docs which is not allowed.""" ) overview_doc.extend(__a ) # Sort return overview_doc def __lowerCamelCase ( __a :Any=False ) -> List[str]: """simple docstring""" with open(__a , encoding="""utf-8""" ) as f: A__ = yaml.safe_load(f.read() ) # Get to the API doc A__ = 0 while content[api_idx]["title"] != "API": api_idx += 1 A__ = content[api_idx]["""sections"""] # Then to the model doc A__ = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 A__ = api_doc[scheduler_idx]["""sections"""] A__ = clean_doc_toc(__a ) A__ = False if new_scheduler_doc != scheduler_doc: A__ = True if overwrite: A__ = new_scheduler_doc if diff: if overwrite: A__ = api_doc with open(__a , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) def __lowerCamelCase ( __a :Optional[int]=False ) -> Dict: """simple docstring""" with open(__a , encoding="""utf-8""" ) as f: A__ = yaml.safe_load(f.read() ) # Get to the API doc A__ = 0 while content[api_idx]["title"] != "API": api_idx += 1 A__ = content[api_idx]["""sections"""] # Then to the model doc A__ = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 A__ = False A__ = api_doc[pipeline_idx]["""sections"""] A__ = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: A__ = pipeline_doc["""section"""] A__ = clean_doc_toc(__a ) if overwrite: A__ = new_sub_pipeline_doc new_pipeline_docs.append(__a ) # sort overall pipeline doc A__ = clean_doc_toc(__a ) if new_pipeline_docs != pipeline_docs: A__ = True if overwrite: A__ = new_pipeline_docs if diff: if overwrite: A__ = api_doc with open(__a , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": A : Tuple = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A : Optional[Any] = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
274
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def lowercase__ ( __snake_case : Any , __snake_case : Tuple , __snake_case : List[Any]=[] ): '''simple docstring''' UpperCAmelCase_ : Dict = size[0] - overlap_pixels * 2 UpperCAmelCase_ : List[Any] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels UpperCAmelCase_ : Tuple = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 UpperCAmelCase_ : List[str] = np.pad(__snake_case , mode='linear_ramp' , pad_width=__snake_case , end_values=0 ) if "l" in remove_borders: UpperCAmelCase_ : Optional[int] = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: UpperCAmelCase_ : List[Any] = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: UpperCAmelCase_ : int = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: UpperCAmelCase_ : Dict = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def lowercase__ ( __snake_case : Dict , __snake_case : Optional[Any] , __snake_case : Optional[int] ): '''simple docstring''' return max(__snake_case , min(__snake_case , __snake_case ) ) def lowercase__ ( __snake_case : [int] , __snake_case : [int] , __snake_case : [int] ): '''simple docstring''' return ( clamp(rect[0] , min[0] , max[0] ), clamp(rect[1] , min[1] , max[1] ), clamp(rect[2] , min[0] , max[0] ), clamp(rect[3] , min[1] , max[1] ), ) def lowercase__ ( __snake_case : [int] , __snake_case : int , __snake_case : [int] ): '''simple docstring''' UpperCAmelCase_ : Union[str, Any] = list(__snake_case ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap UpperCAmelCase_ : int = clamp_rect(__snake_case , [0, 0] , [image_size[0], image_size[1]] ) return rect def lowercase__ ( __snake_case : List[str] , __snake_case : str , __snake_case : Union[str, Any] , __snake_case : Any ): '''simple docstring''' UpperCAmelCase_ : Tuple = Image.new('RGB' , (tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) , Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) , (0, 0) , ) result.paste(__snake_case , (original_slice, 0) ) return result def lowercase__ ( __snake_case : Union[str, Any] , __snake_case : str ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) UpperCAmelCase_ : List[Any] = tile.crop(__snake_case ) return tile def lowercase__ ( __snake_case : Optional[Any] , __snake_case : List[str] ): '''simple docstring''' UpperCAmelCase_ : str = n % d return n - divisor class lowerCamelCase (_snake_case ): '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 3_5_0 , ) -> List[Any]: super().__init__( vae=_UpperCamelCase , text_encoder=_UpperCamelCase , tokenizer=_UpperCamelCase , unet=_UpperCamelCase , low_res_scheduler=_UpperCamelCase , scheduler=_UpperCamelCase , max_noise_level=_UpperCamelCase , ) def __UpperCAmelCase ( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , **_UpperCamelCase ) -> List[Any]: torch.manual_seed(0 ) UpperCAmelCase_ : Tuple = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) UpperCAmelCase_ : List[str] = add_overlap_rect(_UpperCamelCase , _UpperCamelCase , image.size ) UpperCAmelCase_ : Optional[int] = image.crop(_UpperCamelCase ) UpperCAmelCase_ : List[Any] = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] UpperCAmelCase_ : int = translated_slice_x - (original_image_slice / 2) UpperCAmelCase_ : str = max(0 , _UpperCamelCase ) UpperCAmelCase_ : Union[str, Any] = squeeze_tile(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) UpperCAmelCase_ : Optional[int] = to_input.size UpperCAmelCase_ : Union[str, Any] = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) UpperCAmelCase_ : str = super(_UpperCamelCase , self ).__call__(image=_UpperCamelCase , **_UpperCamelCase ).images[0] UpperCAmelCase_ : Any = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) UpperCAmelCase_ : Optional[Any] = unsqueeze_tile(_UpperCamelCase , _UpperCamelCase ) UpperCAmelCase_ : int = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) UpperCAmelCase_ : List[str] = [] if x == 0: remove_borders.append('l' ) elif crop_rect[2] == image.size[0]: remove_borders.append('r' ) if y == 0: remove_borders.append('t' ) elif crop_rect[3] == image.size[1]: remove_borders.append('b' ) UpperCAmelCase_ : Optional[Any] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=_UpperCamelCase ) , mode='L' , ) final_image.paste( _UpperCamelCase , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , _UpperCamelCase ) @torch.no_grad() def __call__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = 7_5 , _UpperCamelCase = 9.0 , _UpperCamelCase = 5_0 , _UpperCamelCase = None , _UpperCamelCase = 1 , _UpperCamelCase = 0.0 , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = 1 , _UpperCamelCase = 1_2_8 , _UpperCamelCase = 3_2 , _UpperCamelCase = 3_2 , ) -> Optional[int]: UpperCAmelCase_ : str = Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) ) UpperCAmelCase_ : str = math.ceil(image.size[0] / tile_size ) UpperCAmelCase_ : str = math.ceil(image.size[1] / tile_size ) UpperCAmelCase_ : Optional[Any] = tcx * tcy UpperCAmelCase_ : str = 0 for y in range(_UpperCamelCase ): for x in range(_UpperCamelCase ): self._process_tile( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , prompt=_UpperCamelCase , num_inference_steps=_UpperCamelCase , guidance_scale=_UpperCamelCase , noise_level=_UpperCamelCase , negative_prompt=_UpperCamelCase , num_images_per_prompt=_UpperCamelCase , eta=_UpperCamelCase , generator=_UpperCamelCase , latents=_UpperCamelCase , ) current_count += 1 if callback is not None: callback({'progress': current_count / total_tile_count, 'image': final_image} ) return final_image def lowercase__ ( ): '''simple docstring''' UpperCAmelCase_ : List[Any] = 'stabilityai/stable-diffusion-x4-upscaler' UpperCAmelCase_ : int = StableDiffusionTiledUpscalePipeline.from_pretrained(__snake_case , revision='fp16' , torch_dtype=torch.floataa ) UpperCAmelCase_ : Union[str, Any] = pipe.to('cuda' ) UpperCAmelCase_ : List[str] = Image.open('../../docs/source/imgs/diffusers_library.jpg' ) def callback(__snake_case : Optional[Any] ): print(F"progress: {obj['progress']:.4f}" ) obj["image"].save('diffusers_library_progress.jpg' ) UpperCAmelCase_ : Optional[int] = pipe(image=__snake_case , prompt='Black font, white background, vector' , noise_level=40 , callback=__snake_case ) final_image.save('diffusers_library.jpg' ) if __name__ == "__main__": main()
145
from __future__ import annotations from collections.abc import Callable __UpperCAmelCase = list[list[float | int]] def lowercase__ ( __snake_case : Matrix , __snake_case : Matrix ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(size + 1 )] for _ in range(__snake_case )] UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : float for row in range(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : Dict = matrix[row][col] UpperCAmelCase_ : Union[str, Any] = vector[row][0] UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : Union[str, Any] = 0 while row < size and col < size: # pivoting UpperCAmelCase_ : Optional[Any] = max((abs(augmented[rowa][col] ), rowa) for rowa in range(__snake_case , __snake_case ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: UpperCAmelCase_ , UpperCAmelCase_ : Tuple = augmented[pivot_row], augmented[row] for rowa in range(row + 1 , __snake_case ): UpperCAmelCase_ : Optional[int] = augmented[rowa][col] / augmented[row][col] UpperCAmelCase_ : List[str] = 0 for cola in range(col + 1 , size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1 , __snake_case ): for row in range(__snake_case ): UpperCAmelCase_ : Union[str, Any] = augmented[row][col] / augmented[col][col] for cola in range(__snake_case , size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(__snake_case ) ] def lowercase__ ( __snake_case : list[int] ): '''simple docstring''' UpperCAmelCase_ : int = len(__snake_case ) UpperCAmelCase_ : Matrix = [[0 for _ in range(__snake_case )] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix = [[0] for _ in range(__snake_case )] UpperCAmelCase_ : Matrix UpperCAmelCase_ : int UpperCAmelCase_ : int UpperCAmelCase_ : int for x_val, y_val in enumerate(__snake_case ): for col in range(__snake_case ): UpperCAmelCase_ : int = (x_val + 1) ** (size - col - 1) UpperCAmelCase_ : int = y_val UpperCAmelCase_ : List[str] = solve(__snake_case , __snake_case ) def interpolated_func(__snake_case : int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(__snake_case ) ) return interpolated_func def lowercase__ ( __snake_case : int ): '''simple docstring''' return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def lowercase__ ( __snake_case : Callable[[int], int] = question_function , __snake_case : int = 10 ): '''simple docstring''' UpperCAmelCase_ : list[int] = [func(__snake_case ) for x_val in range(1 , order + 1 )] UpperCAmelCase_ : list[Callable[[int], int]] = [ interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 ) ] UpperCAmelCase_ : int = 0 UpperCAmelCase_ : Callable[[int], int] UpperCAmelCase_ : int for poly in polynomials: UpperCAmelCase_ : Optional[int] = 1 while func(__snake_case ) == poly(__snake_case ): x_val += 1 ret += poly(__snake_case ) return ret if __name__ == "__main__": print(F'{solution() = }')
145
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class __magic_name__ : '''simple docstring''' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=[1, 1, 2] , _a=1 , _a=32 , _a=4 , _a=8 , _a=37 , _a="gelu_new" , _a=0.1 , _a=0.1 , _a=0.0 , _a=512 , _a=3 , _a=0.02 , _a=3 , _a=4 , _a=None , _a=False , ): """simple docstring""" lowerCamelCase = parent lowerCamelCase = batch_size lowerCamelCase = seq_length lowerCamelCase = is_training lowerCamelCase = use_input_mask lowerCamelCase = use_token_type_ids lowerCamelCase = use_labels lowerCamelCase = vocab_size lowerCamelCase = block_sizes lowerCamelCase = num_decoder_layers lowerCamelCase = d_model lowerCamelCase = n_head lowerCamelCase = d_head lowerCamelCase = d_inner lowerCamelCase = hidden_act lowerCamelCase = hidden_dropout lowerCamelCase = attention_dropout lowerCamelCase = activation_dropout lowerCamelCase = max_position_embeddings lowerCamelCase = type_vocab_size lowerCamelCase = 2 lowerCamelCase = num_labels lowerCamelCase = num_choices lowerCamelCase = scope lowerCamelCase = initializer_std # Used in the tests to check the size of the first attention layer lowerCamelCase = n_head # Used in the tests to check the size of the first hidden state lowerCamelCase = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCamelCase = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCamelCase = self.num_hidden_layers + 2 def _lowerCAmelCase ( 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] ) lowerCamelCase = None if self.use_token_type_ids: lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase = None lowerCamelCase = None lowerCamelCase = None if self.use_labels: lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase = ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = TFFunnelModel(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) lowerCamelCase = [input_ids, input_mask] lowerCamelCase = model(_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCamelCase = False lowerCamelCase = TFFunnelModel(config=_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCamelCase = False lowerCamelCase = TFFunnelModel(config=_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = TFFunnelBaseModel(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) lowerCamelCase = [input_ids, input_mask] lowerCamelCase = model(_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCamelCase = False lowerCamelCase = TFFunnelBaseModel(config=_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCamelCase = False lowerCamelCase = TFFunnelBaseModel(config=_a ) lowerCamelCase = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = TFFunnelForPreTraining(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = TFFunnelForMaskedLM(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = self.num_labels lowerCamelCase = TFFunnelForSequenceClassification(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = self.num_choices lowerCamelCase = TFFunnelForMultipleChoice(config=_a ) lowerCamelCase = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase = tf.tile(tf.expand_dims(_a , 1 ) , (1, self.num_choices, 1) ) lowerCamelCase = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } lowerCamelCase = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = self.num_labels lowerCamelCase = TFFunnelForTokenClassification(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self , _a , _a , _a , _a , _a , _a , _a , ): """simple docstring""" lowerCamelCase = TFFunnelForQuestionAnswering(config=_a ) lowerCamelCase = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} lowerCamelCase = model(_a ) 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 ): """simple docstring""" lowerCamelCase = self.prepare_config_and_inputs() ( ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ) = config_and_inputs lowerCamelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class __magic_name__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) __UpperCamelCase = ( { "feature-extraction": (TFFunnelBaseModel, TFFunnelModel), "fill-mask": TFFunnelForMaskedLM, "question-answering": TFFunnelForQuestionAnswering, "text-classification": TFFunnelForSequenceClassification, "token-classification": TFFunnelForTokenClassification, "zero-shot": TFFunnelForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = TFFunnelModelTester(self ) lowerCamelCase = ConfigTester(self , config_class=_a ) def _lowerCAmelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) @require_tf class __magic_name__ ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) __UpperCamelCase = False __UpperCamelCase = False def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = TFFunnelModelTester(self , base=_a ) lowerCamelCase = ConfigTester(self , config_class=_a ) def _lowerCAmelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a )
291
"""simple docstring""" 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, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch lowerCAmelCase : int = logging.get_logger(__name__) class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["pixel_values"] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BILINEAR , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , **_a , ): """simple docstring""" super().__init__(**_a ) lowerCamelCase = size if size is not None else {"""shortest_edge""": 256} lowerCamelCase = get_size_dict(_a , default_to_square=_a ) lowerCamelCase = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} lowerCamelCase = get_size_dict(_a , param_name="""crop_size""" ) lowerCamelCase = do_resize lowerCamelCase = size lowerCamelCase = resample lowerCamelCase = do_center_crop lowerCamelCase = crop_size lowerCamelCase = do_rescale lowerCamelCase = rescale_factor lowerCamelCase = do_normalize lowerCamelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def _lowerCAmelCase ( self , _a , _a , _a = PILImageResampling.BICUBIC , _a = None , **_a , ): """simple docstring""" lowerCamelCase = get_size_dict(_a , default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowerCamelCase = get_resize_output_image_size(_a , size=size["""shortest_edge"""] , default_to_square=_a ) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def _lowerCAmelCase ( self , _a , _a , _a = None , **_a , ): """simple docstring""" lowerCamelCase = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f'The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}' ) return center_crop(_a , size=(size["""height"""], size["""width"""]) , data_format=_a , **_a ) def _lowerCAmelCase ( self , _a , _a , _a = None , **_a ): """simple docstring""" return rescale(_a , scale=_a , data_format=_a , **_a ) def _lowerCAmelCase ( self , _a , _a , _a , _a = None , **_a , ): """simple docstring""" return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def _lowerCAmelCase ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): """simple docstring""" lowerCamelCase = do_resize if do_resize is not None else self.do_resize lowerCamelCase = size if size is not None else self.size lowerCamelCase = get_size_dict(_a , default_to_square=_a ) lowerCamelCase = resample if resample is not None else self.resample lowerCamelCase = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase = crop_size if crop_size is not None else self.crop_size lowerCamelCase = get_size_dict(_a , param_name="""crop_size""" ) lowerCamelCase = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase = image_mean if image_mean is not None else self.image_mean lowerCamelCase = image_std if image_std is not None else self.image_std lowerCamelCase = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. lowerCamelCase = [to_numpy_array(_a ) for image in images] if do_resize: lowerCamelCase = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: lowerCamelCase = [self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: lowerCamelCase = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: lowerCamelCase = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] lowerCamelCase = [to_channel_dimension_format(_a , _a ) for image in images] lowerCamelCase = {"""pixel_values""": images} return BatchFeature(data=_a , tensor_type=_a ) def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_a ) != len(_a ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(_a ): lowerCamelCase = target_sizes.numpy() lowerCamelCase = [] for idx in range(len(_a ) ): lowerCamelCase = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=_a ) lowerCamelCase = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_a ) else: lowerCamelCase = logits.argmax(dim=1 ) lowerCamelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
291
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : int = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = [ '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CTRLForSequenceClassification''', '''CTRLLMHeadModel''', '''CTRLModel''', '''CTRLPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCTRLForSequenceClassification''', '''TFCTRLLMHeadModel''', '''TFCTRLModel''', '''TFCTRLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
195
"""simple docstring""" a__ : Optional[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = input("Enter message: " ) __SCREAMING_SNAKE_CASE = input("Enter key [alphanumeric]: " ) __SCREAMING_SNAKE_CASE = input("Encrypt/Decrypt [e/d]: " ) if mode.lower().startswith("e" ): __SCREAMING_SNAKE_CASE = "encrypt" __SCREAMING_SNAKE_CASE = encrypt_message(lowerCAmelCase_ , lowerCAmelCase_ ) elif mode.lower().startswith("d" ): __SCREAMING_SNAKE_CASE = "decrypt" __SCREAMING_SNAKE_CASE = decrypt_message(lowerCAmelCase_ , lowerCAmelCase_ ) print(f"""\n{mode.title()}ed message:""" ) print(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return translate_message(lowerCAmelCase_ , lowerCAmelCase_ , "encrypt" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return translate_message(lowerCAmelCase_ , lowerCAmelCase_ , "decrypt" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = key.upper() for symbol in message: __SCREAMING_SNAKE_CASE = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(lowerCAmelCase_ ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 0 else: translated.append(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) if __name__ == "__main__": main()
195
1
"""simple docstring""" def lowercase ( a__ : int , a__ : int ) -> int: return abs(a__ ) if a == 0 else greatest_common_divisor(b % a , a__ ) def lowercase ( a__ : int , a__ : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. _UpperCamelCase , _UpperCamelCase = y, x % y return abs(a__ ) def lowercase ( ) -> Any: try: _UpperCamelCase = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) _UpperCamelCase = int(nums[0] ) _UpperCamelCase = int(nums[1] ) print( F'''greatest_common_divisor({num_a}, {num_a}) = ''' F'''{greatest_common_divisor(a__ , a__ )}''' ) print(F'''By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(a__ , a__ )}''' ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
256
"""simple docstring""" def lowercase ( a__ : int , a__ : int ) -> int: return int((input_a, input_a).count(1 ) != 0 ) def lowercase ( ) -> None: assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
256
1
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
363
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, ) else: from .modeling_text_unet import UNetFlatConditionModel from .pipeline_versatile_diffusion import VersatileDiffusionPipeline from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
318
0
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = (DDPMParallelScheduler,) def SCREAMING_SNAKE_CASE_ (self : Any , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' lowerCamelCase__: Any ={ "num_train_timesteps": 1_000, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", "variance_type": "fixed_small", "clip_sample": True, } config.update(**UpperCAmelCase_) return config def SCREAMING_SNAKE_CASE_ (self : int) ->Dict: '''simple docstring''' for timesteps in [1, 5, 100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2]): self.check_over_configs(beta_start=UpperCAmelCase_ , beta_end=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->Optional[int]: '''simple docstring''' for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->Optional[Any]: '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any) ->Tuple: '''simple docstring''' self.check_over_configs(thresholding=UpperCAmelCase_) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=UpperCAmelCase_ , prediction_type=UpperCAmelCase_ , sample_max_value=UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : int) ->int: '''simple docstring''' for t in [0, 500, 999]: self.check_over_forward(time_step=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->str: '''simple docstring''' lowerCamelCase__: Dict =self.scheduler_classes[0] lowerCamelCase__: Tuple =self.get_scheduler_config() lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) assert torch.sum(torch.abs(scheduler._get_variance(0) - 0.0)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.0_0979)) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.02)) < 1E-5 def SCREAMING_SNAKE_CASE_ (self : Any) ->str: '''simple docstring''' lowerCamelCase__: int =self.scheduler_classes[0] lowerCamelCase__: Tuple =self.get_scheduler_config() lowerCamelCase__: Tuple =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: str =len(UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.dummy_model() lowerCamelCase__: int =self.dummy_sample_deter lowerCamelCase__: Union[str, Any] =self.dummy_sample_deter + 0.1 lowerCamelCase__: Optional[Any] =self.dummy_sample_deter - 0.1 lowerCamelCase__: Optional[Any] =samplea.shape[0] lowerCamelCase__: List[Any] =torch.stack([samplea, samplea, samplea] , dim=0) lowerCamelCase__: Union[str, Any] =torch.arange(UpperCAmelCase_)[0:3, None].repeat(1 , UpperCAmelCase_) lowerCamelCase__: Optional[int] =model(samples.flatten(0 , 1) , timesteps.flatten(0 , 1)) lowerCamelCase__: Tuple =scheduler.batch_step_no_noise(UpperCAmelCase_ , timesteps.flatten(0 , 1) , samples.flatten(0 , 1)) lowerCamelCase__: List[str] =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: Any =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 1153.1833) < 1E-2 assert abs(result_mean.item() - 0.5005) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any =self.scheduler_classes[0] lowerCamelCase__: Optional[Any] =self.get_scheduler_config() lowerCamelCase__: Optional[int] =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =len(UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.dummy_model() lowerCamelCase__: List[Any] =self.dummy_sample_deter lowerCamelCase__: int =torch.manual_seed(0) for t in reversed(range(UpperCAmelCase_)): # 1. predict noise residual lowerCamelCase__: Tuple =model(UpperCAmelCase_ , UpperCAmelCase_) # 2. predict previous mean of sample x_t-1 lowerCamelCase__: Optional[Any] =scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample lowerCamelCase__: Any =pred_prev_sample lowerCamelCase__: Any =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: List[str] =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 258.9606) < 1E-2 assert abs(result_mean.item() - 0.3372) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: Any =self.get_scheduler_config(prediction_type="v_prediction") lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: str =len(UpperCAmelCase_) lowerCamelCase__: str =self.dummy_model() lowerCamelCase__: str =self.dummy_sample_deter lowerCamelCase__: Dict =torch.manual_seed(0) for t in reversed(range(UpperCAmelCase_)): # 1. predict noise residual lowerCamelCase__: Union[str, Any] =model(UpperCAmelCase_ , UpperCAmelCase_) # 2. predict previous mean of sample x_t-1 lowerCamelCase__: Dict =scheduler.step(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , generator=UpperCAmelCase_).prev_sample lowerCamelCase__: List[str] =pred_prev_sample lowerCamelCase__: List[Any] =torch.sum(torch.abs(UpperCAmelCase_)) lowerCamelCase__: Tuple =torch.mean(torch.abs(UpperCAmelCase_)) assert abs(result_sum.item() - 202.0296) < 1E-2 assert abs(result_mean.item() - 0.2631) < 1E-3 def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Optional[int]: '''simple docstring''' lowerCamelCase__: str =self.scheduler_classes[0] lowerCamelCase__: Union[str, Any] =self.get_scheduler_config() lowerCamelCase__: Any =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: List[Any] =[100, 87, 50, 1, 0] scheduler.set_timesteps(timesteps=UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =scheduler.timesteps for i, timestep in enumerate(UpperCAmelCase_): if i == len(UpperCAmelCase_) - 1: lowerCamelCase__: Dict =-1 else: lowerCamelCase__: Union[str, Any] =timesteps[i + 1] lowerCamelCase__: Tuple =scheduler.previous_timestep(UpperCAmelCase_) lowerCamelCase__: str =prev_t.item() self.assertEqual(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Union[str, Any]) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: List[Any] =self.get_scheduler_config() lowerCamelCase__: Dict =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Optional[Any] =[100, 87, 50, 51, 0] with self.assertRaises(UpperCAmelCase_ , msg="`custom_timesteps` must be in descending order."): scheduler.set_timesteps(timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->List[Any]: '''simple docstring''' lowerCamelCase__: Dict =self.scheduler_classes[0] lowerCamelCase__: Any =self.get_scheduler_config() lowerCamelCase__: int =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Optional[int] =[100, 87, 50, 1, 0] lowerCamelCase__: int =len(UpperCAmelCase_) with self.assertRaises(UpperCAmelCase_ , msg="Can only pass one of `num_inference_steps` or `custom_timesteps`."): scheduler.set_timesteps(num_inference_steps=UpperCAmelCase_ , timesteps=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Any: '''simple docstring''' lowerCamelCase__: Tuple =self.scheduler_classes[0] lowerCamelCase__: Optional[Any] =self.get_scheduler_config() lowerCamelCase__: Optional[Any] =scheduler_class(**UpperCAmelCase_) lowerCamelCase__: Dict =[scheduler.config.num_train_timesteps] with self.assertRaises( UpperCAmelCase_ , msg="`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}" , ): scheduler.set_timesteps(timesteps=UpperCAmelCase_)
10
# 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 class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """philschmid/bart-large-cnn-samsum""" _lowercase : List[Any] = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) _lowercase : Any = """summarizer""" _lowercase : Any = AutoTokenizer _lowercase : str = AutoModelForSeqaSeqLM _lowercase : Optional[int] = ["""text"""] _lowercase : Optional[int] = ["""text"""] def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return self.pre_processor(lowerCAmelCase__ , return_tensors="pt" , truncation=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return self.model.generate(**lowerCAmelCase__ )[0] def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.pre_processor.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ , clean_up_tokenization_spaces=lowerCAmelCase__ )
95
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) __lowerCAmelCase : List[str] ={"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[Any] =["""ViTFeatureExtractor"""] __lowerCAmelCase : List[str] =["""ViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : str =[ """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTForImageClassification""", """ViTForMaskedImageModeling""", """ViTModel""", """ViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Any =[ """TFViTForImageClassification""", """TFViTModel""", """TFViTPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : Dict =[ """FlaxViTForImageClassification""", """FlaxViTModel""", """FlaxViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys __lowerCAmelCase : List[str] =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
32
"""simple docstring""" from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("""socket.socket""" ) @patch("""builtins.open""" ) def UpperCAmelCase__ ( lowerCAmelCase__ :Tuple , lowerCAmelCase__ :List[str] ) -> Union[str, Any]: '''simple docstring''' lowercase = Mock() lowercase = conn, Mock() lowercase = iter([1, None] ) lowercase = lambda lowerCAmelCase__ : next(lowerCAmelCase__ ) # ===== invoke ===== send_file(filename="""mytext.txt""" , testing=lowerCAmelCase__ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
32
1
'''simple docstring''' import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset __a = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class A__ ( nn.Module ): """simple docstring""" def __init__( self : str , lowerCAmelCase__ : Union[str, Any] ) -> Dict: """simple docstring""" super().__init__() _UpperCAmelCase : str = torchvision.models.resnetaaa(pretrained=lowerCAmelCase__ ) _UpperCAmelCase : List[str] = list(model.children() )[:-2] _UpperCAmelCase : str = nn.Sequential(*lowerCAmelCase__ ) _UpperCAmelCase : str = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def _lowerCAmelCase ( self : Tuple , lowerCAmelCase__ : str ) -> List[Any]: """simple docstring""" _UpperCAmelCase : List[Any] = self.pool(self.model(lowerCAmelCase__ ) ) _UpperCAmelCase : Tuple = torch.flatten(lowerCAmelCase__ , start_dim=2 ) _UpperCAmelCase : Dict = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class A__ ( UpperCamelCase ): """simple docstring""" def __init__( self : int , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any] ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase : Any = [json.loads(lowerCAmelCase__ ) for l in open(lowerCAmelCase__ )] _UpperCAmelCase : List[str] = os.path.dirname(lowerCAmelCase__ ) _UpperCAmelCase : str = tokenizer _UpperCAmelCase : int = labels _UpperCAmelCase : int = len(lowerCAmelCase__ ) _UpperCAmelCase : List[str] = max_seq_length _UpperCAmelCase : Tuple = transforms def __len__( self : List[Any] ) -> str: """simple docstring""" return len(self.data ) def __getitem__( self : List[str] , lowerCAmelCase__ : List[Any] ) -> int: """simple docstring""" _UpperCAmelCase : Optional[int] = torch.LongTensor(self.tokenizer.encode(self.data[index]["text"] , add_special_tokens=lowerCAmelCase__ ) ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : Optional[int] = sentence[0], sentence[1:-1], sentence[-1] _UpperCAmelCase : Dict = sentence[: self.max_seq_length] _UpperCAmelCase : Dict = torch.zeros(self.n_classes ) _UpperCAmelCase : Dict = 1 _UpperCAmelCase : List[Any] = Image.open(os.path.join(self.data_dir , self.data[index]["img"] ) ).convert("RGB" ) _UpperCAmelCase : Optional[int] = self.transforms(lowerCAmelCase__ ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def _lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" _UpperCAmelCase : Union[str, Any] = Counter() for row in self.data: label_freqs.update(row["label"] ) return label_freqs def __UpperCAmelCase ( a_: Optional[int] ): _UpperCAmelCase : Optional[Any] = [len(row["sentence"] ) for row in batch] _UpperCAmelCase , _UpperCAmelCase : int = len(a_ ), max(a_ ) _UpperCAmelCase : Union[str, Any] = torch.zeros(a_, a_, dtype=torch.long ) _UpperCAmelCase : List[str] = torch.zeros(a_, a_, dtype=torch.long ) for i_batch, (input_row, length) in enumerate(zip(a_, a_ ) ): _UpperCAmelCase : Tuple = input_row["sentence"] _UpperCAmelCase : int = 1 _UpperCAmelCase : List[Any] = torch.stack([row["image"] for row in batch] ) _UpperCAmelCase : Union[str, Any] = torch.stack([row["label"] for row in batch] ) _UpperCAmelCase : str = torch.stack([row["image_start_token"] for row in batch] ) _UpperCAmelCase : int = torch.stack([row["image_end_token"] for row in batch] ) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def __UpperCAmelCase ( ): return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def __UpperCAmelCase ( ): return transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize( mean=[0.46_77_70_44, 0.44_53_14_29, 0.40_66_10_17], std=[0.12_22_19_94, 0.12_14_58_35, 0.14_38_04_69], ), ] )
145
'''simple docstring''' from __future__ import annotations __a = list[tuple[int, int]] __a = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __a = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A__ : """simple docstring""" def __init__( self : List[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : float , lowerCAmelCase__ : Node | None , ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[str] = pos_x _UpperCAmelCase : List[Any] = pos_y _UpperCAmelCase : Optional[int] = (pos_y, pos_x) _UpperCAmelCase : Tuple = goal_x _UpperCAmelCase : List[str] = goal_y _UpperCAmelCase : str = g_cost _UpperCAmelCase : List[Any] = parent _UpperCAmelCase : str = self.calculate_heuristic() def _lowerCAmelCase ( self : str ) -> float: """simple docstring""" _UpperCAmelCase : Optional[Any] = abs(self.pos_x - self.goal_x ) _UpperCAmelCase : Optional[Any] = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self : Any , lowerCAmelCase__ : Optional[int] ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A__ : """simple docstring""" def __init__( self : Union[str, Any] , lowerCAmelCase__ : tuple[int, int] , lowerCAmelCase__ : tuple[int, int] ) -> List[str]: """simple docstring""" _UpperCAmelCase : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , lowerCAmelCase__ ) _UpperCAmelCase : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , lowerCAmelCase__ ) _UpperCAmelCase : Optional[int] = [self.start] _UpperCAmelCase : list[Node] = [] _UpperCAmelCase : List[Any] = False def _lowerCAmelCase ( self : Tuple ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() _UpperCAmelCase : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: _UpperCAmelCase : List[str] = True return self.retrace_path(lowerCAmelCase__ ) self.closed_nodes.append(lowerCAmelCase__ ) _UpperCAmelCase : Union[str, Any] = self.get_successors(lowerCAmelCase__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(lowerCAmelCase__ ) else: # retrieve the best current path _UpperCAmelCase : List[Any] = self.open_nodes.pop(self.open_nodes.index(lowerCAmelCase__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(lowerCAmelCase__ ) else: self.open_nodes.append(lowerCAmelCase__ ) if not self.reached: return [self.start.pos] return None def _lowerCAmelCase ( self : List[str] , lowerCAmelCase__ : Node ) -> list[Node]: """simple docstring""" _UpperCAmelCase : Union[str, Any] = [] for action in delta: _UpperCAmelCase : Tuple = parent.pos_x + action[1] _UpperCAmelCase : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(lowerCAmelCase__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( lowerCAmelCase__ , lowerCAmelCase__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , lowerCAmelCase__ , ) ) return successors def _lowerCAmelCase ( self : Any , lowerCAmelCase__ : Node | None ) -> Path: """simple docstring""" _UpperCAmelCase : Optional[int] = node _UpperCAmelCase : Any = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) _UpperCAmelCase : Any = current_node.parent path.reverse() return path if __name__ == "__main__": __a = (0, 0) __a = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') __a = GreedyBestFirst(init, goal) __a = greedy_bf.search() if path: for pos_x, pos_y in path: __a = 2 for elem in grid: print(elem)
145
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __magic_name__ ( unittest.TestCase): def __init__( self : Optional[int] , lowerCamelCase__ : List[str] , lowerCamelCase__ : List[Any]=7 , lowerCamelCase__ : Optional[Any]=3 , lowerCamelCase__ : int=18 , lowerCamelCase__ : Union[str, Any]=30 , lowerCamelCase__ : Tuple=400 , lowerCamelCase__ : str=True , lowerCamelCase__ : Dict=None , lowerCamelCase__ : List[Any]=True , ) -> Tuple: '''simple docstring''' UpperCamelCase__ : Optional[int] = size if size is not None else {'height': 18, 'width': 18} UpperCamelCase__ : str = parent UpperCamelCase__ : Optional[Any] = batch_size UpperCamelCase__ : Optional[int] = num_channels UpperCamelCase__ : int = image_size UpperCamelCase__ : int = min_resolution UpperCamelCase__ : Optional[int] = max_resolution UpperCamelCase__ : Union[str, Any] = do_resize UpperCamelCase__ : Dict = size UpperCamelCase__ : int = apply_ocr def UpperCAmelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class __magic_name__ ( __lowerCAmelCase , unittest.TestCase): A: Optional[int] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ : List[Any] = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self : str ) -> int: '''simple docstring''' UpperCamelCase__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''size''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''apply_ocr''' ) ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: '''simple docstring''' UpperCamelCase__ : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) UpperCamelCase__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def UpperCAmelCase__ ( self : Dict ) -> int: '''simple docstring''' pass def UpperCAmelCase__ ( self : Dict ) -> Tuple: '''simple docstring''' UpperCamelCase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , Image.Image ) # Test not batched input UpperCamelCase__ : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , lowerCamelCase__ ) self.assertIsInstance(encoding.boxes , lowerCamelCase__ ) # Test batched UpperCamelCase__ : List[Any] = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: '''simple docstring''' UpperCamelCase__ : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase__ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , numpify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , np.ndarray ) # Test not batched input UpperCamelCase__ : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched UpperCamelCase__ : List[Any] = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def UpperCAmelCase__ ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , torchify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , torch.Tensor ) # Test not batched input UpperCamelCase__ : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched UpperCamelCase__ : Dict = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCamelCase__ : Optional[Any] = LayoutLMvaImageProcessor() from datasets import load_dataset UpperCamelCase__ : Tuple = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) UpperCamelCase__ : Tuple = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) UpperCamelCase__ : Dict = image_processing(lowerCamelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 UpperCamelCase__ : Tuple = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 UpperCamelCase__ : List[str] = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , lowerCamelCase__ ) self.assertListEqual(encoding.boxes , lowerCamelCase__ ) # with apply_OCR = False UpperCamelCase__ : Tuple = LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase__ ) UpperCamelCase__ : Dict = image_processing(lowerCamelCase__ , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
362
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __UpperCamelCase : List[Any] = data_utils.TransfoXLTokenizer __UpperCamelCase : str = data_utils.TransfoXLCorpus __UpperCamelCase : Dict = data_utils __UpperCamelCase : List[Any] = data_utils def _a ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Dict ): """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(SCREAMING_SNAKE_CASE , '''rb''' ) as fp: UpperCamelCase__ : str = pickle.load(SCREAMING_SNAKE_CASE , encoding='''latin1''' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) UpperCamelCase__ : Tuple = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file'''] print(F"Save vocabulary to {pytorch_vocab_dump_path}" ) UpperCamelCase__ : List[str] = corpus.vocab.__dict__ torch.save(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : List[str] = corpus.__dict__ corpus_dict_no_vocab.pop('''vocab''' , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Optional[int] = pytorch_dump_folder_path + '''/''' + CORPUS_NAME print(F"Save dataset to {pytorch_dataset_dump_path}" ) torch.save(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model UpperCamelCase__ : List[Any] = os.path.abspath(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Union[str, Any] = os.path.abspath(SCREAMING_SNAKE_CASE ) print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}." ) # Initialise PyTorch model if transfo_xl_config_file == "": UpperCamelCase__ : Any = TransfoXLConfig() else: UpperCamelCase__ : int = TransfoXLConfig.from_json_file(SCREAMING_SNAKE_CASE ) print(F"Building PyTorch model from configuration: {config}" ) UpperCamelCase__ : Dict = TransfoXLLMHeadModel(SCREAMING_SNAKE_CASE ) UpperCamelCase__ : str = load_tf_weights_in_transfo_xl(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # Save pytorch-model UpperCamelCase__ : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) UpperCamelCase__ : Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) print(F"Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE )}" ) torch.save(model.state_dict() , SCREAMING_SNAKE_CASE ) print(F"Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE )}" ) with open(SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __UpperCamelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __UpperCamelCase : int = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
51
0
import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''): raise Exception('''requires fairseq >= 1.0.0a''') logging.set_verbosity_info() UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = '''Hello world! cécé herlolip''' def UpperCAmelCase_ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowercase = FairseqRobertaModel.from_pretrained(__SCREAMING_SNAKE_CASE ) roberta.eval() # disable dropout lowercase = roberta.model.encoder.sentence_encoder lowercase = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1e-5 , ) if classification_head: lowercase = roberta.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our RoBERTa config:' , __SCREAMING_SNAKE_CASE ) lowercase = XLMRobertaXLForSequenceClassification(__SCREAMING_SNAKE_CASE ) if classification_head else XLMRobertaXLForMaskedLM(__SCREAMING_SNAKE_CASE ) model.eval() # Now let's copy all the weights. # Embeddings lowercase = roberta_sent_encoder.embed_tokens.weight lowercase = roberta_sent_encoder.embed_positions.weight lowercase = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. lowercase = roberta_sent_encoder.layer_norm.weight lowercase = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer lowercase = model.roberta.encoder.layer[i] lowercase = roberta_sent_encoder.layers[i] lowercase = layer.attention lowercase = roberta_layer.self_attn_layer_norm.weight lowercase = roberta_layer.self_attn_layer_norm.bias # self attention lowercase = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) lowercase = roberta_layer.self_attn.q_proj.weight lowercase = roberta_layer.self_attn.q_proj.bias lowercase = roberta_layer.self_attn.k_proj.weight lowercase = roberta_layer.self_attn.k_proj.bias lowercase = roberta_layer.self_attn.v_proj.weight lowercase = roberta_layer.self_attn.v_proj.bias # self-attention output lowercase = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape lowercase = roberta_layer.self_attn.out_proj.weight lowercase = roberta_layer.self_attn.out_proj.bias # this one is final layer norm lowercase = roberta_layer.final_layer_norm.weight lowercase = roberta_layer.final_layer_norm.bias # intermediate lowercase = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape lowercase = roberta_layer.fca.weight lowercase = roberta_layer.fca.bias # output lowercase = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape lowercase = roberta_layer.fca.weight lowercase = roberta_layer.fca.bias # end of layer if classification_head: lowercase = roberta.model.classification_heads['mnli'].dense.weight lowercase = roberta.model.classification_heads['mnli'].dense.bias lowercase = roberta.model.classification_heads['mnli'].out_proj.weight lowercase = roberta.model.classification_heads['mnli'].out_proj.bias else: # LM Head lowercase = roberta.model.encoder.lm_head.dense.weight lowercase = roberta.model.encoder.lm_head.dense.bias lowercase = roberta.model.encoder.lm_head.layer_norm.weight lowercase = roberta.model.encoder.lm_head.layer_norm.bias lowercase = roberta.model.encoder.lm_head.weight lowercase = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. lowercase = roberta.encode(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) # batch of size 1 lowercase = model(__SCREAMING_SNAKE_CASE )[0] if classification_head: lowercase = roberta.model.classification_heads['mnli'](roberta.extract_features(__SCREAMING_SNAKE_CASE ) ) else: lowercase = roberta.model(__SCREAMING_SNAKE_CASE )[0] print(our_output.shape , their_output.shape ) lowercase = torch.max(torch.abs(our_output - their_output ) ).item() print(F'''max_absolute_diff = {max_absolute_diff}''' ) # ~ 1e-7 lowercase = torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) pathlib.Path(__SCREAMING_SNAKE_CASE ).mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--roberta_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.''' ) UpperCAmelCase = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
195
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 A_ : '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case ): return None class A_ : '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case ): return None class A_ ( unittest.TestCase ): '''simple docstring''' _UpperCamelCase : Tuple = [ # (model_name, model_kwargs) ("""bert-base-cased""", {}), ("""gpt2""", {"""use_cache""": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def SCREAMING_SNAKE_CASE__ ( self ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(snake_case , 'tf' , 12 , **snake_case ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(snake_case , 'pt' , 12 , **snake_case ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ): from transformers import BertModel lowercase = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(snake_case ) ) vocab_file.flush() lowercase = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: lowercase = BertModel(BertConfig(vocab_size=len(snake_case ) ) ) model.save_pretrained(snake_case ) self._test_export(snake_case , 'pt' , 12 , snake_case ) @require_tf @slow def SCREAMING_SNAKE_CASE__ ( self ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowercase = self._test_export(snake_case , 'tf' , 12 , **snake_case ) lowercase = quantize(Path(snake_case ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(snake_case ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def SCREAMING_SNAKE_CASE__ ( self ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: lowercase = self._test_export(snake_case , 'pt' , 12 , **snake_case ) lowercase = quantize(snake_case ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(snake_case ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case , snake_case=None , **snake_case ): try: # Compute path with TemporaryDirectory() as tempdir: lowercase = Path(snake_case ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(snake_case , snake_case , snake_case , snake_case , snake_case , **snake_case ) return path except Exception as e: self.fail(snake_case ) @require_torch @require_tokenizers @slow def SCREAMING_SNAKE_CASE__ ( self ): from transformers import BertModel lowercase = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowercase = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(snake_case , snake_case , 'pt' ) @require_tf @require_tokenizers @slow def SCREAMING_SNAKE_CASE__ ( self ): from transformers import TFBertModel lowercase = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) lowercase = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(snake_case , snake_case , 'tf' ) def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case , snake_case ): lowercase = FeatureExtractionPipeline(snake_case , snake_case ) lowercase = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] lowercase , lowercase , lowercase , lowercase = infer_shapes(snake_case , snake_case ) # Assert all variables are present self.assertEqual(len(snake_case ) , len(snake_case ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , snake_case ) self.assertSequenceEqual(variable_names[3:] , 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 SCREAMING_SNAKE_CASE__ ( self ): lowercase = ['input_ids', 'attention_mask', 'token_type_ids'] lowercase = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} lowercase , lowercase = ensure_valid_input(FuncContiguousArgs() , snake_case , snake_case ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(snake_case ) , 3 ) # Should have exactly the same input names self.assertEqual(set(snake_case ) , set(snake_case ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(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) lowercase , lowercase = ensure_valid_input(FuncNonContiguousArgs() , snake_case , snake_case ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(snake_case ) , 1 ) self.assertEqual(len(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 SCREAMING_SNAKE_CASE__ ( self ): lowercase = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
195
1
'''simple docstring''' from __future__ import annotations from math import ceil, floor, sqrt def _snake_case ( A = 2000000 ) -> int: lowerCAmelCase__ = [0] lowerCAmelCase__ = 42 for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target lowerCAmelCase__ = 0 # the area corresponding to the grid that gives the product closest to target lowerCAmelCase__ = 0 # an estimate of b, using the quadratic formula lowerCAmelCase__ = 42 # the largest integer less than b_estimate lowerCAmelCase__ = 42 # the largest integer less than b_estimate lowerCAmelCase__ = 42 # the triangle number corresponding to b_floor lowerCAmelCase__ = 42 # the triangle number corresponding to b_ceil lowerCAmelCase__ = 42 for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): lowerCAmelCase__ = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 lowerCAmelCase__ = floor(A ) lowerCAmelCase__ = ceil(A ) lowerCAmelCase__ = triangle_numbers[b_floor] lowerCAmelCase__ = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): lowerCAmelCase__ = triangle_b_first_guess * triangle_a lowerCAmelCase__ = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): lowerCAmelCase__ = triangle_b_second_guess * triangle_a lowerCAmelCase__ = idx_a * b_ceil return area if __name__ == "__main__": print(f"""{solution() = }""")
228
'''simple docstring''' import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging __UpperCAmelCase = logging.get_logger(__name__) class a__ ( a__ ): '''simple docstring''' lowercase__ : int = "linear" lowercase__ : Any = "cosine" lowercase__ : Optional[int] = "cosine_with_restarts" lowercase__ : Optional[Any] = "polynomial" lowercase__ : Tuple = "constant" lowercase__ : Optional[int] = "constant_with_warmup" lowercase__ : Optional[int] = "piecewise_constant" def _snake_case ( A , A = -1 ) -> Any: return LambdaLR(A , lambda A : 1 , last_epoch=A ) def _snake_case ( A , A , A = -1 ) -> Optional[Any]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1.0 , A ) ) return 1.0 return LambdaLR(A , A , last_epoch=A ) def _snake_case ( A , A , A = -1 ) -> Union[str, Any]: lowerCAmelCase__ = {} lowerCAmelCase__ = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: lowerCAmelCase__ , lowerCAmelCase__ = rule_str.split(''':''' ) lowerCAmelCase__ = int(A ) lowerCAmelCase__ = float(A ) lowerCAmelCase__ = value lowerCAmelCase__ = float(rule_list[-1] ) def create_rules_function(A , A ): def rule_func(A ) -> float: lowerCAmelCase__ = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(A ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func lowerCAmelCase__ = create_rules_function(A , A ) return LambdaLR(A , A , last_epoch=A ) def _snake_case ( A , A , A , A=-1 ) -> Optional[int]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A = 0.5 , A = -1 ) -> List[str]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) lowerCAmelCase__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(A ) * 2.0 * progress )) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A = 1 , A = -1 ) -> Union[str, Any]: def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) lowerCAmelCase__ = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(A ) * progress) % 1.0) )) ) return LambdaLR(A , A , A ) def _snake_case ( A , A , A , A=1E-7 , A=1.0 , A=-1 ) -> Union[str, Any]: lowerCAmelCase__ = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(F"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})""" ) def lr_lambda(A ): if current_step < num_warmup_steps: return float(A ) / float(max(1 , A ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: lowerCAmelCase__ = lr_init - lr_end lowerCAmelCase__ = num_training_steps - num_warmup_steps lowerCAmelCase__ = 1 - (current_step - num_warmup_steps) / decay_steps lowerCAmelCase__ = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(A , A , A ) __UpperCAmelCase = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def _snake_case ( A , A , A = None , A = None , A = None , A = 1 , A = 1.0 , A = -1 , ) -> int: lowerCAmelCase__ = SchedulerType(A ) lowerCAmelCase__ = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(A , last_epoch=A ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(A , step_rules=A , last_epoch=A ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(F"""{name} requires `num_warmup_steps`, please provide that argument.""" ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(A , num_warmup_steps=A , last_epoch=A ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(F"""{name} requires `num_training_steps`, please provide that argument.""" ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( A , num_warmup_steps=A , num_training_steps=A , num_cycles=A , last_epoch=A , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( A , num_warmup_steps=A , num_training_steps=A , power=A , last_epoch=A , ) return schedule_func( A , num_warmup_steps=A , num_training_steps=A , last_epoch=A )
228
1
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device A = False class __lowercase ( unittest.TestCase ): '''simple docstring''' pass @nightly @require_torch_gpu class __lowercase ( unittest.TestCase ): '''simple docstring''' def _lowerCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCamelCase ( self ): __a : Union[str, Any] = VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion''' ) # remove text_unet pipe.remove_unused_weights() pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : Union[str, Any] = '''A painting of a squirrel eating a burger ''' __a : int = torch.manual_seed(0 ) __a : str = pipe( prompt=_UpperCAmelCase , generator=_UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_UpperCAmelCase ) __a : str = VersatileDiffusionTextToImagePipeline.from_pretrained(_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : List[Any] = generator.manual_seed(0 ) __a : Any = pipe( prompt=_UpperCAmelCase , generator=_UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _lowerCamelCase ( self ): __a : List[Any] = VersatileDiffusionTextToImagePipeline.from_pretrained( '''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : int = '''A painting of a squirrel eating a burger ''' __a : Dict = torch.manual_seed(0 ) __a : Optional[Any] = pipe( prompt=_UpperCAmelCase , generator=_UpperCAmelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images __a : Dict = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a : List[Any] = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
160
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : str = logging.get_logger(__name__) __lowercase : Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __lowercase ( _lowercase ): lowerCamelCase : int = "ctrl" lowerCamelCase : Optional[int] = ["past_key_values"] lowerCamelCase : Optional[int] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__(self , A=2_4_6_5_3_4 , A=2_5_6 , A=1_2_8_0 , A=8_1_9_2 , A=4_8 , A=1_6 , A=0.1 , A=0.1 , A=1E-6 , A=0.02 , A=True , **A , ): lowerCamelCase_ : List[str] = vocab_size lowerCamelCase_ : Optional[Any] = n_positions lowerCamelCase_ : List[Any] = n_embd lowerCamelCase_ : Optional[Any] = n_layer lowerCamelCase_ : Any = n_head lowerCamelCase_ : int = dff lowerCamelCase_ : str = resid_pdrop lowerCamelCase_ : List[Any] = embd_pdrop lowerCamelCase_ : List[Any] = layer_norm_epsilon lowerCamelCase_ : Any = initializer_range lowerCamelCase_ : Dict = use_cache super().__init__(**A )
318
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def lowerCamelCase ( _UpperCamelCase : Any ) -> int: '''simple docstring''' if "cls_token" in name: __UpperCAmelCase : Dict = name.replace("""cls_token""" , """vit.embeddings.cls_token""" ) if "mask_token" in name: __UpperCAmelCase : Dict = name.replace("""mask_token""" , """decoder.mask_token""" ) if "decoder_pos_embed" in name: __UpperCAmelCase : int = name.replace("""decoder_pos_embed""" , """decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: __UpperCAmelCase : int = name.replace("""pos_embed""" , """vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: __UpperCAmelCase : List[str] = name.replace("""patch_embed.proj""" , """vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: __UpperCAmelCase : Optional[int] = name.replace("""patch_embed.norm""" , """vit.embeddings.norm""" ) if "decoder_blocks" in name: __UpperCAmelCase : List[str] = name.replace("""decoder_blocks""" , """decoder.decoder_layers""" ) if "blocks" in name: __UpperCAmelCase : Any = name.replace("""blocks""" , """vit.encoder.layer""" ) if "attn.proj" in name: __UpperCAmelCase : Dict = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: __UpperCAmelCase : str = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: __UpperCAmelCase : Optional[Any] = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: __UpperCAmelCase : Dict = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: __UpperCAmelCase : Tuple = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: __UpperCAmelCase : Optional[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if "decoder_embed" in name: __UpperCAmelCase : List[Any] = name.replace("""decoder_embed""" , """decoder.decoder_embed""" ) if "decoder_norm" in name: __UpperCAmelCase : Optional[Any] = name.replace("""decoder_norm""" , """decoder.decoder_norm""" ) if "decoder_pred" in name: __UpperCAmelCase : List[str] = name.replace("""decoder_pred""" , """decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: __UpperCAmelCase : str = name.replace("""norm.weight""" , """vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: __UpperCAmelCase : Tuple = name.replace("""norm.bias""" , """vit.layernorm.bias""" ) return name def lowerCamelCase ( _UpperCamelCase : Dict , _UpperCamelCase : List[str] ) -> Optional[int]: '''simple docstring''' for key in orig_state_dict.copy().keys(): __UpperCAmelCase : Optional[Any] = orig_state_dict.pop(_UpperCamelCase ) if "qkv" in key: __UpperCAmelCase : str = key.split(""".""" ) __UpperCAmelCase : Tuple = int(key_split[1] ) if "decoder_blocks" in key: __UpperCAmelCase : str = config.decoder_hidden_size __UpperCAmelCase : Dict = """decoder.decoder_layers.""" if "weight" in key: __UpperCAmelCase : Any = val[:dim, :] __UpperCAmelCase : Tuple = val[dim : dim * 2, :] __UpperCAmelCase : Union[str, Any] = val[-dim:, :] elif "bias" in key: __UpperCAmelCase : Tuple = val[:dim] __UpperCAmelCase : Any = val[dim : dim * 2] __UpperCAmelCase : List[Any] = val[-dim:] else: __UpperCAmelCase : Tuple = config.hidden_size __UpperCAmelCase : Tuple = """vit.encoder.layer.""" if "weight" in key: __UpperCAmelCase : Any = val[:dim, :] __UpperCAmelCase : Union[str, Any] = val[dim : dim * 2, :] __UpperCAmelCase : int = val[-dim:, :] elif "bias" in key: __UpperCAmelCase : int = val[:dim] __UpperCAmelCase : List[Any] = val[dim : dim * 2] __UpperCAmelCase : Dict = val[-dim:] else: __UpperCAmelCase : List[Any] = val return orig_state_dict def lowerCamelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Tuple ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : int = ViTMAEConfig() if "large" in checkpoint_url: __UpperCAmelCase : int = 1_0_2_4 __UpperCAmelCase : Dict = 4_0_9_6 __UpperCAmelCase : Optional[int] = 2_4 __UpperCAmelCase : int = 1_6 elif "huge" in checkpoint_url: __UpperCAmelCase : Tuple = 1_4 __UpperCAmelCase : Tuple = 1_2_8_0 __UpperCAmelCase : Optional[Any] = 5_1_2_0 __UpperCAmelCase : str = 3_2 __UpperCAmelCase : Union[str, Any] = 1_6 __UpperCAmelCase : List[str] = ViTMAEForPreTraining(_UpperCamelCase ) __UpperCAmelCase : List[Any] = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location="""cpu""" )["""model"""] __UpperCAmelCase : Union[str, Any] = ViTMAEImageProcessor(size=config.image_size ) __UpperCAmelCase : Tuple = convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) model.eval() __UpperCAmelCase : int = """https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg""" __UpperCAmelCase : Any = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) __UpperCAmelCase : Tuple = ViTMAEImageProcessor(size=config.image_size ) __UpperCAmelCase : Any = image_processor(images=_UpperCamelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) __UpperCAmelCase : int = model(**_UpperCamelCase ) __UpperCAmelCase : Optional[Any] = outputs.logits if "large" in checkpoint_url: __UpperCAmelCase : Optional[int] = torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: __UpperCAmelCase : Optional[Any] = torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: __UpperCAmelCase : Union[str, Any] = torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(_UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth', type=str, help='URL of the 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.' ) UpperCAmelCase : str = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
320
"""simple docstring""" import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html UpperCAmelCase : Optional[int] = 'platform' import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class lowerCamelCase__ : """simple docstring""" __a = PegasusConfig __a = {} __a = """gelu""" def __init__( self : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Tuple=13 , UpperCamelCase : Tuple=7 , UpperCamelCase : Dict=True , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Union[str, Any]=32 , UpperCamelCase : Union[str, Any]=5 , UpperCamelCase : Any=4 , UpperCamelCase : Tuple=37 , UpperCamelCase : Any=0.1 , UpperCamelCase : Any=0.1 , UpperCamelCase : Union[str, Any]=20 , UpperCamelCase : List[str]=2 , UpperCamelCase : int=1 , UpperCamelCase : Optional[Any]=0 , ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = parent __UpperCAmelCase : str = batch_size __UpperCAmelCase : Optional[Any] = seq_length __UpperCAmelCase : Dict = is_training __UpperCAmelCase : Dict = use_labels __UpperCAmelCase : List[Any] = vocab_size __UpperCAmelCase : Dict = hidden_size __UpperCAmelCase : Optional[Any] = num_hidden_layers __UpperCAmelCase : Union[str, Any] = num_attention_heads __UpperCAmelCase : List[Any] = intermediate_size __UpperCAmelCase : Union[str, Any] = hidden_dropout_prob __UpperCAmelCase : List[str] = attention_probs_dropout_prob __UpperCAmelCase : List[Any] = max_position_embeddings __UpperCAmelCase : Any = eos_token_id __UpperCAmelCase : Optional[int] = pad_token_id __UpperCAmelCase : List[str] = bos_token_id def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) __UpperCAmelCase : str = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) __UpperCAmelCase : Union[str, Any] = np.concatenate([input_ids, eos_tensor] , axis=1 ) __UpperCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCAmelCase : Any = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __UpperCAmelCase : Any = prepare_pegasus_inputs_dict(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return config, inputs_dict def lowerCamelCase__ ( self : Dict , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 20 __UpperCAmelCase : Tuple = model_class_name(UpperCamelCase ) __UpperCAmelCase : List[Any] = model.encode(inputs_dict["""input_ids"""] ) __UpperCAmelCase ,__UpperCAmelCase : int = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCAmelCase : Tuple = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : Any = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) __UpperCAmelCase : Optional[int] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCAmelCase : Union[str, Any] = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) __UpperCAmelCase : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCAmelCase : Tuple = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCamelCase , ) __UpperCAmelCase : Dict = model.decode(UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase : List[Any] , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = 20 __UpperCAmelCase : int = model_class_name(UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = model.encode(inputs_dict["""input_ids"""] ) __UpperCAmelCase ,__UpperCAmelCase : Dict = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) __UpperCAmelCase : int = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) __UpperCAmelCase : int = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : List[Any] = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) __UpperCAmelCase : List[str] = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) __UpperCAmelCase : Optional[int] = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) __UpperCAmelCase : Optional[int] = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) __UpperCAmelCase : Union[str, Any] = model.decode(UpperCamelCase , UpperCamelCase , decoder_attention_mask=UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'''Max diff is {diff}''' ) def lowerCamelCase ( _UpperCamelCase : List[Any] , _UpperCamelCase : Optional[Any] , _UpperCamelCase : Tuple , _UpperCamelCase : List[str]=None , _UpperCamelCase : Any=None , ) -> Dict: '''simple docstring''' if attention_mask is None: __UpperCAmelCase : Optional[int] = np.not_equal(_UpperCamelCase , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: __UpperCAmelCase : Dict = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class lowerCamelCase__ ( A , unittest.TestCase ): """simple docstring""" __a = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __a = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __a = True __a = False __a = False __a = False def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' __UpperCAmelCase : List[Any] = FlaxPegasusModelTester(self ) __UpperCAmelCase : List[str] = ConfigTester(self , config_class=UpperCamelCase ) def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' __UpperCAmelCase ,__UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' __UpperCAmelCase ,__UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' __UpperCAmelCase ,__UpperCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCAmelCase : Tuple = self._prepare_for_class(UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : Dict = model_class(UpperCamelCase ) @jax.jit def encode_jitted(UpperCamelCase : Optional[Any] , UpperCamelCase : List[Any]=None , **UpperCamelCase : List[str] ): return model.encode(input_ids=UpperCamelCase , attention_mask=UpperCamelCase ) with self.subTest("""JIT Enabled""" ): __UpperCAmelCase : Tuple = encode_jitted(**UpperCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCAmelCase : Optional[int] = encode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase , UpperCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' __UpperCAmelCase ,__UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __UpperCAmelCase : int = model_class(UpperCamelCase ) __UpperCAmelCase : int = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) __UpperCAmelCase : Any = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(UpperCamelCase : Union[str, Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[int] ): return model.decode( decoder_input_ids=UpperCamelCase , decoder_attention_mask=UpperCamelCase , encoder_outputs=UpperCamelCase , ) with self.subTest("""JIT Enabled""" ): __UpperCAmelCase : Union[str, Any] = decode_jitted(**UpperCamelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): __UpperCAmelCase : str = decode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase , UpperCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' for model_class_name in self.all_model_classes: __UpperCAmelCase : Optional[Any] = model_class_name.from_pretrained("""google/pegasus-large""" , from_pt=UpperCamelCase ) __UpperCAmelCase : Optional[int] = np.ones((1, 1) ) __UpperCAmelCase : List[str] = model(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @slow def lowerCamelCase__ ( self : Dict ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = FlaxPegasusForConditionalGeneration.from_pretrained("""google/pegasus-xsum""" ) __UpperCAmelCase : Union[str, Any] = PegasusTokenizer.from_pretrained("""google/pegasus-xsum""" ) __UpperCAmelCase : List[Any] = [ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""", """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category.\"We got told like this morning 'Oh I think you're nominated'\", said Dappy.\"And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!\"Bandmate Fazer added: \"We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations.\"The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around.\"At the end of the day we're grateful to be where we are in our careers.\"If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans.\"Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border.\"We just done Edinburgh the other day,\" said Dappy.\"We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!\" """, ] __UpperCAmelCase : List[str] = [ """California's largest electricity provider has turned off power to hundreds of thousands of customers.""", """Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.""", ] __UpperCAmelCase : List[str] = tokenizer(UpperCamelCase , return_tensors="""np""" , truncation=UpperCamelCase , max_length=512 , padding=UpperCamelCase ) __UpperCAmelCase : int = model.generate(**UpperCamelCase , num_beams=2 ).sequences __UpperCAmelCase : str = tokenizer.batch_decode(UpperCamelCase , skip_special_tokens=UpperCamelCase ) assert tgt_text == decoded
320
1
import unittest from transformers import 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
import unittest from transformers import 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=1_3 , SCREAMING_SNAKE_CASE__ : str=7 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=9_9 , SCREAMING_SNAKE_CASE__ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Tuple=3_7 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=5_1_2 , SCREAMING_SNAKE_CASE__ : int=1_6 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : Any=0.02 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> Any: a_ : Tuple = parent a_ : int = batch_size a_ : Tuple = seq_length a_ : List[Any] = is_training a_ : List[str] = use_token_type_ids a_ : Dict = use_labels a_ : Any = vocab_size a_ : List[str] = hidden_size a_ : Tuple = num_hidden_layers a_ : List[Any] = num_attention_heads a_ : Dict = intermediate_size a_ : Any = hidden_act a_ : List[str] = hidden_dropout_prob a_ : Tuple = attention_probs_dropout_prob a_ : Optional[Any] = max_position_embeddings a_ : List[Any] = type_vocab_size a_ : int = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : str = scope a_ : Tuple = self.vocab_size - 1 def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any: a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Any = None if self.use_token_type_ids: a_ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : List[Any] = None a_ : Union[str, Any] = None a_ : List[Any] = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) a_ : Union[str, Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) a_ : List[str] = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: a_ : Dict = OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , head_mask=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ ) a_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: a_ : str = OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: a_ : int = OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : str = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , *SCREAMING_SNAKE_CASE__ : str ) -> List[str]: a_ : Any = self.num_labels a_ : Dict = OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() a_ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Any = model(SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: a_ : Optional[Any] = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Optional[Any] = config_and_inputs a_ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'head_mask': head_mask, } return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE__ ( lowercase__ , lowercase__ , lowercase__ , unittest.TestCase ): snake_case__ : Tuple = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) snake_case__ : List[str] = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly snake_case__ : Dict = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=False ) -> List[str]: a_ : str = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": a_ : Optional[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : str = inputs_dict['labels'] a_ : Optional[int] = inputs_dict['labels'] a_ : Optional[int] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ , ) a_ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: a_ : str = OpenAIGPTModelTester(self ) a_ : int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , n_embd=3_7 ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: a_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any ) -> Optional[Any]: a_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Optional[Any]: a_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str: for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ : str = OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self : Dict ) -> int: a_ : Dict = OpenAIGPTLMHeadModel.from_pretrained('openai-gpt' ) model.to(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) # the president is a_ : Tuple = [ 4_8_1, 4_7_3_5, 5_4_4, 2_4_6, 9_6_3, 8_7_0, 7_6_2, 2_3_9, 2_4_4, 4_0_4_7_7, 2_4_4, 2_4_9, 7_1_9, 8_8_1, 4_8_7, 5_4_4, 2_4_0, 2_4_4, 6_0_3, 4_8_1, ] # the president is a very good man. " \n " i\'m sure he is, " said the a_ : Dict = model.generate(SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE__ )
32
1
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]: if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__UpperCAmelCase , '''rb''' ) as fp: lowercase__: str = pickle.load(__UpperCAmelCase , encoding='''latin1''' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowercase__: Dict = pytorch_dump_folder_path + '''/''' + VOCAB_FILES_NAMES['''pretrained_vocab_file'''] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowercase__: Tuple = corpus.vocab.__dict__ torch.save(__UpperCAmelCase , __UpperCAmelCase ) lowercase__: Any = corpus.__dict__ corpus_dict_no_vocab.pop('''vocab''' , __UpperCAmelCase ) lowercase__: Optional[int] = pytorch_dump_folder_path + '''/''' + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__UpperCAmelCase , __UpperCAmelCase ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowercase__: List[Any] = os.path.abspath(__UpperCAmelCase ) lowercase__: List[Any] = os.path.abspath(__UpperCAmelCase ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowercase__: Optional[Any] = TransfoXLConfig() else: lowercase__: Any = TransfoXLConfig.from_json_file(__UpperCAmelCase ) print(F"""Building PyTorch model from configuration: {config}""" ) lowercase__: Optional[Any] = TransfoXLLMHeadModel(__UpperCAmelCase ) lowercase__: Optional[Any] = load_tf_weights_in_transfo_xl(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # Save pytorch-model lowercase__: List[Any] = os.path.join(__UpperCAmelCase , __UpperCAmelCase ) lowercase__: Optional[int] = os.path.join(__UpperCAmelCase , __UpperCAmelCase ) print(F"""Save PyTorch model to {os.path.abspath(__UpperCAmelCase )}""" ) torch.save(model.state_dict() , __UpperCAmelCase ) print(F"""Save configuration file to {os.path.abspath(__UpperCAmelCase )}""" ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
358
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "microsoft/cvt-13": "https://huggingface.co/microsoft/cvt-13/resolve/main/config.json", # See all Cvt models at https://huggingface.co/models?filter=cvt } class UpperCAmelCase (_UpperCAmelCase ): """simple docstring""" _UpperCAmelCase :Tuple = "cvt" def __init__( self , _UpperCAmelCase=3 , _UpperCAmelCase=[7, 3, 3] , _UpperCAmelCase=[4, 2, 2] , _UpperCAmelCase=[2, 1, 1] , _UpperCAmelCase=[64, 192, 384] , _UpperCAmelCase=[1, 3, 6] , _UpperCAmelCase=[1, 2, 10] , _UpperCAmelCase=[4.0, 4.0, 4.0] , _UpperCAmelCase=[0.0, 0.0, 0.0] , _UpperCAmelCase=[0.0, 0.0, 0.0] , _UpperCAmelCase=[0.0, 0.0, 0.1] , _UpperCAmelCase=[True, True, True] , _UpperCAmelCase=[False, False, True] , _UpperCAmelCase=["dw_bn", "dw_bn", "dw_bn"] , _UpperCAmelCase=[3, 3, 3] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=[2, 2, 2] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=0.02 , _UpperCAmelCase=1e-1_2 , **_UpperCAmelCase , ): super().__init__(**_UpperCAmelCase ) lowercase__: Dict = num_channels lowercase__: str = patch_sizes lowercase__: Optional[Any] = patch_stride lowercase__: List[str] = patch_padding lowercase__: Optional[Any] = embed_dim lowercase__: Optional[int] = num_heads lowercase__: Any = depth lowercase__: str = mlp_ratio lowercase__: Any = attention_drop_rate lowercase__: Any = drop_rate lowercase__: Optional[Any] = drop_path_rate lowercase__: Dict = qkv_bias lowercase__: Dict = cls_token lowercase__: Any = qkv_projection_method lowercase__: List[str] = kernel_qkv lowercase__: Union[str, Any] = padding_kv lowercase__: Optional[int] = stride_kv lowercase__: int = padding_q lowercase__: Dict = stride_q lowercase__: Any = initializer_range lowercase__: Union[str, Any] = layer_norm_eps
2
0
def lowerCAmelCase_ ( __a ) -> int: """simple docstring""" if not isinstance(__a , __a ): raise TypeError("only integers accepted as input" ) else: lowerCamelCase__: Tuple =str(abs(__a ) ) lowerCamelCase__: Union[str, Any] =[list(__a ) for char in range(len(__a ) )] for index in range(len(__a ) ): num_transpositions[index].pop(__a ) return max( int("".join(list(__a ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
10
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 __snake_case : def __init__( self : List[str] , _snake_case : Union[str, Any] , _snake_case : List[str]=2 , _snake_case : Any=True , _snake_case : Any=False , _snake_case : List[str]=10 , _snake_case : Any=3 , _snake_case : Union[str, Any]=32 * 4 , _snake_case : List[Any]=32 * 6 , _snake_case : Tuple=4 , _snake_case : Dict=32 , ): """simple docstring""" UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = is_training UpperCAmelCase_ = use_auxiliary_loss UpperCAmelCase_ = num_queries UpperCAmelCase_ = num_channels UpperCAmelCase_ = min_size UpperCAmelCase_ = max_size UpperCAmelCase_ = num_labels UpperCAmelCase_ = mask_feature_size def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( _snake_case) UpperCAmelCase_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_snake_case) UpperCAmelCase_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_snake_case) > 0.5 ).float() UpperCAmelCase_ = (torch.rand((self.batch_size, self.num_labels) , device=_snake_case) > 0.5).long() UpperCAmelCase_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowerCamelCase ( self : Any): """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 : int): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def lowerCamelCase ( self : str , _snake_case : List[Any] , _snake_case : List[str]): """simple docstring""" UpperCAmelCase_ = output.encoder_hidden_states UpperCAmelCase_ = output.pixel_decoder_hidden_states UpperCAmelCase_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_snake_case) , len(config.backbone_config.depths)) self.parent.assertTrue(len(_snake_case) , len(config.backbone_config.depths)) self.parent.assertTrue(len(_snake_case) , config.decoder_config.decoder_layers) def lowerCamelCase ( self : Union[str, Any] , _snake_case : List[str] , _snake_case : int , _snake_case : Optional[Any] , _snake_case : str=False): """simple docstring""" with torch.no_grad(): UpperCAmelCase_ = MaskFormerModel(config=_snake_case) model.to(_snake_case) model.eval() UpperCAmelCase_ = model(pixel_values=_snake_case , pixel_mask=_snake_case) UpperCAmelCase_ = model(_snake_case , output_hidden_states=_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(_snake_case , _snake_case) def lowerCamelCase ( self : List[Any] , _snake_case : List[Any] , _snake_case : List[Any] , _snake_case : str , _snake_case : Optional[int] , _snake_case : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerForInstanceSegmentation(config=_snake_case) model.to(_snake_case) model.eval() def comm_check_on_output(_snake_case : Tuple): # 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(): UpperCAmelCase_ = model(pixel_values=_snake_case , pixel_mask=_snake_case) UpperCAmelCase_ = model(_snake_case) comm_check_on_output(_snake_case) UpperCAmelCase_ = model( pixel_values=_snake_case , pixel_mask=_snake_case , mask_labels=_snake_case , class_labels=_snake_case) comm_check_on_output(_snake_case) self.parent.assertTrue(result.loss is not None) self.parent.assertEqual(result.loss.shape , torch.Size([1])) @require_torch class __snake_case ( a , a , unittest.TestCase ): UpperCAmelCase__ : Union[str, Any] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () UpperCAmelCase__ : Optional[Any] = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) UpperCAmelCase__ : Dict = False UpperCAmelCase__ : List[str] = False UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Union[str, Any] = False def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerModelTester(self) UpperCAmelCase_ = ConfigTester(self , config_class=_snake_case , has_text_modality=_snake_case) def lowerCamelCase ( self : List[Any]): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_snake_case , **_snake_case , output_hidden_states=_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_snake_case) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''') def lowerCamelCase ( self : Dict): """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''') def lowerCamelCase ( self : int): """simple docstring""" pass @unittest.skip(reason='''MaskFormer is not a generative model''') def lowerCamelCase ( self : str): """simple docstring""" pass @unittest.skip(reason='''MaskFormer does not use token embeddings''') def lowerCamelCase ( self : int): """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 : Any): """simple docstring""" pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''') def lowerCamelCase ( self : str): """simple docstring""" pass def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(_snake_case) UpperCAmelCase_ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _snake_case) @slow def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCAmelCase_ = MaskFormerModel.from_pretrained(_snake_case) self.assertIsNotNone(_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = (self.model_tester.min_size,) * 2 UpperCAmelCase_ = { '''pixel_values''': torch.randn((2, 3, *size) , device=_snake_case), '''mask_labels''': torch.randn((2, 10, *size) , device=_snake_case), '''class_labels''': torch.zeros(2 , 10 , device=_snake_case).long(), } UpperCAmelCase_ = MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(_snake_case) UpperCAmelCase_ = model(**_snake_case) self.assertTrue(outputs.loss is not None) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_snake_case , **_snake_case , output_hidden_states=_snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(_snake_case).to(_snake_case) UpperCAmelCase_ = model(**_snake_case , output_attentions=_snake_case) self.assertTrue(outputs.attentions is not None) def lowerCamelCase ( self : int): """simple docstring""" if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = model_class(_snake_case) model.to(_snake_case) model.train() UpperCAmelCase_ = model(_snake_case , mask_labels=_snake_case , class_labels=_snake_case).loss loss.backward() def lowerCamelCase ( self : Optional[int]): """simple docstring""" UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = True UpperCAmelCase_ = True UpperCAmelCase_ = model_class(_snake_case) model.to(_snake_case) model.train() UpperCAmelCase_ = model(_snake_case , mask_labels=_snake_case , class_labels=_snake_case) UpperCAmelCase_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCAmelCase_ = 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 UpperCAmelCase_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_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) snake_case_ : Dict = 1e-4 def A () -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class __snake_case ( unittest.TestCase ): @cached_property def lowerCamelCase ( self : List[str]): """simple docstring""" return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''') if is_vision_available() else None ) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''').to(_snake_case) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = 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(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) UpperCAmelCase_ = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _snake_case , atol=_snake_case)) UpperCAmelCase_ = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _snake_case , atol=_snake_case)) UpperCAmelCase_ = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]]).to(_snake_case) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = 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(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) # masks_queries_logits UpperCAmelCase_ = 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) , ) UpperCAmelCase_ = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] UpperCAmelCase_ = torch.tensor(_snake_case).to(_snake_case) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _snake_case , atol=_snake_case)) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)) UpperCAmelCase_ = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ]).to(_snake_case) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(_snake_case , return_tensors='''pt''').to(_snake_case) UpperCAmelCase_ = 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(_snake_case , (1, 3, 800, 1088)) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) # masks_queries_logits UpperCAmelCase_ = 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) , ) UpperCAmelCase_ = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] UpperCAmelCase_ = torch.tensor(_snake_case).to(_snake_case) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _snake_case , atol=_snake_case)) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)) UpperCAmelCase_ = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]]).to(_snake_case) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _snake_case , atol=_snake_case)) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''') .to(_snake_case) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = image_processor( [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors='''pt''' , ) UpperCAmelCase_ = inputs['''pixel_values'''].to(_snake_case) UpperCAmelCase_ = [el.to(_snake_case) for el in inputs['''mask_labels''']] UpperCAmelCase_ = [el.to(_snake_case) for el in inputs['''class_labels''']] with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case) self.assertTrue(outputs.loss is not None)
51
0
def UpperCamelCase ( _a , _a ) -> str: '''simple docstring''' lowercase_ :int = '''''' for word_or_phrase in separated: if not isinstance(_a , _a ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(_a ) if __name__ == "__main__": from doctest import testmod testmod()
252
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase ( self ): lowercase_ :int = logging.get_logger() # the current default level is logging.WARNING lowercase_ :List[str] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(UpperCamelCase_ ) def UpperCamelCase ( self ): lowercase_ :Tuple = logging.get_verbosity() lowercase_ :str = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Tuple = '''Testing 1, 2, 3''' # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , '''''' ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) # restore to the original level logging.set_verbosity(UpperCamelCase_ ) @mockenv(TRANSFORMERS_VERBOSITY='''error''' ) def UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var lowercase_ :Any = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Optional[Any] = os.getenv('''TRANSFORMERS_VERBOSITY''' , UpperCamelCase_ ) lowercase_ :Any = logging.log_levels[env_level_str] lowercase_ :Optional[int] = logging.get_verbosity() self.assertEqual( UpperCamelCase_ , UpperCamelCase_ , f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level lowercase_ :str = '''''' transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY='''super-error''' ) def UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() lowercase_ :Any = logging.logging.getLogger() with CaptureLogger(UpperCamelCase_ ) as cl: # this action activates the env var logging.get_logger('''transformers.models.bart.tokenization_bart''' ) self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error''' , cl.out ) # no need to restore as nothing was changed def UpperCamelCase ( self ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() lowercase_ :Optional[int] = logging.get_logger('''transformers.models.bart.tokenization_bart''' ) lowercase_ :Any = '''Testing 1, 2, 3''' with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1''' ): # nothing should be logged as env var disables this method with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning_advice(UpperCamelCase_ ) self.assertEqual(cl.out , '''''' ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''''' ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(UpperCamelCase_ ) as cl: logger.warning_advice(UpperCamelCase_ ) self.assertEqual(cl.out , msg + '''\n''' ) def UpperCamelCase ( ) -> List[Any]: '''simple docstring''' disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
252
1
class __lowerCAmelCase : def __init__( self :Dict , __magic_name__ :Union[str, Any] , __magic_name__ :List[str] ): '''simple docstring''' a = name a = val def __str__( self :Optional[int] ): '''simple docstring''' return F'{self.__class__.__name__}({self.name}, {self.val})' def __lt__( self :List[str] , __magic_name__ :Union[str, Any] ): '''simple docstring''' return self.val < other.val class __lowerCAmelCase : def __init__( self :Dict , __magic_name__ :Dict ): '''simple docstring''' a = {} a = {} a = self.build_heap(__magic_name__ ) def __getitem__( self :List[Any] , __magic_name__ :Any ): '''simple docstring''' return self.get_value(__magic_name__ ) def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' return (idx - 1) // 2 def lowerCamelCase__ ( self :List[str] , __magic_name__ :int ): '''simple docstring''' return idx * 2 + 1 def lowerCamelCase__ ( self :int , __magic_name__ :int ): '''simple docstring''' return idx * 2 + 2 def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :Optional[int] ): '''simple docstring''' return self.heap_dict[key] def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :int ): '''simple docstring''' a = len(__magic_name__ ) - 1 a = self.get_parent_idx(__magic_name__ ) for idx, i in enumerate(__magic_name__ ): a = idx a = i.val for i in range(__magic_name__ , -1 , -1 ): self.sift_down(__magic_name__ , __magic_name__ ) return array def lowerCamelCase__ ( self :str , __magic_name__ :Optional[int] , __magic_name__ :Union[str, Any] ): '''simple docstring''' while True: a = self.get_left_child_idx(__magic_name__ ) # noqa: E741 a = self.get_right_child_idx(__magic_name__ ) a = idx if l < len(__magic_name__ ) and array[l] < array[idx]: a = l if r < len(__magic_name__ ) and array[r] < array[smallest]: a = r if smallest != idx: a , a = array[smallest], array[idx] ( ( a ) , ( a ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) a = smallest else: break def lowerCamelCase__ ( self :Optional[int] , __magic_name__ :int ): '''simple docstring''' a = self.get_parent_idx(__magic_name__ ) while p >= 0 and self.heap[p] > self.heap[idx]: a , a = self.heap[idx], self.heap[p] a , a = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) a = p a = self.get_parent_idx(__magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' return self.heap[0] def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a , a = self.heap[-1], self.heap[0] a , a = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) a = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def lowerCamelCase__ ( self :Tuple , __magic_name__ :Union[str, Any] ): '''simple docstring''' self.heap.append(__magic_name__ ) a = len(self.heap ) - 1 a = node.val self.sift_up(len(self.heap ) - 1 ) def lowerCamelCase__ ( self :int ): '''simple docstring''' return len(self.heap ) == 0 def lowerCamelCase__ ( self :Dict , __magic_name__ :List[str] , __magic_name__ :str ): '''simple docstring''' assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" a = new_value a = new_value self.sift_up(self.idx_of_element[node] ) __UpperCamelCase : Any = Node("R", -1) __UpperCamelCase : Optional[int] = Node("B", 6) __UpperCamelCase : Tuple = Node("A", 3) __UpperCamelCase : Union[str, Any] = Node("X", 1) __UpperCamelCase : Optional[int] = Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __UpperCamelCase : Dict = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
228
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() __UpperCamelCase : str = logging.get_logger(__name__) __UpperCamelCase : List[str] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } __UpperCamelCase : Union[str, Any] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Union[str, Any]: for attribute in key.split(""".""" ): a = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: a = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: a = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": a = value elif weight_type == "weight_g": a = value elif weight_type == "weight_v": a = value elif weight_type == "bias": a = value else: a = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def __A ( __lowerCamelCase , __lowerCamelCase ) -> int: a = [] a = fairseq_model.state_dict() a = hf_model.feature_extractor a = hf_model.adapter for name, value in fairseq_dict.items(): a = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) a = True elif any(x in name for x in ["""adaptor""", """w2v_encoder.proj.""", """w2v_proj_ln."""] ): load_adapter(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) a = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: a = True if "*" in mapped_key: a = name.split(__lowerCamelCase )[0].split(""".""" )[-2] a = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: a = """weight_g""" elif "weight_v" in name: a = """weight_v""" elif "bias" in name: a = """bias""" elif "weight" in name: a = """weight""" else: a = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(f'Unused weights: {unused_weights}' ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Tuple: a = full_name.split("""conv_layers.""" )[-1] a = name.split(""".""" ) a = int(items[0] ) a = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) a = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) -> Any: a = full_name.split("""adaptor.""" )[-1] a = name.split(""".""" ) if items[1].isdigit(): a = int(items[1] ) else: a = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), f'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.' a = value logger.info(f'Adapter proj layer norm bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), f'{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.' a = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), f'{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.' a = value logger.info(f'Adapter proj layer bias was initialized from {full_name}.' ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), f'{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.' a = value logger.info(f'Adapter proj layer weight was initialized from {full_name}.' ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), f'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.' a = value logger.info(f'Adapter layer {layer_id} bias was initialized from {full_name}.' ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), f'{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.' a = value logger.info(f'Adapter layer {layer_id} bias was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) def __A ( __lowerCamelCase ) -> Tuple: a , a = emb.weight.shape a = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) a = emb.weight.data return lin_layer @torch.no_grad() def __A ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) -> Optional[int]: a = WavaVecaConfig.from_pretrained( __lowerCamelCase , add_adapter=__lowerCamelCase , adapter_stride=__lowerCamelCase , adapter_kernel_size=__lowerCamelCase , use_auth_token=__lowerCamelCase , output_hidden_size=__lowerCamelCase , ) a = MBartConfig.from_pretrained(__lowerCamelCase ) # load model a , a , a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={ """config_yaml""": config_yaml_path, """data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path, """load_pretrained_decoder_from""": None, } , ) a = model[0].eval() # load feature extractor a = WavaVecaFeatureExtractor.from_pretrained(__lowerCamelCase , use_auth_token=__lowerCamelCase ) # set weights for wav2vec2 encoder a = WavaVecaModel(__lowerCamelCase ) recursively_load_weights_wavaveca(model.encoder , __lowerCamelCase ) # load decoder weights a = MBartForCausalLM(__lowerCamelCase ) a , a = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=__lowerCamelCase ) logger.warning(f'The following keys are missing when loading the decoder weights: {missing_keys}' ) logger.warning(f'The following keys are unexpected when loading the decoder weights: {unexpected_keys}' ) a = SpeechEncoderDecoderModel(encoder=__lowerCamelCase , decoder=__lowerCamelCase ) a = False a = MBartaaTokenizer(__lowerCamelCase ) tokenizer.save_pretrained(__lowerCamelCase ) a = hf_wavavec.config.to_dict() a = tokenizer.pad_token_id a = tokenizer.bos_token_id a = tokenizer.eos_token_id a = """mbart50""" a = """wav2vec2""" a = tokenizer.eos_token_id a = 25_0004 a = tokenizer.eos_token_id a = SpeechEncoderDecoderConfig.from_dict(__lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) feature_extractor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": __UpperCamelCase : Any = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-xls-r-1b", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/mbart-large-50-one-to-many-mmt", type=str, help="Path to hf decoder checkpoint config", ) parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers") parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers") parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers") parser.add_argument("--encoder_output_dim", default=1_024, type=int, help="encoder output dim") parser.add_argument("--start_token_id", default=250_004, type=int, help="`decoder_start_token_id` of model config") __UpperCamelCase : int = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
228
1
from ...configuration_utils import PretrainedConfig class snake_case_ ( __A ): __A : Optional[Any] = "bert-generation" def __init__( self : Optional[int] , lowercase_ : Any=5_03_58 , lowercase_ : List[Any]=10_24 , lowercase_ : Optional[Any]=24 , lowercase_ : Union[str, Any]=16 , lowercase_ : Tuple=40_96 , lowercase_ : List[Any]="gelu" , lowercase_ : str=0.1 , lowercase_ : Dict=0.1 , lowercase_ : Tuple=5_12 , lowercase_ : Optional[int]=0.02 , lowercase_ : Dict=1E-12 , lowercase_ : Optional[Any]=0 , lowercase_ : str=2 , lowercase_ : int=1 , lowercase_ : Union[str, Any]="absolute" , lowercase_ : Union[str, Any]=True , **lowercase_ : Dict , ) -> Optional[int]: super().__init__(pad_token_id=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_ ) lowercase__ : Tuple = vocab_size lowercase__ : Dict = hidden_size lowercase__ : Dict = num_hidden_layers lowercase__ : Union[str, Any] = num_attention_heads lowercase__ : int = hidden_act lowercase__ : int = intermediate_size lowercase__ : Any = hidden_dropout_prob lowercase__ : Optional[int] = attention_probs_dropout_prob lowercase__ : str = max_position_embeddings lowercase__ : Optional[int] = initializer_range lowercase__ : List[Any] = layer_norm_eps lowercase__ : Any = position_embedding_type lowercase__ : Optional[int] = use_cache
353
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask UpperCamelCase = logging.getLogger(__name__) class snake_case_ ( __A ): __A : int = "token-classification" def __init__( self : Tuple , lowercase_ : Dict ) -> List[str]: if type(lowercase_ ) == dict: lowercase__ : Dict = Namespace(**lowercase_ ) lowercase__ : str = import_module("tasks" ) try: lowercase__ : Tuple = getattr(lowercase_ , hparams.task_type ) lowercase__ : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( F'''Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' F'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) lowercase__ : Optional[Any] = self.token_classification_task.get_labels(hparams.labels ) lowercase__ : int = CrossEntropyLoss().ignore_index super().__init__(lowercase_ , len(self.labels ) , self.mode ) def __UpperCamelCase ( self : Union[str, Any] , **lowercase_ : List[str] ) -> Any: return self.model(**lowercase_ ) def __UpperCamelCase ( self : Optional[Any] , lowercase_ : str , lowercase_ : Optional[int] ) -> Tuple: lowercase__ : int = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": lowercase__ : Tuple = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids lowercase__ : Optional[int] = self(**lowercase_ ) lowercase__ : Union[str, Any] = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def __UpperCamelCase ( self : Tuple ) -> Union[str, Any]: lowercase__ : Tuple = self.hparams for mode in ["train", "dev", "test"]: lowercase__ : Any = self._feature_file(lowercase_ ) if os.path.exists(lowercase_ ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , lowercase_ ) lowercase__ : str = torch.load(lowercase_ ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) lowercase__ : Optional[Any] = self.token_classification_task.read_examples_from_file(args.data_dir , lowercase_ ) lowercase__ : Dict = self.token_classification_task.convert_examples_to_features( lowercase_ , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["xlnet"] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=lowercase_ , pad_on_left=bool(self.config.model_type in ["xlnet"] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("Saving features into cached file %s" , lowercase_ ) torch.save(lowercase_ , lowercase_ ) def __UpperCamelCase ( self : Optional[Any] , lowercase_ : int , lowercase_ : int , lowercase_ : bool = False ) -> DataLoader: lowercase__ : str = self._feature_file(lowercase_ ) logger.info("Loading features from cached file %s" , lowercase_ ) lowercase__ : str = torch.load(lowercase_ ) lowercase__ : List[str] = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) lowercase__ : str = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: lowercase__ : Dict = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: lowercase__ : Dict = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) lowercase__ : List[str] = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) , batch_size=lowercase_ ) def __UpperCamelCase ( self : str , lowercase_ : Dict , lowercase_ : Tuple ) -> str: """Compute validation""" "" lowercase__ : Union[str, Any] = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": lowercase__ : int = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids lowercase__ : List[Any] = self(**lowercase_ ) lowercase__ , lowercase__ : Any = outputs[:2] lowercase__ : Optional[Any] = logits.detach().cpu().numpy() lowercase__ : int = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def __UpperCamelCase ( self : Optional[int] , lowercase_ : Any ) -> List[Any]: lowercase__ : int = torch.stack([x["val_loss"] for x in outputs] ).mean() lowercase__ : Any = np.concatenate([x["pred"] for x in outputs] , axis=0 ) lowercase__ : Dict = np.argmax(lowercase_ , axis=2 ) lowercase__ : int = np.concatenate([x["target"] for x in outputs] , axis=0 ) lowercase__ : Any = dict(enumerate(self.labels ) ) lowercase__ : List[Any] = [[] for _ in range(out_label_ids.shape[0] )] lowercase__ : Dict = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) lowercase__ : Any = { "val_loss": val_loss_mean, "accuracy_score": accuracy_score(lowercase_ , lowercase_ ), "precision": precision_score(lowercase_ , lowercase_ ), "recall": recall_score(lowercase_ , lowercase_ ), "f1": fa_score(lowercase_ , lowercase_ ), } lowercase__ : List[Any] = dict(results.items() ) lowercase__ : List[str] = results return ret, preds_list, out_label_list def __UpperCamelCase ( self : Any , lowercase_ : Dict ) -> Dict: # when stable lowercase__ , lowercase__ , lowercase__ : Dict = self._eval_end(lowercase_ ) lowercase__ : Any = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def __UpperCamelCase ( self : str , lowercase_ : Tuple ) -> int: # updating to test_epoch_end instead of deprecated test_end lowercase__ , lowercase__ , lowercase__ : Dict = self._eval_end(lowercase_ ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 lowercase__ : Optional[int] = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def __UpperCamelCase ( lowercase_ : int , lowercase_ : Union[str, Any] ) -> Tuple: # Add NER specific options BaseTransformer.add_model_specific_args(lowercase_ , lowercase_ ) parser.add_argument( "--task_type" , default="NER" , type=lowercase_ , help="Task type to fine tune in training (e.g. NER, POS, etc)" ) parser.add_argument( "--max_seq_length" , default=1_28 , type=lowercase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--labels" , default="" , type=lowercase_ , help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used." , ) parser.add_argument( "--gpus" , default=0 , type=lowercase_ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) UpperCamelCase = NERTransformer.add_model_specific_args(parser, os.getcwd()) UpperCamelCase = parser.parse_args() UpperCamelCase = NERTransformer(args) UpperCamelCase = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 UpperCamelCase = sorted(glob.glob(os.path.join(args.output_dir, '''checkpoint-epoch=*.ckpt'''), recursive=True)) UpperCamelCase = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
333
0
"""simple docstring""" import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def A_ ( _lowerCAmelCase : Tuple ): """simple docstring""" if "cls_token" in name: _a = name.replace('''cls_token''', '''vit.embeddings.cls_token''' ) if "mask_token" in name: _a = name.replace('''mask_token''', '''decoder.mask_token''' ) if "decoder_pos_embed" in name: _a = name.replace('''decoder_pos_embed''', '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: _a = name.replace('''pos_embed''', '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: _a = name.replace('''patch_embed.proj''', '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: _a = name.replace('''patch_embed.norm''', '''vit.embeddings.norm''' ) if "decoder_blocks" in name: _a = name.replace('''decoder_blocks''', '''decoder.decoder_layers''' ) if "blocks" in name: _a = name.replace('''blocks''', '''vit.encoder.layer''' ) if "attn.proj" in name: _a = name.replace('''attn.proj''', '''attention.output.dense''' ) if "attn" in name: _a = name.replace('''attn''', '''attention.self''' ) if "norm1" in name: _a = name.replace('''norm1''', '''layernorm_before''' ) if "norm2" in name: _a = name.replace('''norm2''', '''layernorm_after''' ) if "mlp.fc1" in name: _a = name.replace('''mlp.fc1''', '''intermediate.dense''' ) if "mlp.fc2" in name: _a = name.replace('''mlp.fc2''', '''output.dense''' ) if "decoder_embed" in name: _a = name.replace('''decoder_embed''', '''decoder.decoder_embed''' ) if "decoder_norm" in name: _a = name.replace('''decoder_norm''', '''decoder.decoder_norm''' ) if "decoder_pred" in name: _a = name.replace('''decoder_pred''', '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: _a = name.replace('''norm.weight''', '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: _a = name.replace('''norm.bias''', '''vit.layernorm.bias''' ) return name def A_ ( _lowerCAmelCase : str, _lowerCAmelCase : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): _a = orig_state_dict.pop(_lowerCAmelCase ) if "qkv" in key: _a = key.split('''.''' ) _a = int(key_split[1] ) if "decoder_blocks" in key: _a = config.decoder_hidden_size _a = '''decoder.decoder_layers.''' if "weight" in key: _a = val[:dim, :] _a = val[dim : dim * 2, :] _a = val[-dim:, :] elif "bias" in key: _a = val[:dim] _a = val[dim : dim * 2] _a = val[-dim:] else: _a = config.hidden_size _a = '''vit.encoder.layer.''' if "weight" in key: _a = val[:dim, :] _a = val[dim : dim * 2, :] _a = val[-dim:, :] elif "bias" in key: _a = val[:dim] _a = val[dim : dim * 2] _a = val[-dim:] else: _a = val return orig_state_dict def A_ ( _lowerCAmelCase : Optional[Any], _lowerCAmelCase : Union[str, Any] ): """simple docstring""" _a = ViTMAEConfig() if "large" in checkpoint_url: _a = 10_24 _a = 40_96 _a = 24 _a = 16 elif "huge" in checkpoint_url: _a = 14 _a = 12_80 _a = 51_20 _a = 32 _a = 16 _a = ViTMAEForPreTraining(_lowerCAmelCase ) _a = torch.hub.load_state_dict_from_url(_lowerCAmelCase, map_location='''cpu''' )['''model'''] _a = ViTMAEImageProcessor(size=config.image_size ) _a = convert_state_dict(_lowerCAmelCase, _lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase ) model.eval() _a = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' _a = Image.open(requests.get(_lowerCAmelCase, stream=_lowerCAmelCase ).raw ) _a = ViTMAEImageProcessor(size=config.image_size ) _a = image_processor(images=_lowerCAmelCase, return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) _a = model(**_lowerCAmelCase ) _a = outputs.logits if "large" in checkpoint_url: _a = torch.tensor( [[-0.7_3_0_9, -0.7_1_2_8, -1.0_1_6_9], [-1.0_1_6_1, -0.9_0_5_8, -1.1_8_7_8], [-1.0_4_7_8, -0.9_4_1_1, -1.1_9_1_1]] ) elif "huge" in checkpoint_url: _a = torch.tensor( [[-1.1_5_9_9, -0.9_1_9_9, -1.2_2_2_1], [-1.1_9_5_2, -0.9_2_6_9, -1.2_3_0_7], [-1.2_1_4_3, -0.9_3_3_7, -1.2_2_6_2]] ) else: _a = torch.tensor( [[-0.9_1_9_2, -0.8_4_8_1, -1.1_2_5_9], [-1.1_3_4_9, -1.0_0_3_4, -1.2_5_9_9], [-1.1_7_5_7, -1.0_4_2_9, -1.2_7_2_6]] ) # verify logits assert torch.allclose(logits[0, :3, :3], _lowerCAmelCase, atol=1e-4 ) print(f'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(_lowerCAmelCase ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''', type=str, help='''URL of the 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.''' ) __snake_case = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
320
"""simple docstring""" def A_ ( ): """simple docstring""" _a = [] _a = 1 while len(_lowerCAmelCase ) < 1e6: constant.append(str(_lowerCAmelCase ) ) i += 1 _a = ''''''.join(_lowerCAmelCase ) return ( int(constant[0] ) * int(constant[9] ) * int(constant[99] ) * int(constant[9_99] ) * int(constant[99_99] ) * int(constant[9_99_99] ) * int(constant[99_99_99] ) ) if __name__ == "__main__": print(solution())
320
1
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _UpperCAmelCase = False _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = 'ybelkada/fonts' def lowerCAmelCase_ ( ) -> Dict: if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> List[Any]: requires_backends(UpperCamelCase_ , ["torch"] ) _check_torch_version() UpperCamelCase_ = image_tensor.unsqueeze(0 ) UpperCamelCase_ = torch.nn.functional.unfold(UpperCamelCase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) UpperCamelCase_ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , UpperCamelCase_ , UpperCamelCase_ , -1 ) UpperCamelCase_ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ = 36 , UpperCamelCase_ = "black" , UpperCamelCase_ = "white" , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = 5 , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> Image.Image: requires_backends(UpperCamelCase_ , "vision" ) # Add new lines so that each line is no more than 80 characters. UpperCamelCase_ = textwrap.TextWrapper(width=80 ) UpperCamelCase_ = wrapper.wrap(text=UpperCamelCase_ ) UpperCamelCase_ = "\n".join(UpperCamelCase_ ) if font_bytes is not None and font_path is None: UpperCamelCase_ = io.BytesIO(UpperCamelCase_ ) elif font_path is not None: UpperCamelCase_ = font_path else: UpperCamelCase_ = hf_hub_download(UpperCamelCase_ , "Arial.TTF" ) UpperCamelCase_ = ImageFont.truetype(UpperCamelCase_ , encoding="UTF-8" , size=UpperCamelCase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. UpperCamelCase_ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , UpperCamelCase_ ) ) UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = temp_draw.textbbox((0, 0) , UpperCamelCase_ , UpperCamelCase_ ) # Create the actual image with a bit of padding around the text. UpperCamelCase_ = text_width + left_padding + right_padding UpperCamelCase_ = text_height + top_padding + bottom_padding UpperCamelCase_ = Image.new("RGB" , (image_width, image_height) , UpperCamelCase_ ) UpperCamelCase_ = ImageDraw.Draw(UpperCamelCase_ ) draw.text(xy=(left_padding, top_padding) , text=UpperCamelCase_ , fill=UpperCamelCase_ , font=UpperCamelCase_ ) return image def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ) -> Union[str, Any]: requires_backends(UpperCamelCase_ , "vision" ) # Convert to PIL image if necessary UpperCamelCase_ = to_pil_image(UpperCamelCase_ ) UpperCamelCase_ = render_text(UpperCamelCase_ , **UpperCamelCase_ ) UpperCamelCase_ = max(header_image.width , image.width ) UpperCamelCase_ = int(image.height * (new_width / image.width) ) UpperCamelCase_ = int(header_image.height * (new_width / header_image.width) ) UpperCamelCase_ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary UpperCamelCase_ = to_numpy_array(UpperCamelCase_ ) if infer_channel_dimension_format(UpperCamelCase_ ) == ChannelDimension.LAST: UpperCamelCase_ = to_channel_dimension_format(UpperCamelCase_ , ChannelDimension.LAST ) return new_image class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : str = ['''flattened_patches'''] def __init__( self: List[Any] , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: bool = True , _SCREAMING_SNAKE_CASE: Dict[str, int] = None , _SCREAMING_SNAKE_CASE: int = 2048 , _SCREAMING_SNAKE_CASE: bool = False , **_SCREAMING_SNAKE_CASE: Optional[Any] , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} UpperCamelCase_ = do_normalize UpperCamelCase_ = do_convert_rgb UpperCamelCase_ = max_patches UpperCamelCase_ = is_vqa def lowercase ( self: Dict , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: int , _SCREAMING_SNAKE_CASE: dict , **_SCREAMING_SNAKE_CASE: Union[str, Any] ) -> np.ndarray: """simple docstring""" requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch UpperCamelCase_ = to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.FIRST ) UpperCamelCase_ = torch.from_numpy(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ , UpperCamelCase_ = patch_size["height"], patch_size["width"] UpperCamelCase_ , UpperCamelCase_ = get_image_size(_SCREAMING_SNAKE_CASE ) # maximize scale s.t. UpperCamelCase_ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) UpperCamelCase_ = max(min(math.floor(scale * image_height / patch_height ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(min(math.floor(scale * image_width / patch_width ) , _SCREAMING_SNAKE_CASE ) , 1 ) UpperCamelCase_ = max(num_feasible_rows * patch_height , 1 ) UpperCamelCase_ = max(num_feasible_cols * patch_width , 1 ) UpperCamelCase_ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=_SCREAMING_SNAKE_CASE , antialias=_SCREAMING_SNAKE_CASE , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] UpperCamelCase_ = torch_extract_patches(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = patches.shape UpperCamelCase_ = patches_shape[1] UpperCamelCase_ = patches_shape[2] UpperCamelCase_ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] UpperCamelCase_ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([rows, 1] ).repeat(1 , _SCREAMING_SNAKE_CASE ).reshape([rows * columns, 1] ) UpperCamelCase_ = torch.arange(_SCREAMING_SNAKE_CASE ).reshape([1, columns] ).repeat(_SCREAMING_SNAKE_CASE , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] UpperCamelCase_ = row_ids.to(torch.floataa ) UpperCamelCase_ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] UpperCamelCase_ = torch.nn.functional.pad(_SCREAMING_SNAKE_CASE , [0, 0, 0, max_patches - (rows * columns)] ).float() UpperCamelCase_ = to_numpy_array(_SCREAMING_SNAKE_CASE ) return result def lowercase ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: np.ndarray , _SCREAMING_SNAKE_CASE: Optional[Union[str, ChannelDimension]] = None , **_SCREAMING_SNAKE_CASE: List[str] ) -> np.ndarray: """simple docstring""" if image.dtype == np.uinta: UpperCamelCase_ = image.astype(np.floataa ) # take mean across the whole `image` UpperCamelCase_ = np.mean(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = np.std(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = max(_SCREAMING_SNAKE_CASE , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def lowercase ( self: Optional[int] , _SCREAMING_SNAKE_CASE: ImageInput , _SCREAMING_SNAKE_CASE: Optional[str] = None , _SCREAMING_SNAKE_CASE: bool = None , _SCREAMING_SNAKE_CASE: Optional[bool] = None , _SCREAMING_SNAKE_CASE: Optional[int] = None , _SCREAMING_SNAKE_CASE: Optional[Dict[str, int]] = None , _SCREAMING_SNAKE_CASE: Optional[Union[str, TensorType]] = None , _SCREAMING_SNAKE_CASE: ChannelDimension = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE: List[Any] , ) -> ImageInput: """simple docstring""" UpperCamelCase_ = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb UpperCamelCase_ = patch_size if patch_size is not None else self.patch_size UpperCamelCase_ = max_patches if max_patches is not None else self.max_patches UpperCamelCase_ = self.is_vqa if kwargs.get("data_format" , _SCREAMING_SNAKE_CASE ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) UpperCamelCase_ = 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." ) # PIL RGBA images are converted to RGB if do_convert_rgb: UpperCamelCase_ = [convert_to_rgb(_SCREAMING_SNAKE_CASE ) for image in images] # All transformations expect numpy arrays. UpperCamelCase_ = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) UpperCamelCase_ = kwargs.pop("font_bytes" , _SCREAMING_SNAKE_CASE ) UpperCamelCase_ = kwargs.pop("font_path" , _SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): UpperCamelCase_ = [header_text] * len(_SCREAMING_SNAKE_CASE ) UpperCamelCase_ = [ render_header(_SCREAMING_SNAKE_CASE , header_text[i] , font_bytes=_SCREAMING_SNAKE_CASE , font_path=_SCREAMING_SNAKE_CASE ) for i, image in enumerate(_SCREAMING_SNAKE_CASE ) ] if do_normalize: UpperCamelCase_ = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] # convert to torch tensor and permute UpperCamelCase_ = [ self.extract_flattened_patches(image=_SCREAMING_SNAKE_CASE , max_patches=_SCREAMING_SNAKE_CASE , patch_size=_SCREAMING_SNAKE_CASE ) for image in images ] # create attention mask in numpy UpperCamelCase_ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] UpperCamelCase_ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_outputs
328
import argparse import json from tqdm import tqdm def lowerCAmelCase_ ( ) -> Tuple: UpperCamelCase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--src_path" , type=UpperCamelCase_ , default="biencoder-nq-dev.json" , help="Path to raw DPR training data" , ) parser.add_argument( "--evaluation_set" , type=UpperCamelCase_ , help="where to store parsed evaluation_set file" , ) parser.add_argument( "--gold_data_path" , type=UpperCamelCase_ , help="where to store parsed gold_data_path file" , ) UpperCamelCase_ = parser.parse_args() with open(args.src_path , "r" ) as src_file, open(args.evaluation_set , "w" ) as eval_file, open( args.gold_data_path , "w" ) as gold_file: UpperCamelCase_ = json.load(UpperCamelCase_ ) for dpr_record in tqdm(UpperCamelCase_ ): UpperCamelCase_ = dpr_record["question"] UpperCamelCase_ = [context["title"] for context in dpr_record["positive_ctxs"]] eval_file.write(question + "\n" ) gold_file.write("\t".join(UpperCamelCase_ ) + "\n" ) if __name__ == "__main__": main()
328
1
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder __lowerCAmelCase : Optional[Any] ='base_with_context' def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.FloatTensor(weights['''token_embedder''']['''embedding'''] ) ) __SCREAMING_SNAKE_CASE : int = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=lowercase__ ) for lyr_num, lyr in enumerate(model.encoders ): __SCREAMING_SNAKE_CASE : str = weights[F'''layers_{lyr_num}'''] __SCREAMING_SNAKE_CASE : int = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : List[Any] = ly_weight['''attention'''] __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Any = nn.Parameter(torch.FloatTensor(weights['''input_proj''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=lowercase__ ) for lyr_num, lyr in enumerate(model.encoders ): __SCREAMING_SNAKE_CASE : List[str] = weights[F'''layers_{lyr_num}'''] __SCREAMING_SNAKE_CASE : int = ly_weight['''attention'''] __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Any = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight['''pre_attention_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Any = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.FloatTensor(weights['''encoder_norm''']['''scale'''] ) ) return model def _UpperCamelCase ( lowercase__ , lowercase__ ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(torch.FloatTensor(weights['''time_emb_dense1''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( torch.FloatTensor(weights['''Embed_0''']['''embedding'''] ) , requires_grad=lowercase__ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( torch.FloatTensor(weights['''continuous_inputs_projection''']['''kernel'''].T ) ) for lyr_num, lyr in enumerate(model.decoders ): __SCREAMING_SNAKE_CASE : Dict = weights[F'''layers_{lyr_num}'''] __SCREAMING_SNAKE_CASE : int = nn.Parameter( torch.FloatTensor(ly_weight['''pre_self_attention_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_0''']['''DenseGeneral_0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = ly_weight['''self_attention'''] __SCREAMING_SNAKE_CASE : Any = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[str] = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = ly_weight['''MultiHeadDotProductAttention_0'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.FloatTensor(attention_weights['''query''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(torch.FloatTensor(attention_weights['''key''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.Parameter(torch.FloatTensor(attention_weights['''value''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.FloatTensor(attention_weights['''out''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Any = nn.Parameter( torch.FloatTensor(ly_weight['''pre_cross_attention_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(torch.FloatTensor(ly_weight['''pre_mlp_layer_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : int = nn.Parameter( torch.FloatTensor(ly_weight['''FiLMLayer_1''']['''DenseGeneral_0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : Dict = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_0''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : int = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wi_1''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.FloatTensor(ly_weight['''mlp''']['''wo''']['''kernel'''].T ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.FloatTensor(weights['''decoder_norm''']['''scale'''] ) ) __SCREAMING_SNAKE_CASE : int = nn.Parameter(torch.FloatTensor(weights['''spec_out_dense''']['''kernel'''].T ) ) return model def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Any = checkpoints.load_tax_checkpoint(args.checkpoint_path ) __SCREAMING_SNAKE_CASE : List[Any] = jnp.tree_util.tree_map(onp.array , lowercase__ ) __SCREAMING_SNAKE_CASE : str = [ '''from __gin__ import dynamic_registration''', '''from music_spectrogram_diffusion.models.diffusion import diffusion_utils''', '''diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0''', '''diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()''', ] __SCREAMING_SNAKE_CASE : Dict = os.path.join(args.checkpoint_path , '''..''' , '''config.gin''' ) __SCREAMING_SNAKE_CASE : Tuple = inference.parse_training_gin_file(lowercase__ , lowercase__ ) __SCREAMING_SNAKE_CASE : Tuple = inference.InferenceModel(args.checkpoint_path , lowercase__ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' , variance_type='''fixed_large''' ) __SCREAMING_SNAKE_CASE : List[Any] = SpectrogramNotesEncoder( max_length=synth_model.sequence_length['''inputs'''] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , ) __SCREAMING_SNAKE_CASE : str = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length['''targets_context'''] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj='''gated-gelu''' , ) __SCREAMING_SNAKE_CASE : Any = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length['''targets_context'''] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) __SCREAMING_SNAKE_CASE : int = load_notes_encoder(ta_checkpoint['''target''']['''token_encoder'''] , lowercase__ ) __SCREAMING_SNAKE_CASE : Dict = load_continuous_encoder(ta_checkpoint['''target''']['''continuous_encoder'''] , lowercase__ ) __SCREAMING_SNAKE_CASE : List[Any] = load_decoder(ta_checkpoint['''target''']['''decoder'''] , lowercase__ ) __SCREAMING_SNAKE_CASE : int = OnnxRuntimeModel.from_pretrained('''kashif/soundstream_mel_decoder''' ) __SCREAMING_SNAKE_CASE : Dict = SpectrogramDiffusionPipeline( notes_encoder=lowercase__ , continuous_encoder=lowercase__ , decoder=lowercase__ , scheduler=lowercase__ , melgan=lowercase__ , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": __lowerCAmelCase : str =argparse.ArgumentParser() parser.add_argument('--output_path', default=None, type=str, required=True, help='Path to the converted model.') parser.add_argument( '--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.' ) parser.add_argument( '--checkpoint_path', default=f"""{MODEL}/checkpoint_500000""", type=str, required=False, help='Path to the original jax model checkpoint.', ) __lowerCAmelCase : Tuple =parser.parse_args() main(args)
9
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
0
import numpy as np from transformers import Pipeline def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[Any] ): '''simple docstring''' lowercase__ : str = np.max(SCREAMING_SNAKE_CASE_ , axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) lowercase__ : Tuple = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) class SCREAMING_SNAKE_CASE__ (__snake_case ): def snake_case_ ( self , **a): lowercase__ : List[Any] = {} if "second_text" in kwargs: lowercase__ : Any = kwargs['second_text'] return preprocess_kwargs, {}, {} def snake_case_ ( self , a , a=None): return self.tokenizer(a , text_pair=a , return_tensors=self.framework) def snake_case_ ( self , a): return self.model(**a) def snake_case_ ( self , a): lowercase__ : Tuple = model_outputs.logits[0].numpy() lowercase__ : str = softmax(a) lowercase__ : Tuple = np.argmax(a) lowercase__ : Dict = self.model.config.idalabel[best_class] lowercase__ : Any = probabilities[best_class].item() lowercase__ : Dict = logits.tolist() return {"label": label, "score": score, "logits": logits}
216
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer 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_file''': '''tokenizer.json'''} snake_case_ = { '''vocab_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/vocab.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/vocab.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/vocab.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/vocab.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/vocab.json''', }, '''merges_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/merges.txt''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/merges.txt''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/merges.txt''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/merges.txt''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''gpt2''': '''https://huggingface.co/gpt2/resolve/main/tokenizer.json''', '''gpt2-medium''': '''https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json''', '''gpt2-large''': '''https://huggingface.co/gpt2-large/resolve/main/tokenizer.json''', '''gpt2-xl''': '''https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json''', '''distilgpt2''': '''https://huggingface.co/distilgpt2/resolve/main/tokenizer.json''', }, } snake_case_ = { '''gpt2''': 1_024, '''gpt2-medium''': 1_024, '''gpt2-large''': 1_024, '''gpt2-xl''': 1_024, '''distilgpt2''': 1_024, } class SCREAMING_SNAKE_CASE__ (__snake_case ): __lowerCamelCase : List[str] = VOCAB_FILES_NAMES __lowerCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase : int = ["""input_ids""", """attention_mask"""] __lowerCamelCase : str = GPTaTokenizer def __init__( self , a=None , a=None , a=None , a="<|endoftext|>" , a="<|endoftext|>" , a="<|endoftext|>" , a=False , **a , ): super().__init__( a , a , tokenizer_file=a , unk_token=a , bos_token=a , eos_token=a , add_prefix_space=a , **a , ) lowercase__ : int = kwargs.pop('add_bos_token' , a) lowercase__ : List[str] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()) if pre_tok_state.get('add_prefix_space' , a) != add_prefix_space: lowercase__ : Optional[Any] = getattr(a , pre_tok_state.pop('type')) lowercase__ : List[Any] = add_prefix_space lowercase__ : str = pre_tok_class(**a) lowercase__ : Tuple = add_prefix_space def snake_case_ ( self , *a , **a): lowercase__ : Tuple = kwargs.get('is_split_into_words' , a) 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(*a , **a) def snake_case_ ( self , *a , **a): lowercase__ : Optional[Any] = kwargs.get('is_split_into_words' , a) 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(*a , **a) def snake_case_ ( self , a , a = None): lowercase__ : Any = self._tokenizer.model.save(a , name=a) return tuple(a) def snake_case_ ( self , a): lowercase__ : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(a , add_special_tokens=a) + [self.eos_token_id]) if len(a) > self.model_max_length: lowercase__ : Union[str, Any] = input_ids[-self.model_max_length :] return input_ids
216
1
from __future__ import annotations def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' if b == 0: return (1, 0) ((lowerCamelCase) , (lowerCamelCase)) = extended_euclid(lowerCamelCase__ , a % b ) lowerCamelCase = a // b return (y, x - k * y) def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' ((lowerCamelCase) , (lowerCamelCase)) = extended_euclid(lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase = na * na lowerCamelCase = ra * x * na + ra * y * na return (n % m + m) % m def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' ((lowerCamelCase) , (lowerCamelCase)) = extended_euclid(lowerCamelCase__ , lowerCamelCase__ ) if b < 0: lowerCamelCase = (b % n + n) % n return b def __lowerCamelCase ( lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : int ): '''simple docstring''' lowerCamelCase , lowerCamelCase = invert_modulo(lowerCamelCase__ , lowerCamelCase__ ), invert_modulo(lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase = na * na lowerCamelCase = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
252
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class __lowercase ( unittest.TestCase ): """simple docstring""" def __init__( self , A , A=7 , A=3 , A=30 , A=4_00 , A=True , A=None , A=True , A=[0.5, 0.5, 0.5] , A=[0.5, 0.5, 0.5] , A=True , A=1 / 2_55 , A=True , ) -> str: '''simple docstring''' lowerCamelCase = size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 13_33} lowerCamelCase = parent lowerCamelCase = batch_size lowerCamelCase = num_channels lowerCamelCase = min_resolution lowerCamelCase = max_resolution lowerCamelCase = do_resize lowerCamelCase = size lowerCamelCase = do_normalize lowerCamelCase = image_mean lowerCamelCase = image_std lowerCamelCase = do_rescale lowerCamelCase = rescale_factor lowerCamelCase = do_pad def __A ( self ) -> List[Any]: '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __A ( self , A , A=False ) -> List[Any]: '''simple docstring''' if not batched: lowerCamelCase = image_inputs[0] if isinstance(A , Image.Image ): lowerCamelCase , lowerCamelCase = image.size else: lowerCamelCase , lowerCamelCase = image.shape[1], image.shape[2] if w < h: lowerCamelCase = int(self.size["""shortest_edge"""] * h / w ) lowerCamelCase = self.size["""shortest_edge"""] elif w > h: lowerCamelCase = self.size["""shortest_edge"""] lowerCamelCase = int(self.size["""shortest_edge"""] * w / h ) else: lowerCamelCase = self.size["""shortest_edge"""] lowerCamelCase = self.size["""shortest_edge"""] else: lowerCamelCase = [] for image in image_inputs: lowerCamelCase , lowerCamelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) lowerCamelCase = max(A , key=lambda A : item[0] )[0] lowerCamelCase = max(A , key=lambda A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowercase ( a_ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Union[str, Any] = YolosImageProcessor if is_vision_available() else None def __A ( self ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = YolosImageProcessingTester(self ) @property def __A ( self ) -> List[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __A ( self ) -> str: '''simple docstring''' lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , """image_mean""" ) ) self.assertTrue(hasattr(A , """image_std""" ) ) self.assertTrue(hasattr(A , """do_normalize""" ) ) self.assertTrue(hasattr(A , """do_resize""" ) ) self.assertTrue(hasattr(A , """size""" ) ) def __A ( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 13_33} ) self.assertEqual(image_processor.do_pad , A ) lowerCamelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=A ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , A ) def __A ( self ) -> Union[str, Any]: '''simple docstring''' pass def __A ( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A ) for image in image_inputs: self.assertIsInstance(A , Image.Image ) # Test not batched input lowerCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A , batched=A ) lowerCamelCase = image_processing(A , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ) -> List[str]: '''simple docstring''' lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , numpify=A ) for image in image_inputs: self.assertIsInstance(A , np.ndarray ) # Test not batched input lowerCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase = image_processing(A , return_tensors="""pt""" ).pixel_values lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A , batched=A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test not batched input lowerCamelCase = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched lowerCamelCase = image_processing(A , return_tensors="""pt""" ).pixel_values lowerCamelCase , lowerCamelCase = self.image_processor_tester.get_expected_values(A , batched=A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __A ( self ) -> Any: '''simple docstring''' lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) lowerCamelCase = self.image_processing_class(do_resize=A , do_normalize=A , do_rescale=A ) # create random PyTorch tensors lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for image in image_inputs: self.assertIsInstance(A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors lowerCamelCase = image_processing_a.pad(A , return_tensors="""pt""" ) lowerCamelCase = image_processing_a(A , return_tensors="""pt""" ) self.assertTrue( torch.allclose(encoded_images_with_method["""pixel_values"""] , encoded_images["""pixel_values"""] , atol=1e-4 ) ) @slow def __A ( self ) -> List[Any]: '''simple docstring''' lowerCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: lowerCamelCase = json.loads(f.read() ) lowerCamelCase = {"""image_id""": 3_97_69, """annotations""": target} # encode them lowerCamelCase = YolosImageProcessor.from_pretrained("""hustvl/yolos-small""" ) lowerCamelCase = image_processing(images=A , annotations=A , return_tensors="""pt""" ) # verify pixel values lowerCamelCase = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["""pixel_values"""].shape , A ) lowerCamelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , A , atol=1e-4 ) ) # verify area lowerCamelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , A ) ) # verify boxes lowerCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , A ) lowerCamelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , A , atol=1e-3 ) ) # verify image_id lowerCamelCase = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , A ) ) # verify is_crowd lowerCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , A ) ) # verify class_labels lowerCamelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , A ) ) # verify orig_size lowerCamelCase = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , A ) ) # verify size lowerCamelCase = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , A ) ) @slow def __A ( self ) -> List[Any]: '''simple docstring''' lowerCamelCase = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: lowerCamelCase = json.loads(f.read() ) lowerCamelCase = {"""file_name""": """000000039769.png""", """image_id""": 3_97_69, """segments_info""": target} lowerCamelCase = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them lowerCamelCase = YolosImageProcessor(format="""coco_panoptic""" ) lowerCamelCase = image_processing(images=A , annotations=A , masks_path=A , return_tensors="""pt""" ) # verify pixel values lowerCamelCase = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding["""pixel_values"""].shape , A ) lowerCamelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , A , atol=1e-4 ) ) # verify area lowerCamelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , A ) ) # verify boxes lowerCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , A ) lowerCamelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , A , atol=1e-3 ) ) # verify image_id lowerCamelCase = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , A ) ) # verify is_crowd lowerCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , A ) ) # verify class_labels lowerCamelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , A ) ) # verify masks lowerCamelCase = 82_28_73 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , A ) # verify orig_size lowerCamelCase = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , A ) ) # verify size lowerCamelCase = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , A ) )
252
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = {'''configuration_plbart''': ['''PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''PLBartConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''PLBartTokenizer'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''PLBART_PRETRAINED_MODEL_ARCHIVE_LIST''', '''PLBartForCausalLM''', '''PLBartForConditionalGeneration''', '''PLBartForSequenceClassification''', '''PLBartModel''', '''PLBartPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
34
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase_ = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''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 lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
34
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def UpperCAmelCase_ ( _A ): '''simple docstring''' return (data["data"], data["target"]) def UpperCAmelCase_ ( _A , _A , _A ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(_A , _A ) # Predict target for test data SCREAMING_SNAKE_CASE__ = xgb.predict(_A ) SCREAMING_SNAKE_CASE__ = predictions.reshape(len(_A ) , 1 ) return predictions def UpperCAmelCase_ ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = fetch_california_housing() SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = data_handling(_A ) SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ = train_test_split( _A , _A , test_size=0.2_5 , random_state=1 ) SCREAMING_SNAKE_CASE__ = xgboost(_A , _A , _A ) # Error printing print(F'''Mean Absolute Error : {mean_absolute_error(_A , _A )}''' ) print(F'''Mean Square Error : {mean_squared_error(_A , _A )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
314
def __a ( ) -> list[list[int]]: '''simple docstring''' return [list(range(1_0_0_0 - i , -1_0_0_0 - i , -1 ) ) for i in range(1_0_0_0 )] A_ : Union[str, Any] = generate_large_matrix() A_ : Union[str, Any] = ( [[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 __a ( SCREAMING_SNAKE_CASE ) -> None: '''simple docstring''' 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 __a ( SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' __UpperCAmelCase = 0 __UpperCAmelCase = 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: __UpperCAmelCase = (left + right) // 2 __UpperCAmelCase = 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: __UpperCAmelCase = mid + 1 else: __UpperCAmelCase = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(SCREAMING_SNAKE_CASE ) def __a ( SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' __UpperCAmelCase = 0 __UpperCAmelCase = len(grid[0] ) for i in range(len(SCREAMING_SNAKE_CASE ) ): __UpperCAmelCase = find_negative_index(grid[i][:bound] ) total += bound return (len(SCREAMING_SNAKE_CASE ) * len(grid[0] )) - total def __a ( SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def __a ( SCREAMING_SNAKE_CASE ) -> int: '''simple docstring''' __UpperCAmelCase = 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 __a ( ) -> None: '''simple docstring''' from timeit import timeit print('''Running benchmarks''' ) __UpperCAmelCase = ( '''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 ): __UpperCAmelCase = 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()
333
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor _UpperCamelCase: Union[str, Any] = logging.get_logger(__name__) class a__ ( SCREAMING_SNAKE_CASE__ ): def __init__( self : int, *lowerCAmelCase : Dict, **lowerCAmelCase : Optional[Any] ) -> None: warnings.warn( 'The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DPTImageProcessor instead.', lowerCAmelCase, ) super().__init__(*lowerCAmelCase, **lowerCAmelCase )
53
"""simple docstring""" def lowercase__ ( _UpperCAmelCase ) -> int: '''simple docstring''' assert isinstance(_UpperCAmelCase , _UpperCAmelCase ), f'''The input value of [n={number}] is not an integer''' if number == 1: return 2 elif number < 1: lowercase : List[Any] = f'''The input value of [n={number}] has to be > 0''' raise ValueError(_UpperCAmelCase ) else: lowercase : str = sylvester(number - 1 ) lowercase : Union[str, Any] = num - 1 lowercase : List[Any] = num return lower * upper + 1 if __name__ == "__main__": print(f'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
53
1
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowercase__ : Tuple = False lowercase__ : Optional[int] = logging.get_logger(__name__) lowercase__ : Optional[Any] = "ybelkada/fonts" def A_ ( ) -> int: '''simple docstring''' if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( f"You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use " '''Pix2StructImageProcessor. Please upgrade torch.''' ) def A_ ( snake_case : List[str] , snake_case : Union[str, Any] , snake_case : Any ) -> int: '''simple docstring''' requires_backends(snake_case , ['''torch'''] ) _check_torch_version() __UpperCamelCase = image_tensor.unsqueeze(0 ) __UpperCamelCase = torch.nn.functional.unfold(snake_case , (patch_height, patch_width) , stride=(patch_height, patch_width) ) __UpperCamelCase = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , snake_case , snake_case , -1 ) __UpperCamelCase = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def A_ ( snake_case : str , snake_case : int = 36 , snake_case : str = "black" , snake_case : str = "white" , snake_case : int = 5 , snake_case : int = 5 , snake_case : int = 5 , snake_case : int = 5 , snake_case : Optional[bytes] = None , snake_case : Optional[str] = None , ) -> Image.Image: '''simple docstring''' requires_backends(snake_case , '''vision''' ) # Add new lines so that each line is no more than 80 characters. __UpperCamelCase = textwrap.TextWrapper(width=80 ) __UpperCamelCase = wrapper.wrap(text=snake_case ) __UpperCamelCase = '''\n'''.join(snake_case ) if font_bytes is not None and font_path is None: __UpperCamelCase = io.BytesIO(snake_case ) elif font_path is not None: __UpperCamelCase = font_path else: __UpperCamelCase = hf_hub_download(snake_case , '''Arial.TTF''' ) __UpperCamelCase = ImageFont.truetype(snake_case , encoding='''UTF-8''' , size=snake_case ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. __UpperCamelCase = ImageDraw.Draw(Image.new('''RGB''' , (1, 1) , snake_case ) ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = temp_draw.textbbox((0, 0) , snake_case , snake_case ) # Create the actual image with a bit of padding around the text. __UpperCamelCase = text_width + left_padding + right_padding __UpperCamelCase = text_height + top_padding + bottom_padding __UpperCamelCase = Image.new('''RGB''' , (image_width, image_height) , snake_case ) __UpperCamelCase = ImageDraw.Draw(snake_case ) draw.text(xy=(left_padding, top_padding) , text=snake_case , fill=snake_case , font=snake_case ) return image def A_ ( snake_case : np.ndarray , snake_case : str , **snake_case : List[Any] ) -> Optional[Any]: '''simple docstring''' requires_backends(snake_case , '''vision''' ) # Convert to PIL image if necessary __UpperCamelCase = to_pil_image(snake_case ) __UpperCamelCase = render_text(snake_case , **snake_case ) __UpperCamelCase = max(header_image.width , image.width ) __UpperCamelCase = int(image.height * (new_width / image.width) ) __UpperCamelCase = int(header_image.height * (new_width / header_image.width) ) __UpperCamelCase = Image.new('''RGB''' , (new_width, new_height + new_header_height) , '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary __UpperCamelCase = to_numpy_array(snake_case ) if infer_channel_dimension_format(snake_case ) == ChannelDimension.LAST: __UpperCamelCase = to_channel_dimension_format(snake_case , ChannelDimension.LAST ) return new_image class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = ['flattened_patches'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 2048 , SCREAMING_SNAKE_CASE_ = False , **SCREAMING_SNAKE_CASE_ , )-> None: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} __UpperCamelCase = do_normalize __UpperCamelCase = do_convert_rgb __UpperCamelCase = max_patches __UpperCamelCase = is_vqa def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ )-> np.ndarray: '''simple docstring''' requires_backends(self.extract_flattened_patches , '''torch''' ) _check_torch_version() # convert to torch __UpperCamelCase = to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , ChannelDimension.FIRST ) __UpperCamelCase = torch.from_numpy(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase , __UpperCamelCase = patch_size['''height'''], patch_size['''width'''] __UpperCamelCase , __UpperCamelCase = get_image_size(SCREAMING_SNAKE_CASE_ ) # maximize scale s.t. __UpperCamelCase = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) __UpperCamelCase = max(min(math.floor(scale * image_height / patch_height ) , SCREAMING_SNAKE_CASE_ ) , 1 ) __UpperCamelCase = max(min(math.floor(scale * image_width / patch_width ) , SCREAMING_SNAKE_CASE_ ) , 1 ) __UpperCamelCase = max(num_feasible_rows * patch_height , 1 ) __UpperCamelCase = max(num_feasible_cols * patch_width , 1 ) __UpperCamelCase = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='''bilinear''' , align_corners=SCREAMING_SNAKE_CASE_ , antialias=SCREAMING_SNAKE_CASE_ , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] __UpperCamelCase = torch_extract_patches(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = patches.shape __UpperCamelCase = patches_shape[1] __UpperCamelCase = patches_shape[2] __UpperCamelCase = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] __UpperCamelCase = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] __UpperCamelCase = torch.arange(SCREAMING_SNAKE_CASE_ ).reshape([rows, 1] ).repeat(1 , SCREAMING_SNAKE_CASE_ ).reshape([rows * columns, 1] ) __UpperCamelCase = torch.arange(SCREAMING_SNAKE_CASE_ ).reshape([1, columns] ).repeat(SCREAMING_SNAKE_CASE_ , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] __UpperCamelCase = row_ids.to(torch.floataa ) __UpperCamelCase = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] __UpperCamelCase = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] __UpperCamelCase = torch.nn.functional.pad(SCREAMING_SNAKE_CASE_ , [0, 0, 0, max_patches - (rows * columns)] ).float() __UpperCamelCase = to_numpy_array(SCREAMING_SNAKE_CASE_ ) return result def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ )-> np.ndarray: '''simple docstring''' if image.dtype == np.uinta: __UpperCamelCase = image.astype(np.floataa ) # take mean across the whole `image` __UpperCamelCase = np.mean(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = np.std(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = max(SCREAMING_SNAKE_CASE_ , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def A__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , )-> ImageInput: '''simple docstring''' __UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize __UpperCamelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __UpperCamelCase = patch_size if patch_size is not None else self.patch_size __UpperCamelCase = max_patches if max_patches is not None else self.max_patches __UpperCamelCase = self.is_vqa if kwargs.get('''data_format''' , SCREAMING_SNAKE_CASE_ ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) __UpperCamelCase = 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.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __UpperCamelCase = [convert_to_rgb(SCREAMING_SNAKE_CASE_ ) for image in images] # All transformations expect numpy arrays. __UpperCamelCase = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) __UpperCamelCase = kwargs.pop('''font_bytes''' , SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = kwargs.pop('''font_path''' , SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __UpperCamelCase = [header_text] * len(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = [ render_header(SCREAMING_SNAKE_CASE_ , header_text[i] , font_bytes=SCREAMING_SNAKE_CASE_ , font_path=SCREAMING_SNAKE_CASE_ ) for i, image in enumerate(SCREAMING_SNAKE_CASE_ ) ] if do_normalize: __UpperCamelCase = [self.normalize(image=SCREAMING_SNAKE_CASE_ ) for image in images] # convert to torch tensor and permute __UpperCamelCase = [ self.extract_flattened_patches(image=SCREAMING_SNAKE_CASE_ , max_patches=SCREAMING_SNAKE_CASE_ , patch_size=SCREAMING_SNAKE_CASE_ ) for image in images ] # create attention mask in numpy __UpperCamelCase = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] __UpperCamelCase = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} , tensor_type=SCREAMING_SNAKE_CASE_ ) return encoded_outputs
328
from math import factorial def A_ ( snake_case : int = 100 ) -> int: '''simple docstring''' return sum(int(snake_case ) for x in str(factorial(snake_case ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
328
1
from math import factorial def lowerCAmelCase( SCREAMING_SNAKE_CASE_ = 1_0_0 )-> int: """simple docstring""" return sum(int(SCREAMING_SNAKE_CASE_ ) for x in str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
60
import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class __magic_name__ ( unittest.TestCase ): def __init__( self , _lowercase , _lowercase=13 , _lowercase=7 , _lowercase=True , _lowercase=True , _lowercase=True , _lowercase=True , _lowercase=99 , _lowercase=32 , _lowercase=5 , _lowercase=4 , _lowercase=37 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=16 , _lowercase=2 , _lowercase=0.02 , _lowercase=4 , )-> Union[str, Any]: UpperCamelCase_ = parent UpperCamelCase_ = batch_size UpperCamelCase_ = seq_length UpperCamelCase_ = is_training UpperCamelCase_ = use_attention_mask UpperCamelCase_ = use_token_type_ids UpperCamelCase_ = use_labels UpperCamelCase_ = vocab_size UpperCamelCase_ = hidden_size UpperCamelCase_ = num_hidden_layers UpperCamelCase_ = num_attention_heads UpperCamelCase_ = intermediate_size UpperCamelCase_ = hidden_act UpperCamelCase_ = hidden_dropout_prob UpperCamelCase_ = attention_probs_dropout_prob UpperCamelCase_ = max_position_embeddings UpperCamelCase_ = type_vocab_size UpperCamelCase_ = type_sequence_label_size UpperCamelCase_ = initializer_range UpperCamelCase_ = num_choices def UpperCAmelCase_ ( self )-> Optional[Any]: UpperCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase_ = None if self.use_attention_mask: UpperCamelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase_ = None if self.use_token_type_ids: UpperCamelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase_ = AlbertConfig( 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=_lowercase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase_ ( self )-> str: UpperCamelCase_ = self.prepare_config_and_inputs() UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = config_and_inputs UpperCamelCase_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class __magic_name__ ( snake_case , unittest.TestCase ): UpperCamelCase_ :Optional[Any] = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase_ ( self )-> Optional[int]: UpperCamelCase_ = FlaxAlbertModelTester(self ) @slow def UpperCAmelCase_ ( self )-> str: for model_class_name in self.all_model_classes: UpperCamelCase_ = model_class_name.from_pretrained("albert-base-v2" ) UpperCamelCase_ = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowercase ) @require_flax class __magic_name__ ( unittest.TestCase ): @slow def UpperCAmelCase_ ( self )-> List[str]: UpperCamelCase_ = FlaxAlbertModel.from_pretrained("albert-base-v2" ) UpperCamelCase_ = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) UpperCamelCase_ = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) UpperCamelCase_ = model(_lowercase , attention_mask=_lowercase )[0] UpperCamelCase_ = (1, 11, 768) self.assertEqual(output.shape , _lowercase ) UpperCamelCase_ = np.array( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , _lowercase , atol=1e-4 ) )
60
1
import numpy as np import datasets lowercase__ ='\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n' lowercase__ ='\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n' lowercase__ ='\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric("mahalanobis")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {\'mahalanobis\': array([0.5])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): def lowerCAmelCase (self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' , id='''sequence''' ) , id='''X''' ), } ) , ) def lowerCAmelCase (self : int , snake_case_ : List[str] , snake_case_ : List[Any] ): # convert to numpy arrays __a : str = np.array(snake_case_ ) __a : Dict = np.array(snake_case_ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction __a : Tuple = X - np.mean(snake_case_ ) __a : List[Any] = np.cov(reference_distribution.T ) try: __a : str = np.linalg.inv(snake_case_ ) except np.linalg.LinAlgError: __a : str = np.linalg.pinv(snake_case_ ) __a : int = np.dot(snake_case_ , snake_case_ ) __a : Any = np.dot(snake_case_ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
216
from pathlib import Path from typing import List from transformers import is_torch_available, is_vision_available from transformers.testing_utils import get_tests_dir, is_tool_test from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText if is_torch_available(): import torch if is_vision_available(): from PIL import Image lowercase__ =['text', 'image', 'audio'] def __UpperCamelCase ( lowerCAmelCase__ : List[str] ): __a : Optional[int] = [] for input_type in input_types: if input_type == "text": inputs.append('''Text input''' ) elif input_type == "image": inputs.append( Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((5_1_2, 5_1_2) ) ) elif input_type == "audio": inputs.append(torch.ones(3_0_0_0 ) ) elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): inputs.append(create_inputs(lowerCAmelCase__ ) ) else: raise ValueError(f"Invalid type requested: {input_type}" ) return inputs def __UpperCamelCase ( lowerCAmelCase__ : List ): __a : List[str] = [] for output in outputs: if isinstance(lowerCAmelCase__ , (str, AgentText) ): output_types.append('''text''' ) elif isinstance(lowerCAmelCase__ , (Image.Image, AgentImage) ): output_types.append('''image''' ) elif isinstance(lowerCAmelCase__ , (torch.Tensor, AgentAudio) ): output_types.append('''audio''' ) else: raise ValueError(f"Invalid output: {output}" ) return output_types @is_tool_test class UpperCamelCase__ : def lowerCAmelCase (self : Any ): self.assertTrue(hasattr(self.tool , '''inputs''' ) ) self.assertTrue(hasattr(self.tool , '''outputs''' ) ) __a : Any = self.tool.inputs for _input in inputs: if isinstance(_input , snake_case_ ): for __input in _input: self.assertTrue(__input in authorized_types ) else: self.assertTrue(_input in authorized_types ) __a : Optional[int] = self.tool.outputs for _output in outputs: self.assertTrue(_output in authorized_types ) def lowerCAmelCase (self : List[Any] ): __a : Union[str, Any] = create_inputs(self.tool.inputs ) __a : List[Any] = self.tool(*snake_case_ ) # There is a single output if len(self.tool.outputs ) == 1: __a : Tuple = [outputs] self.assertListEqual(output_types(snake_case_ ) , self.tool.outputs ) def lowerCAmelCase (self : List[Any] ): self.assertTrue(hasattr(self.tool , '''description''' ) ) self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) ) self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) ) def lowerCAmelCase (self : Any ): __a : Any = create_inputs(self.tool.inputs ) __a : Union[str, Any] = self.tool(*snake_case_ ) if not isinstance(snake_case_ , snake_case_ ): __a : Tuple = [outputs] self.assertEqual(len(snake_case_ ) , len(self.tool.outputs ) ) for output, output_type in zip(snake_case_ , self.tool.outputs ): __a : List[Any] = AGENT_TYPE_MAPPING[output_type] self.assertTrue(isinstance(snake_case_ , snake_case_ ) ) def lowerCAmelCase (self : Optional[int] ): __a : Any = create_inputs(self.tool.inputs ) __a : Dict = [] for _input, input_type in zip(snake_case_ , self.tool.inputs ): if isinstance(snake_case_ , snake_case_ ): _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] ) else: _inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) ) # Should not raise an error __a : Optional[Any] = self.tool(*snake_case_ ) if not isinstance(snake_case_ , snake_case_ ): __a : Dict = [outputs] self.assertEqual(len(snake_case_ ) , len(self.tool.outputs ) )
216
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase_ = { '''configuration_m2m_100''': ['''M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''M2M100Config''', '''M2M100OnnxConfig'''], '''tokenization_m2m_100''': ['''M2M100Tokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST''', '''M2M100ForConditionalGeneration''', '''M2M100Model''', '''M2M100PreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
174
'''simple docstring''' def __lowercase ( __lowercase ) -> int: '''simple docstring''' if not isinstance(__lowercase , __lowercase ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) _A = 0 _A = str(__lowercase ) while len(__lowercase ) != 1: _A = [int(__lowercase ) for i in num_string] _A = 1 for i in range(0 , len(__lowercase ) ): total *= numbers[i] _A = str(__lowercase ) steps += 1 return steps def __lowercase ( __lowercase ) -> int: '''simple docstring''' if not isinstance(__lowercase , __lowercase ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) _A = 0 _A = str(__lowercase ) while len(__lowercase ) != 1: _A = [int(__lowercase ) for i in num_string] _A = 0 for i in range(0 , len(__lowercase ) ): total += numbers[i] _A = str(__lowercase ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
174
1
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class _a ( __a ): __a : str = ["""vqvae"""] def __init__( self : str , lowercase : AutoencoderKL , lowercase : UNetaDConditionModel , lowercase : Mel , lowercase : Union[DDIMScheduler, DDPMScheduler] , ): '''simple docstring''' super().__init__() self.register_modules(unet=lowercase , scheduler=lowercase , mel=lowercase , vqvae=lowercase ) def A ( self : Optional[Any] ): '''simple docstring''' return 50 if isinstance(self.scheduler , lowercase ) else 1_000 @torch.no_grad() def __call__( self : Optional[Any] , lowercase : int = 1 , lowercase : str = None , lowercase : np.ndarray = None , lowercase : int = 0 , lowercase : int = 0 , lowercase : int = None , lowercase : torch.Generator = None , lowercase : float = 0 , lowercase : float = 0 , lowercase : torch.Generator = None , lowercase : float = 0 , lowercase : torch.Tensor = None , lowercase : torch.Tensor = None , lowercase : Tuple=True , ): '''simple docstring''' UpperCAmelCase = steps or self.get_default_steps() self.scheduler.set_timesteps(lowercase ) UpperCAmelCase = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: UpperCAmelCase = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: UpperCAmelCase = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowercase , device=self.device , ) UpperCAmelCase = noise UpperCAmelCase = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowercase , lowercase ) UpperCAmelCase = self.mel.audio_slice_to_image(lowercase ) UpperCAmelCase = np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) UpperCAmelCase = (input_image / 255) * 2 - 1 UpperCAmelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: UpperCAmelCase = self.vqvae.encode(torch.unsqueeze(lowercase , 0 ) ).latent_dist.sample( generator=lowercase )[0] UpperCAmelCase = self.vqvae.config.scaling_factor * input_images if start_step > 0: UpperCAmelCase = self.scheduler.add_noise(lowercase , lowercase , self.scheduler.timesteps[start_step - 1] ) UpperCAmelCase = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) UpperCAmelCase = int(mask_start_secs * pixels_per_second ) UpperCAmelCase = int(mask_end_secs * pixels_per_second ) UpperCAmelCase = self.scheduler.add_noise(lowercase , lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowercase ): UpperCAmelCase = self.unet(lowercase , lowercase , lowercase )['''sample'''] else: UpperCAmelCase = self.unet(lowercase , lowercase )['''sample'''] if isinstance(self.scheduler , lowercase ): UpperCAmelCase = self.scheduler.step( model_output=lowercase , timestep=lowercase , sample=lowercase , eta=lowercase , generator=lowercase , )['''prev_sample'''] else: UpperCAmelCase = self.scheduler.step( model_output=lowercase , timestep=lowercase , sample=lowercase , generator=lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: UpperCAmelCase = mask[:, step, :, :mask_start] if mask_end > 0: UpperCAmelCase = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance UpperCAmelCase = 1 / self.vqvae.config.scaling_factor * images UpperCAmelCase = self.vqvae.decode(lowercase )['''sample'''] UpperCAmelCase = (images / 2 + 0.5).clamp(0 , 1 ) UpperCAmelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() UpperCAmelCase = (images * 255).round().astype('''uint8''' ) UpperCAmelCase = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) UpperCAmelCase = [self.mel.image_to_audio(lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowercase ) ) @torch.no_grad() def A ( self : Dict , lowercase : List[Image.Image] , lowercase : int = 50 ): '''simple docstring''' assert isinstance(self.scheduler , lowercase ) self.scheduler.set_timesteps(lowercase ) UpperCAmelCase = np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) UpperCAmelCase = (sample / 255) * 2 - 1 UpperCAmelCase = torch.Tensor(lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): UpperCAmelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps UpperCAmelCase = self.scheduler.alphas_cumprod[t] UpperCAmelCase = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) UpperCAmelCase = 1 - alpha_prod_t UpperCAmelCase = self.unet(lowercase , lowercase )['''sample'''] UpperCAmelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output UpperCAmelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) UpperCAmelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def A ( lowercase : torch.Tensor , lowercase : torch.Tensor , lowercase : float ): '''simple docstring''' UpperCAmelCase = acos(torch.dot(torch.flatten(lowercase ) , torch.flatten(lowercase ) ) / torch.norm(lowercase ) / torch.norm(lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(lowercase ) + sin(alpha * theta ) * xa / sin(lowercase )
34
'''simple docstring''' import json import os import re import shutil import tempfile import unittest from typing import Tuple from transformers import AddedToken, BatchEncoding, PerceiverTokenizer from transformers.utils import cached_property, is_tf_available, is_torch_available from ...test_tokenization_common import TokenizerTesterMixin if is_torch_available(): A ='pt' elif is_tf_available(): A ='tf' else: A ='jax' class _a ( __a , unittest.TestCase ): __a : Optional[Any] = PerceiverTokenizer __a : str = False def A ( self : Union[str, Any] ): '''simple docstring''' super().setUp() UpperCAmelCase = PerceiverTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self : Optional[int] ): '''simple docstring''' return PerceiverTokenizer.from_pretrained('''deepmind/language-perceiver''' ) def A ( self : Union[str, Any] , **lowercase : int ): '''simple docstring''' return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase ) def A ( self : Tuple , lowercase : str , lowercase : List[str]=False , lowercase : Union[str, Any]=20 , lowercase : Union[str, Any]=5 ): '''simple docstring''' UpperCAmelCase = [] for i in range(len(lowercase ) ): try: UpperCAmelCase = tokenizer.decode([i] , clean_up_tokenization_spaces=lowercase ) except UnicodeDecodeError: pass toks.append((i, tok) ) UpperCAmelCase = list(filter(lambda lowercase : re.match(R'''^[ a-zA-Z]+$''' , t[1] ) , lowercase ) ) UpperCAmelCase = list(filter(lambda lowercase : [t[0]] == tokenizer.encode(t[1] , add_special_tokens=lowercase ) , lowercase ) ) if max_length is not None and len(lowercase ) > max_length: UpperCAmelCase = toks[:max_length] if min_length is not None and len(lowercase ) < min_length and len(lowercase ) > 0: while len(lowercase ) < min_length: UpperCAmelCase = toks + toks # toks_str = [t[1] for t in toks] UpperCAmelCase = [t[0] for t in toks] # Ensure consistency UpperCAmelCase = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) if " " not in output_txt and len(lowercase ) > 1: UpperCAmelCase = ( tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=lowercase ) + ''' ''' + tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=lowercase ) ) if with_prefix_space: UpperCAmelCase = ''' ''' + output_txt UpperCAmelCase = tokenizer.encode(lowercase , add_special_tokens=lowercase ) return output_txt, output_ids def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = self.perceiver_tokenizer UpperCAmelCase = '''Unicode €.''' UpperCAmelCase = tokenizer(lowercase ) UpperCAmelCase = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5] self.assertEqual(encoded['''input_ids'''] , lowercase ) # decoding UpperCAmelCase = tokenizer.decode(lowercase ) self.assertEqual(lowercase , '''[CLS]Unicode €.[SEP]''' ) UpperCAmelCase = tokenizer('''e è é ê ë''' ) UpperCAmelCase = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5] self.assertEqual(encoded['''input_ids'''] , lowercase ) # decoding UpperCAmelCase = tokenizer.decode(lowercase ) self.assertEqual(lowercase , '''[CLS]e è é ê ë[SEP]''' ) # encode/decode, but with `encode` instead of `__call__` self.assertEqual(tokenizer.decode(tokenizer.encode('''e è é ê ë''' ) ) , '''[CLS]e è é ê ë[SEP]''' ) def A ( self : str ): '''simple docstring''' UpperCAmelCase = self.perceiver_tokenizer UpperCAmelCase = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] # fmt: off UpperCAmelCase = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: on UpperCAmelCase = tokenizer(lowercase , padding=lowercase , return_tensors=lowercase ) self.assertIsInstance(lowercase , lowercase ) if FRAMEWORK != "jax": UpperCAmelCase = list(batch.input_ids.numpy()[0] ) else: UpperCAmelCase = list(batch.input_ids.tolist()[0] ) self.assertListEqual(lowercase , lowercase ) self.assertEqual((2, 38) , batch.input_ids.shape ) self.assertEqual((2, 38) , batch.attention_mask.shape ) def A ( self : str ): '''simple docstring''' UpperCAmelCase = self.perceiver_tokenizer UpperCAmelCase = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] UpperCAmelCase = tokenizer(lowercase , padding=lowercase , return_tensors=lowercase ) # check if input_ids are returned and no decoder_input_ids self.assertIn('''input_ids''' , lowercase ) self.assertIn('''attention_mask''' , lowercase ) self.assertNotIn('''decoder_input_ids''' , lowercase ) self.assertNotIn('''decoder_attention_mask''' , lowercase ) def A ( self : Dict ): '''simple docstring''' UpperCAmelCase = self.perceiver_tokenizer UpperCAmelCase = [ '''Summary of the text.''', '''Another summary.''', ] UpperCAmelCase = tokenizer( text_target=lowercase , max_length=32 , padding='''max_length''' , truncation=lowercase , return_tensors=lowercase ) self.assertEqual(32 , targets['''input_ids'''].shape[1] ) def A ( self : int ): '''simple docstring''' UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test UpperCAmelCase = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = ''' He is very happy, UNwant\u00E9d,running''' UpperCAmelCase = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) UpperCAmelCase = tokenizer.__class__.from_pretrained(lowercase ) UpperCAmelCase = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) shutil.rmtree(lowercase ) UpperCAmelCase = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): # Isolate this from the other tests because we save additional tokens/etc UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = ''' He is very happy, UNwant\u00E9d,running''' tokenizer.add_tokens(['''bim''', '''bambam'''] ) UpperCAmelCase = tokenizer.additional_special_tokens additional_special_tokens.append('''new_additional_special_token''' ) tokenizer.add_special_tokens({'''additional_special_tokens''': additional_special_tokens} ) UpperCAmelCase = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) UpperCAmelCase = tokenizer.__class__.from_pretrained(lowercase ) UpperCAmelCase = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) self.assertIn('''new_additional_special_token''' , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) UpperCAmelCase = tokenizer.__class__.from_pretrained(lowercase , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(lowercase ) def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowercase ) with open(os.path.join(lowercase , '''special_tokens_map.json''' ) , encoding='''utf-8''' ) as json_file: UpperCAmelCase = json.load(lowercase ) with open(os.path.join(lowercase , '''tokenizer_config.json''' ) , encoding='''utf-8''' ) as json_file: UpperCAmelCase = json.load(lowercase ) UpperCAmelCase = [f"<extra_id_{i}>" for i in range(125 )] UpperCAmelCase = added_tokens_extra_ids + [ '''an_additional_special_token''' ] UpperCAmelCase = added_tokens_extra_ids + [ '''an_additional_special_token''' ] with open(os.path.join(lowercase , '''special_tokens_map.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(lowercase , lowercase ) with open(os.path.join(lowercase , '''tokenizer_config.json''' ) , '''w''' , encoding='''utf-8''' ) as outfile: json.dump(lowercase , lowercase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files UpperCAmelCase = tokenizer_class.from_pretrained( lowercase , ) self.assertIn( '''an_additional_special_token''' , tokenizer_without_change_in_init.additional_special_tokens ) self.assertEqual( ['''an_additional_special_token'''] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids(['''an_additional_special_token'''] ) ) , ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained UpperCAmelCase = added_tokens_extra_ids + [AddedToken('''a_new_additional_special_token''' , lstrip=lowercase )] UpperCAmelCase = tokenizer_class.from_pretrained( lowercase , additional_special_tokens=lowercase , ) self.assertIn('''a_new_additional_special_token''' , tokenizer.additional_special_tokens ) self.assertEqual( ['''a_new_additional_special_token'''] , tokenizer.convert_ids_to_tokens( tokenizer.convert_tokens_to_ids(['''a_new_additional_special_token'''] ) ) , ) def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = self.perceiver_tokenizer self.assertEqual(tokenizer.decode([178] ) , '''�''' ) def A ( self : Union[str, Any] ): '''simple docstring''' pass def A ( self : Any ): '''simple docstring''' pass def A ( self : Dict ): '''simple docstring''' pass def A ( self : str ): '''simple docstring''' pass def A ( self : List[str] ): '''simple docstring''' UpperCAmelCase = self.get_tokenizers(fast=lowercase , do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}" ): UpperCAmelCase = ['''[CLS]''', '''t''', '''h''', '''i''', '''s''', ''' ''', '''i''', '''s''', ''' ''', '''a''', ''' ''', '''t''', '''e''', '''s''', '''t''', '''[SEP]'''] UpperCAmelCase = tokenizer.convert_tokens_to_string(lowercase ) self.assertIsInstance(lowercase , lowercase )
34
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __lowercase ( unittest.TestCase ): '''simple docstring''' def A_ ( self : int ): UpperCamelCase__ = 0 def A_ ( self : str ): UpperCamelCase__ = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_a , _a ) def A_ ( self : Union[str, Any] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ = Path(_a ) / '''preprocessor_config.json''' UpperCamelCase__ = Path(_a ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_a , '''w''' ) ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def A_ ( self : List[str] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ = Path(_a ) / '''preprocessor_config.json''' UpperCamelCase__ = Path(_a ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_a , '''w''' ) ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def A_ ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCamelCase__ = Path(_a ) / '''preprocessor_config.json''' UpperCamelCase__ = Path(_a ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_a , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ).to_dict() config_dict.pop('''image_processor_type''' ) UpperCamelCase__ = CLIPImageProcessor(**_a ) # save in new folder model_config.save_pretrained(_a ) config.save_pretrained(_a ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ) # make sure private variable is not incorrectly saved UpperCamelCase__ = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_a , _a ) def A_ ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ = Path(_a ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_a , '''w''' ) , ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def A_ ( self : Dict ): with self.assertRaisesRegex( _a , '''clip-base is not a local folder and is not a valid model identifier''' ): UpperCamelCase__ = AutoImageProcessor.from_pretrained('''clip-base''' ) def A_ ( self : List[Any] ): with self.assertRaisesRegex( _a , R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a , revision='''aaaaaa''' ) def A_ ( self : Optional[int] ): with self.assertRaisesRegex( _a , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): UpperCamelCase__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def A_ ( self : int ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_a ): UpperCamelCase__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): UpperCamelCase__ = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_a ) UpperCamelCase__ = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a , trust_remote_code=_a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def A_ ( self : Any ): try: AutoConfig.register('''custom''' , _a ) AutoImageProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoImageProcessor.register(_a , _a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase__ = Path(_a ) / '''preprocessor_config.json''' UpperCamelCase__ = Path(_a ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_a , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_a , '''w''' ) ) UpperCamelCase__ = CustomImageProcessor.from_pretrained(_a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) UpperCamelCase__ = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def A_ ( self : Any ): class __lowercase ( A ): '''simple docstring''' _A : Optional[Any] = True try: AutoConfig.register('''custom''' , _a ) AutoImageProcessor.register(_a , _a ) # If remote code is not set, the default is to use local UpperCamelCase__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCamelCase__ = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCamelCase__ = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_a , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
35
import warnings from ...utils import logging from .image_processing_chinese_clip import ChineseCLIPImageProcessor lowercase = logging.get_logger(__name__) class __lowercase ( A ): '''simple docstring''' def __init__( self : List[str] , *_a : Any , **_a : str ): warnings.warn( '''The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use ChineseCLIPImageProcessor instead.''' , _a , ) super().__init__(*_a , **_a )
35
1
'''simple docstring''' def lowercase__ ( __lowercase : int ) -> "list[int]": """simple docstring""" if upper_limit < 0: raise ValueError('Limit for the Catalan sequence must be ≥ 0' ) __UpperCamelCase = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __UpperCamelCase = 1 if upper_limit > 0: __UpperCamelCase = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(__lowercase ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : Union[str, Any] =int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(f'The Catalan numbers from 0 through {N} are:') print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
53
'''simple docstring''' from __future__ import annotations from typing import Any class snake_case ( __lowerCamelCase ): """simple docstring""" pass class snake_case : """simple docstring""" def __init__( self : List[Any] , __A : Any ): __UpperCamelCase = data __UpperCamelCase = None def __iter__( self : Optional[Any] ): __UpperCamelCase = self __UpperCamelCase = [] while node: if node in visited: raise ContainsLoopError visited.append(__A ) yield node.data __UpperCamelCase = node.next_node @property def _lowerCamelCase ( self : List[str] ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": a__ : Dict =Node(1) a__ : Optional[int] =Node(2) a__ : List[str] =Node(3) a__ : Optional[int] =Node(4) print(root_node.has_loop) # False a__ : str =root_node.next_node print(root_node.has_loop) # True a__ : Optional[int] =Node(5) a__ : List[Any] =Node(6) a__ : int =Node(5) a__ : Tuple =Node(6) print(root_node.has_loop) # False a__ : str =Node(1) print(root_node.has_loop) # False
53
1
'''simple docstring''' __lowerCamelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) -> list[str]: A_ = set() # keep track of all the paths to be checked A_ = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue A_ = queue.pop(0 ) # get the last node from the path A_ = path[-1] if node not in explored: A_ = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: A_ = list(UpperCAmelCase__ ) new_path.append(UpperCAmelCase__ ) queue.append(UpperCAmelCase__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(UpperCAmelCase__ ) # in case there's no path between the 2 nodes return [] def UpperCAmelCase__ ( UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 A_ = [start] A_ = set(UpperCAmelCase__ ) # Keep tab on distances from `start` node. A_ = {start: 0, target: -1} while queue: A_ = queue.pop(0 ) if node == target: A_ = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(UpperCAmelCase__ ) queue.append(UpperCAmelCase__ ) A_ = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
101
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class A__ ( _snake_case ): def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = False , **UpperCamelCase__ , ) -> Optional[Any]: '''simple docstring''' super().__init__(features=UpperCamelCase__ , cache_dir=UpperCamelCase__ , keep_in_memory=UpperCamelCase__ , **UpperCamelCase__ ) A_ = Sql( cache_dir=UpperCamelCase__ , features=UpperCamelCase__ , sql=UpperCamelCase__ , con=UpperCamelCase__ , **UpperCamelCase__ , ) def snake_case_ ( self ) -> Optional[Any]: '''simple docstring''' A_ = None A_ = None A_ = None A_ = None self.builder.download_and_prepare( download_config=UpperCamelCase__ , download_mode=UpperCamelCase__ , verification_mode=UpperCamelCase__ , base_path=UpperCamelCase__ , ) # Build dataset for splits A_ = self.builder.as_dataset( split="""train""" , verification_mode=UpperCamelCase__ , in_memory=self.keep_in_memory ) return dataset class A__ : def __init__( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> List[Any]: '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) A_ = dataset A_ = name A_ = con A_ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE A_ = num_proc A_ = to_sql_kwargs def snake_case_ ( self ) -> int: '''simple docstring''' A_ = self.to_sql_kwargs.pop("""sql""" , UpperCamelCase__ ) A_ = self.to_sql_kwargs.pop("""con""" , UpperCamelCase__ ) A_ = self.to_sql_kwargs.pop("""index""" , UpperCamelCase__ ) A_ = self._write(index=UpperCamelCase__ , **self.to_sql_kwargs ) return written def snake_case_ ( self , UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' A_ , A_ , A_ = args A_ = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs A_ = query_table( table=self.dataset.data , key=slice(UpperCamelCase__ , offset + self.batch_size ) , indices=self.dataset._indices , ) A_ = batch.to_pandas() A_ = df.to_sql(self.name , self.con , index=UpperCamelCase__ , **UpperCamelCase__ ) return num_rows or len(UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , **UpperCamelCase__ ) -> int: '''simple docstring''' A_ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: A_ , A_ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , UpperCamelCase__ , UpperCamelCase__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
101
1
"""simple docstring""" import math import sys def _snake_case ( _snake_case : int ): if number != int(_snake_case ): raise ValueError('''the value of input must be a natural number''' ) if number < 0: raise ValueError('''the value of input must not be a negative number''' ) if number == 0: return 1 lowerCAmelCase : List[str] = [-1] * (number + 1) lowerCAmelCase : Dict = 0 for i in range(1 , number + 1 ): lowerCAmelCase : Any = sys.maxsize lowerCAmelCase : int = int(math.sqrt(_snake_case ) ) for j in range(1 , root + 1 ): lowerCAmelCase : Dict = 1 + answers[i - (j**2)] lowerCAmelCase : Optional[Any] = min(_snake_case , _snake_case ) lowerCAmelCase : Union[str, Any] = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
60
"""simple docstring""" import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, 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(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class snake_case_( unittest.TestCase ): def __init__( self : List[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[Any]=1_3 , UpperCamelCase_ : Tuple=7 , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : int=True , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : List[str]=9_9 , UpperCamelCase_ : str=3_2 , UpperCamelCase_ : Union[str, Any]=5 , UpperCamelCase_ : int=4 , UpperCamelCase_ : Optional[Any]=3_7 , UpperCamelCase_ : Optional[int]="gelu" , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : List[str]=0.1 , UpperCamelCase_ : str=5_1_2 , UpperCamelCase_ : Optional[Any]=1_6 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : Any=0.02 , UpperCamelCase_ : Union[str, Any]=4 , ): lowerCAmelCase : str = parent lowerCAmelCase : List[str] = batch_size lowerCAmelCase : int = seq_length lowerCAmelCase : str = is_training lowerCAmelCase : Tuple = use_attention_mask lowerCAmelCase : Dict = use_token_type_ids lowerCAmelCase : Optional[int] = use_labels lowerCAmelCase : Optional[Any] = vocab_size lowerCAmelCase : Optional[int] = hidden_size lowerCAmelCase : Optional[Any] = num_hidden_layers lowerCAmelCase : str = num_attention_heads lowerCAmelCase : Optional[Any] = intermediate_size lowerCAmelCase : int = hidden_act lowerCAmelCase : int = hidden_dropout_prob lowerCAmelCase : Tuple = attention_probs_dropout_prob lowerCAmelCase : str = max_position_embeddings lowerCAmelCase : str = type_vocab_size lowerCAmelCase : str = type_sequence_label_size lowerCAmelCase : Any = initializer_range lowerCAmelCase : int = num_choices def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : Optional[int] = None if self.use_attention_mask: lowerCAmelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase : Union[str, Any] = None if self.use_token_type_ids: lowerCAmelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase : Union[str, Any] = RobertaPreLayerNormConfig( 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 : int ): lowerCAmelCase : List[str] = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Optional[Any] = config_and_inputs lowerCAmelCase : Optional[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : int = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Tuple = config_and_inputs lowerCAmelCase : str = True lowerCAmelCase : Optional[Any] = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase : str = 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 # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class snake_case_( a__ , unittest.TestCase ): __UpperCamelCase = True __UpperCamelCase = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Any = FlaxRobertaPreLayerNormModelTester(self ) @slow def lowerCamelCase__ ( self : List[str] ): for model_class_name in self.all_model_classes: lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCamelCase_ ) lowerCAmelCase : int = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCamelCase_ ) @require_flax class snake_case_( unittest.TestCase ): @slow def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : str = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCamelCase_ ) lowerCAmelCase : Any = np.array([[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]] , dtype=jnp.intaa ) lowerCAmelCase : Union[str, Any] = model(UpperCamelCase_ )[0] lowerCAmelCase : str = [1, 1_1, 5_0_2_6_5] self.assertEqual(list(output.shape ) , UpperCamelCase_ ) # compare the actual values for a slice. lowerCAmelCase : Optional[Any] = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCamelCase_ , atol=1E-4 ) ) @slow def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Dict = FlaxRobertaPreLayerNormModel.from_pretrained('''andreasmadsen/efficient_mlm_m0.40''' , from_pt=UpperCamelCase_ ) lowerCAmelCase : str = np.array([[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]] , dtype=jnp.intaa ) lowerCAmelCase : str = model(UpperCamelCase_ )[0] # compare the actual values for a slice. lowerCAmelCase : str = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , UpperCamelCase_ , atol=1E-4 ) )
60
1
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class lowerCamelCase__ ( unittest.TestCase ): def _lowerCamelCase ( self : Optional[int] ): a__: List[str] =torch.nn.Linear(1_0 , 1_0 ) a__: Union[str, Any] =torch.optim.SGD(model.parameters() , 0.1 ) a__: Optional[Any] =Accelerator() a__: Dict =accelerator.prepare(_a ) try: pickle.loads(pickle.dumps(_a ) ) except Exception as e: self.fail(F"Accelerated optimizer pickling failed with {e}" ) AcceleratorState._reset_state()
42
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration __UpperCAmelCase = 5_00_00 __UpperCAmelCase = 50_00 __UpperCAmelCase , __UpperCAmelCase = os.path.split(__file__) __UpperCAmelCase = os.path.join(RESULTS_BASEPATH, '''results''', RESULTS_FILENAME.replace('''.py''', '''.json''')) @get_duration def __lowerCamelCase ( __magic_name__ : datasets.Dataset , __magic_name__ : int ): for i in range(__magic_name__ ): a__: int =dataset[i] @get_duration def __lowerCamelCase ( __magic_name__ : datasets.Dataset , __magic_name__ : Any , __magic_name__ : Union[str, Any] ): for i in range(0 , len(__magic_name__ ) , __magic_name__ ): a__: List[str] =dataset[i : i + batch_size] @get_duration def __lowerCamelCase ( __magic_name__ : datasets.Dataset , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] ): with dataset.formatted_as(type=__magic_name__ ): for i in range(__magic_name__ ): a__: Optional[Any] =dataset[i] @get_duration def __lowerCamelCase ( __magic_name__ : datasets.Dataset , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] ): with dataset.formatted_as(type=__magic_name__ ): for i in range(0 , __magic_name__ , __magic_name__ ): a__: List[Any] =dataset[i : i + batch_size] def __lowerCamelCase ( ): a__: Union[str, Any] ={"num examples": SPEED_TEST_N_EXAMPLES} a__: int =[ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted, {"type": "pandas", "length": SMALL_TEST}), (read_formatted, {"type": "torch", "length": SMALL_TEST}), (read_formatted, {"type": "tensorflow", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_000}), ] a__: Optional[Any] =[ (read, {"length": SMALL_TEST}), (read, {"length": SPEED_TEST_N_EXAMPLES}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 10}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 100}), (read_batch, {"length": SPEED_TEST_N_EXAMPLES, "batch_size": 1_000}), (read_formatted, {"type": "numpy", "length": SMALL_TEST}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 10}), (read_formatted_batch, {"type": "numpy", "length": SMALL_TEST, "batch_size": 1_000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("generating dataset" ) a__: str =datasets.Features( {"list": datasets.Sequence(datasets.Value("float32" ) ), "numbers": datasets.Value("float32" )} ) a__: List[str] =generate_example_dataset( os.path.join(__magic_name__ , "dataset.arrow" ) , __magic_name__ , num_examples=__magic_name__ , seq_shapes={"list": (100,)} , ) print("first set of iterations" ) for func, kwargs in functions: print(func.__name__ , str(__magic_name__ ) ) a__: str =func(__magic_name__ , **__magic_name__ ) print("shuffling dataset" ) a__: List[str] =dataset.shuffle() print("Second set of iterations (after shuffling" ) for func, kwargs in functions_shuffled: print("shuffled " , func.__name__ , str(__magic_name__ ) ) a__: Optional[int] =func( __magic_name__ , **__magic_name__ ) with open(__magic_name__ , "wb" ) as f: f.write(json.dumps(__magic_name__ ).encode("utf-8" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
42
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase): # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: __lowerCAmelCase = ksize + 1 __lowerCAmelCase = np.zeros((ksize, ksize), dtype=np.floataa) # each value for y in range(lowerCamelCase): for x in range(lowerCamelCase): # distance from center __lowerCAmelCase = x - ksize // 2 __lowerCAmelCase = y - ksize // 2 # degree to radiant __lowerCAmelCase = theta / 1_8_0 * np.pi __lowerCAmelCase = np.cos(_theta) __lowerCAmelCase = np.sin(_theta) # get kernel x __lowerCAmelCase = cos_theta * px + sin_theta * py # get kernel y __lowerCAmelCase = -sin_theta * px + cos_theta * py # fill kernel __lowerCAmelCase = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos(2 * np.pi * _x / lambd + psi) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image _UpperCAmelCase : Union[str, Any] = imread("""../image_data/lena.jpg""") # turn image in gray scale value _UpperCAmelCase : Tuple = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges _UpperCAmelCase : Tuple = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: _UpperCAmelCase : int = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) _UpperCAmelCase : Dict = out / out.max() * 2_5_5 _UpperCAmelCase : Dict = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
174
'''simple docstring''' from collections.abc import Generator def __magic_name__( ): __lowerCAmelCase , __lowerCAmelCase = 0, 1 while True: __lowerCAmelCase , __lowerCAmelCase = b, a + b yield b def __magic_name__( lowerCamelCase = 1_0_0_0): __lowerCAmelCase = 1 __lowerCAmelCase = fibonacci_generator() while len(str(next(lowerCamelCase))) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
174
1
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a__ ( __snake_case ): A__ : Dict = 'ClapFeatureExtractor' A__ : Optional[int] = ('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self , UpperCAmelCase , UpperCAmelCase ) -> Dict: super().__init__(a_ , a_ ) def __call__( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , **UpperCAmelCase ) -> Optional[int]: __a = kwargs.pop('sampling_rate' , a_ ) 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 = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if audios is not None: __a = self.feature_extractor( a_ , sampling_rate=a_ , return_tensors=a_ , **a_ ) if text is not None and audios is not None: __a = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __SCREAMING_SNAKE_CASE ( self , *UpperCAmelCase , **UpperCAmelCase ) -> Any: return self.tokenizer.batch_decode(*a_ , **a_ ) def __SCREAMING_SNAKE_CASE ( self , *UpperCAmelCase , **UpperCAmelCase ) -> Tuple: return self.tokenizer.decode(*a_ , **a_ ) @property def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: __a = self.tokenizer.model_input_names __a = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
352
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable lowerCamelCase_ : Union[str, Any] = {"""configuration_gpt_neox""": ["""GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTNeoXConfig"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Union[str, Any] = ["""GPTNeoXTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : List[str] = [ """GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTNeoXForCausalLM""", """GPTNeoXForQuestionAnswering""", """GPTNeoXForSequenceClassification""", """GPTNeoXForTokenClassification""", """GPTNeoXLayer""", """GPTNeoXModel""", """GPTNeoXPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
197
0
'''simple docstring''' from typing import Any import numpy as np def __snake_case( _lowerCAmelCase ) -> bool: return np.array_equal(_lowerCAmelCase , matrix.conjugate().T ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase ) -> Any: snake_case__ : int = v.conjugate().T snake_case__ : Optional[Any] = v_star.dot(_lowerCAmelCase ) assert isinstance(_lowerCAmelCase , np.ndarray ) return (v_star_dot.dot(_lowerCAmelCase )) / (v_star.dot(_lowerCAmelCase )) def __snake_case( ) -> None: snake_case__ : int = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) snake_case__ : List[str] = np.array([[1], [2], [3]] ) assert is_hermitian(_lowerCAmelCase ), f"{a} is not hermitian." print(rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) ) snake_case__ : Optional[int] = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(_lowerCAmelCase ), f"{a} is not hermitian." assert rayleigh_quotient(_lowerCAmelCase , _lowerCAmelCase ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
35
'''simple docstring''' from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self : int , snake_case_ : Tuple , snake_case_ : List[str]=3 , snake_case_ : Tuple=32 , snake_case_ : List[Any]=3 , snake_case_ : List[str]=10 , snake_case_ : List[str]=[10, 20, 30, 40] , snake_case_ : Tuple=[1, 1, 2, 1] , snake_case_ : Tuple=True , snake_case_ : str=True , snake_case_ : int="relu" , snake_case_ : List[Any]=3 , snake_case_ : str=None , ): snake_case__ : List[Any] = parent snake_case__ : List[Any] = batch_size snake_case__ : int = image_size snake_case__ : List[Any] = num_channels snake_case__ : Optional[Any] = embeddings_size snake_case__ : Optional[int] = hidden_sizes snake_case__ : Tuple = depths snake_case__ : Any = is_training snake_case__ : Optional[int] = use_labels snake_case__ : Optional[int] = hidden_act snake_case__ : Optional[int] = num_labels snake_case__ : int = scope snake_case__ : Tuple = len(snake_case_ ) def lowerCamelCase ( self : Any ): snake_case__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : Union[str, Any] = None if self.use_labels: snake_case__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, pixel_values, labels def lowerCamelCase ( self : int ): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def lowerCamelCase ( self : Tuple , snake_case_ : Tuple , snake_case_ : List[Any] , snake_case_ : Optional[int] ): snake_case__ : Optional[Any] = TFResNetModel(config=snake_case_ ) snake_case__ : int = model(snake_case_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCamelCase ( self : List[str] , snake_case_ : List[str] , snake_case_ : str , snake_case_ : Union[str, Any] ): snake_case__ : str = self.num_labels snake_case__ : Optional[int] = TFResNetForImageClassification(snake_case_ ) snake_case__ : Tuple = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase ( self : Tuple ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : str = config_and_inputs snake_case__ : int = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class UpperCAmelCase_ ( _a , _a , unittest.TestCase ): """simple docstring""" lowercase = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () lowercase = ( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) lowercase = False lowercase = False lowercase = False lowercase = False lowercase = False def lowerCamelCase ( self : Optional[int] ): snake_case__ : Tuple = TFResNetModelTester(self ) snake_case__ : List[str] = ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ ) def lowerCamelCase ( self : Dict ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase ( self : str ): return @unittest.skip(reason="""ResNet does not use inputs_embeds""" ) def lowerCamelCase ( self : int ): pass @unittest.skip(reason="""ResNet does not support input and output embeddings""" ) def lowerCamelCase ( self : List[Any] ): pass def lowerCamelCase ( self : List[Any] ): snake_case__ , snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Dict = model_class(snake_case_ ) snake_case__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Union[str, Any] = [*signature.parameters.keys()] snake_case__ : Optional[int] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case_ ) def lowerCamelCase ( self : Union[str, Any] ): snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def lowerCamelCase ( self : List[str] ): def check_hidden_states_output(snake_case_ : Any , snake_case_ : Any , snake_case_ : List[str] ): snake_case__ : List[Any] = model_class(snake_case_ ) snake_case__ : Dict = model(**self._prepare_for_class(snake_case_ , snake_case_ ) ) snake_case__ : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states snake_case__ : List[Any] = self.model_tester.num_stages self.assertEqual(len(snake_case_ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: snake_case__ : Dict = layer_type snake_case__ : Optional[int] = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[Any] = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) def lowerCamelCase ( self : Optional[Any] ): snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) @slow def lowerCamelCase ( self : Optional[Any] ): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : str = TFResNetModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def __snake_case( ) -> Optional[int]: snake_case__ : Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCamelCase ( self : List[Any] ): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCamelCase ( self : Optional[int] ): snake_case__ : List[str] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case__ : List[Any] = self.default_image_processor snake_case__ : List[Any] = prepare_img() snake_case__ : List[str] = image_processor(images=snake_case_ , return_tensors="""tf""" ) # forward pass snake_case__ : Optional[Any] = model(**snake_case_ ) # verify the logits snake_case__ : Union[str, Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , snake_case_ ) snake_case__ : List[str] = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , snake_case_ , atol=1E-4 ) )
35
1
"""simple docstring""" import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCamelCase = logging.get_logger(__name__) class _lowerCamelCase ( lowerCamelCase__ ): """simple docstring""" def __init__( self , **_SCREAMING_SNAKE_CASE )->Tuple: '''simple docstring''' requires_backends(self , ['''bs4'''] ) super().__init__(**_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )->Union[str, Any]: '''simple docstring''' A_ : Optional[int] = [] A_ : Tuple = [] A_ : Dict = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag A_ : Tuple = parent.find_all(child.name , recursive=_SCREAMING_SNAKE_CASE ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(_SCREAMING_SNAKE_CASE ) else next(i for i, s in enumerate(_SCREAMING_SNAKE_CASE , 1 ) if s is child ) ) A_ : Optional[Any] = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _snake_case ( self , _SCREAMING_SNAKE_CASE )->int: '''simple docstring''' A_ : Any = BeautifulSoup(_SCREAMING_SNAKE_CASE , '''html.parser''' ) A_ : Union[str, Any] = [] A_ : List[str] = [] A_ : Any = [] for element in html_code.descendants: if type(_SCREAMING_SNAKE_CASE ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue A_ : List[str] = html.unescape(_SCREAMING_SNAKE_CASE ).strip() if not text_in_this_tag: continue all_doc_strings.append(_SCREAMING_SNAKE_CASE ) A_ , A_ : Dict = self.xpath_soup(_SCREAMING_SNAKE_CASE ) stringaxtag_seq.append(_SCREAMING_SNAKE_CASE ) stringaxsubs_seq.append(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError('''Number of doc strings and xtags does not correspond''' ) if len(_SCREAMING_SNAKE_CASE ) != len(_SCREAMING_SNAKE_CASE ): raise ValueError('''Number of doc strings and xsubs does not correspond''' ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )->Any: '''simple docstring''' A_ : Optional[Any] = '''''' for tagname, subs in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): xpath += F'''/{tagname}''' if subs != 0: xpath += F'''[{subs}]''' return xpath def __call__( self , _SCREAMING_SNAKE_CASE )->Any: '''simple docstring''' A_ : List[Any] = False # Check that strings has a valid type if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): A_ : Any = True elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): if len(_SCREAMING_SNAKE_CASE ) == 0 or isinstance(html_strings[0] , _SCREAMING_SNAKE_CASE ): A_ : Any = True if not valid_strings: raise ValueError( '''HTML strings must of type `str`, `List[str]` (batch of examples), ''' F'''but is of type {type(_SCREAMING_SNAKE_CASE )}.''' ) A_ : Tuple = bool(isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) and (isinstance(html_strings[0] , _SCREAMING_SNAKE_CASE )) ) if not is_batched: A_ : str = [html_strings] # Get nodes + xpaths A_ : Optional[Any] = [] A_ : int = [] for html_string in html_strings: A_ , A_ , A_ : List[str] = self.get_three_from_single(_SCREAMING_SNAKE_CASE ) nodes.append(_SCREAMING_SNAKE_CASE ) A_ : str = [] for node, tag_list, sub_list in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): A_ : List[Any] = self.construct_xpath(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) xpath_strings.append(_SCREAMING_SNAKE_CASE ) xpaths.append(_SCREAMING_SNAKE_CASE ) # return as Dict A_ : int = {'''nodes''': nodes, '''xpaths''': xpaths} A_ : int = BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE ) return encoded_inputs
356
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} UpperCamelCase = { """vocab_file""": { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model""", }, """tokenizer_file""": { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json""", }, } UpperCamelCase = { """xlnet-base-cased""": None, """xlnet-large-cased""": None, } UpperCamelCase = """▁""" # Segments (not really needed) UpperCamelCase = 0 UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 3 UpperCamelCase = 4 class _lowerCamelCase ( UpperCamelCase ): """simple docstring""" snake_case = VOCAB_FILES_NAMES snake_case = PRETRAINED_VOCAB_FILES_MAP snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case = "left" snake_case = XLNetTokenizer def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<sep>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<cls>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE=["<eop>", "<eod>"] , **_SCREAMING_SNAKE_CASE , )->Dict: '''simple docstring''' A_ : Tuple = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token super().__init__( vocab_file=_SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) A_ : Optional[Any] = 3 A_ : List[Any] = do_lower_case A_ : Optional[Any] = remove_space A_ : Tuple = keep_accents A_ : str = vocab_file A_ : List[str] = False if not self.vocab_file else True def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )->List[int]: '''simple docstring''' A_ : Optional[Any] = [self.sep_token_id] A_ : str = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )->List[int]: '''simple docstring''' A_ : str = [self.sep_token_id] A_ : List[str] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )->Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return A_ : Union[str, Any] = 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 ): copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE ) return (out_vocab_file,)
65
0
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') lowercase = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(lowerCAmelCase__ ): os.makedirs(lowerCAmelCase__ ) lowercase = model.state_dict() def to_tf_var_name(lowerCAmelCase__ ): for patt, repl in iter(lowerCAmelCase__ ): lowercase = name.replace(lowerCAmelCase__ , lowerCAmelCase__ ) return f'bert/{name}' def create_tf_var(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): lowercase = tf.dtypes.as_dtype(tensor.dtype ) lowercase = tf.get_variable(dtype=lowerCAmelCase__ , shape=tensor.shape , name=lowerCAmelCase__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(lowerCAmelCase__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: lowercase = to_tf_var_name(lowerCAmelCase__ ) lowercase = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): lowercase = torch_tensor.T lowercase = create_tf_var(tensor=lowerCAmelCase__ , name=lowerCAmelCase__ , session=lowerCAmelCase__ ) tf.keras.backend.set_value(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase = session.run(lowerCAmelCase__ ) print(f'Successfully created {tf_name}: {np.allclose(lowerCAmelCase__ , lowerCAmelCase__ )}' ) lowercase = tf.train.Saver(tf.trainable_variables() ) saver.save(lowerCAmelCase__ , os.path.join(lowerCAmelCase__ , model_name.replace('''-''' , '''_''' ) + '''.ckpt''' ) ) def UpperCamelCase ( lowerCAmelCase__=None ): '''simple docstring''' lowercase = argparse.ArgumentParser() parser.add_argument('''--model_name''' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''' , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Directory in which to save tensorflow model''' ) lowercase = parser.parse_args(lowerCAmelCase__ ) lowercase = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=lowerCAmelCase__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
101
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowercase__ :str = logging.get_logger(__name__) def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' lowercase = '''huggingface/label-files''' lowercase = '''imagenet-1k-id2label.json''' lowercase = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) lowercase = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} lowercase = {v: k for k, v in idalabel.items()} lowercase = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" lowercase = BitConfig( conv_layer=lowerCAmelCase__ , num_labels=1000 , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , ) return config def UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' if "stem.conv" in name: lowercase = name.replace('''stem.conv''' , '''bit.embedder.convolution''' ) if "blocks" in name: lowercase = name.replace('''blocks''' , '''layers''' ) if "head.fc" in name: lowercase = name.replace('''head.fc''' , '''classifier.1''' ) if name.startswith('''norm''' ): lowercase = '''bit.''' + name if "bit" not in name and "classifier" not in name: lowercase = '''bit.encoder.''' + name return name def UpperCamelCase ( ): '''simple docstring''' lowercase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ): '''simple docstring''' lowercase = get_config(lowerCAmelCase__ ) # load original model from timm lowercase = create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() # load state_dict of original model lowercase = timm_model.state_dict() for key in state_dict.copy().keys(): lowercase = state_dict.pop(lowerCAmelCase__ ) lowercase = val.squeeze() if '''head''' in key else val # load HuggingFace model lowercase = BitForImageClassification(lowerCAmelCase__ ) model.eval() model.load_state_dict(lowerCAmelCase__ ) # create image processor lowercase = create_transform(**resolve_data_config({} , model=lowerCAmelCase__ ) ) lowercase = transform.transforms lowercase = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } lowercase = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowerCAmelCase__ , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=lowerCAmelCase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowercase = prepare_img() lowercase = transform(lowerCAmelCase__ ).unsqueeze(0 ) lowercase = processor(lowerCAmelCase__ , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ) # verify logits with torch.no_grad(): lowercase = model(lowerCAmelCase__ ) lowercase = outputs.logits print('''Logits:''' , logits[0, :3] ) print('''Predicted class:''' , model.config.idalabel[logits.argmax(-1 ).item()] ) lowercase = timm_model(lowerCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase__ , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(f'Saving model {model_name} and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(f'Pushing model {model_name} and processor to the hub' ) model.push_to_hub(f'ybelkada/{model_name}' ) processor.push_to_hub(f'ybelkada/{model_name}' ) if __name__ == "__main__": lowercase__ :List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="resnetv2_50x1_bitm", type=str, help="Name of the BiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model to the hub.", ) lowercase__ :List[str] = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
101
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Tuple = logging.get_logger(__name__) _lowerCamelCase : Tuple = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class lowercase ( a ): lowercase__ : List[str] = """roc_bert""" def __init__( self : Dict , _UpperCamelCase : Dict=30_522 , _UpperCamelCase : Tuple=768 , _UpperCamelCase : int=12 , _UpperCamelCase : str=12 , _UpperCamelCase : Any=3_072 , _UpperCamelCase : Tuple="gelu" , _UpperCamelCase : int=0.1 , _UpperCamelCase : List[str]=0.1 , _UpperCamelCase : Tuple=512 , _UpperCamelCase : Tuple=2 , _UpperCamelCase : Dict=0.0_2 , _UpperCamelCase : Dict=1e-12 , _UpperCamelCase : Optional[int]=True , _UpperCamelCase : int=0 , _UpperCamelCase : Tuple="absolute" , _UpperCamelCase : Any=None , _UpperCamelCase : List[str]=True , _UpperCamelCase : Any=True , _UpperCamelCase : Any=768 , _UpperCamelCase : List[Any]=910 , _UpperCamelCase : List[str]=512 , _UpperCamelCase : Union[str, Any]=24_858 , _UpperCamelCase : List[str]=True , **_UpperCamelCase : int , ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = type_vocab_size SCREAMING_SNAKE_CASE = layer_norm_eps SCREAMING_SNAKE_CASE = use_cache SCREAMING_SNAKE_CASE = enable_pronunciation SCREAMING_SNAKE_CASE = enable_shape SCREAMING_SNAKE_CASE = pronunciation_embed_dim SCREAMING_SNAKE_CASE = pronunciation_vocab_size SCREAMING_SNAKE_CASE = shape_embed_dim SCREAMING_SNAKE_CASE = shape_vocab_size SCREAMING_SNAKE_CASE = concat_input SCREAMING_SNAKE_CASE = position_embedding_type SCREAMING_SNAKE_CASE = classifier_dropout super().__init__(pad_token_id=_UpperCamelCase , **_UpperCamelCase )
365
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase : int = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } _lowerCamelCase : Tuple = {'''allegro/herbert-base-cased''': 5_14} _lowerCamelCase : Optional[int] = {} class lowercase ( a ): lowercase__ : List[str] = VOCAB_FILES_NAMES lowercase__ : str = PRETRAINED_VOCAB_FILES_MAP lowercase__ : Tuple = PRETRAINED_INIT_CONFIGURATION lowercase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ : str = HerbertTokenizer def __init__( self : Dict , _UpperCamelCase : Any=None , _UpperCamelCase : Any=None , _UpperCamelCase : Optional[int]=None , _UpperCamelCase : Optional[int]="<s>" , _UpperCamelCase : Union[str, Any]="<unk>" , _UpperCamelCase : List[str]="<pad>" , _UpperCamelCase : List[str]="<mask>" , _UpperCamelCase : Tuple="</s>" , **_UpperCamelCase : Any , ) -> str: '''simple docstring''' super().__init__( _UpperCamelCase , _UpperCamelCase , tokenizer_file=_UpperCamelCase , cls_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , sep_token=_UpperCamelCase , **_UpperCamelCase , ) def __snake_case( self : Optional[Any] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.cls_token_id] SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __snake_case( self : Any , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None , _UpperCamelCase : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_UpperCamelCase , token_ids_a=_UpperCamelCase , already_has_special_tokens=_UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_UpperCamelCase )) + [1] return [1] + ([0] * len(_UpperCamelCase )) + [1] + ([0] * len(_UpperCamelCase )) + [1] def __snake_case( self : Union[str, Any] , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __snake_case( self : str , _UpperCamelCase : str , _UpperCamelCase : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = self._tokenizer.model.save(_UpperCamelCase , name=_UpperCamelCase ) return tuple(_UpperCamelCase )
206
0
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __UpperCAmelCase : def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=99 , lowerCAmelCase_=16 , lowerCAmelCase_=36 , lowerCAmelCase_=6 , lowerCAmelCase_=6 , lowerCAmelCase_=6 , lowerCAmelCase_=37 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=3 , lowerCAmelCase_=4 , lowerCAmelCase_=None , ): """simple docstring""" _snake_case = parent _snake_case = batch_size _snake_case = seq_length _snake_case = is_training _snake_case = use_input_mask _snake_case = use_token_type_ids _snake_case = use_labels _snake_case = vocab_size _snake_case = embedding_size _snake_case = hidden_size _snake_case = num_hidden_layers _snake_case = num_hidden_groups _snake_case = num_attention_heads _snake_case = intermediate_size _snake_case = hidden_act _snake_case = hidden_dropout_prob _snake_case = attention_probs_dropout_prob _snake_case = max_position_embeddings _snake_case = type_vocab_size _snake_case = type_sequence_label_size _snake_case = initializer_range _snake_case = num_labels _snake_case = num_choices _snake_case = scope def lowerCamelCase ( self ): """simple docstring""" _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _snake_case = None if self.use_input_mask: _snake_case = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case = None if self.use_token_type_ids: _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _snake_case = None _snake_case = None _snake_case = None if self.use_labels: _snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _snake_case = ids_tensor([self.batch_size] , self.num_choices ) _snake_case = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase ( self ): """simple docstring""" return AlbertConfig( 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 , num_hidden_groups=self.num_hidden_groups , ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = AlbertModel(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ ) _snake_case = model(lowerCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = AlbertForPreTraining(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , sentence_order_label=lowerCAmelCase_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = AlbertForMaskedLM(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = AlbertForQuestionAnswering(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , start_positions=lowerCAmelCase_ , end_positions=lowerCAmelCase_ , ) 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 , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_labels _snake_case = AlbertForSequenceClassification(lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_labels _snake_case = AlbertForTokenClassification(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" _snake_case = self.num_choices _snake_case = AlbertForMultipleChoice(config=lowerCAmelCase_ ) model.to(lowerCAmelCase_ ) model.eval() _snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _snake_case = model( lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , token_type_ids=lowerCAmelCase_ , labels=lowerCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.prepare_config_and_inputs() ( ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ( _snake_case ) , ) = config_and_inputs _snake_case = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class __UpperCAmelCase ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): __lowercase = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __lowercase = ( { """feature-extraction""": AlbertModel, """fill-mask""": AlbertForMaskedLM, """question-answering""": AlbertForQuestionAnswering, """text-classification""": AlbertForSequenceClassification, """token-classification""": AlbertForTokenClassification, """zero-shot""": AlbertForSequenceClassification, } if is_torch_available() else {} ) __lowercase = True def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ): """simple docstring""" _snake_case = super()._prepare_for_class(lowerCAmelCase_ , lowerCAmelCase_ , return_labels=lowerCAmelCase_ ) if return_labels: if model_class in get_values(lowerCAmelCase_ ): _snake_case = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowerCAmelCase_ ) _snake_case = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase_ ) return inputs_dict def lowerCamelCase ( self ): """simple docstring""" _snake_case = AlbertModelTester(self ) _snake_case = ConfigTester(self , config_class=lowerCAmelCase_ , hidden_size=37 ) def lowerCamelCase ( self ): """simple docstring""" self.config_tester.run_common_tests() def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _snake_case = type self.model_tester.create_and_check_model(*lowerCAmelCase_ ) @slow def lowerCamelCase ( self ): """simple docstring""" for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case = AlbertModel.from_pretrained(lowerCAmelCase_ ) self.assertIsNotNone(lowerCAmelCase_ ) @require_torch class __UpperCAmelCase ( unittest.TestCase ): @slow def lowerCamelCase ( self ): """simple docstring""" _snake_case = AlbertModel.from_pretrained('albert-base-v2' ) _snake_case = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) _snake_case = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): _snake_case = model(lowerCAmelCase_ , attention_mask=lowerCAmelCase_ )[0] _snake_case = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , lowerCAmelCase_ ) _snake_case = torch.tensor( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase_ , atol=1E-4 ) )
42
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : Union[str, Any] = { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/config.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/config.json", } class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """xlnet""" __lowercase = ["""mems"""] __lowercase = { """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , lowerCAmelCase_=3_20_00 , lowerCAmelCase_=10_24 , lowerCAmelCase_=24 , lowerCAmelCase_=16 , lowerCAmelCase_=40_96 , lowerCAmelCase_="gelu" , lowerCAmelCase_=True , lowerCAmelCase_="bi" , lowerCAmelCase_=0.02 , lowerCAmelCase_=1E-12 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=None , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=-1 , lowerCAmelCase_=False , lowerCAmelCase_="last" , lowerCAmelCase_=True , lowerCAmelCase_="tanh" , lowerCAmelCase_=0.1 , lowerCAmelCase_=5 , lowerCAmelCase_=5 , lowerCAmelCase_=5 , lowerCAmelCase_=1 , lowerCAmelCase_=2 , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = vocab_size _snake_case = d_model _snake_case = n_layer _snake_case = n_head if d_model % n_head != 0: raise ValueError(F'\'d_model % n_head\' ({d_model % n_head}) should be equal to 0' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})' ) _snake_case = d_model // n_head _snake_case = ff_activation _snake_case = d_inner _snake_case = untie_r _snake_case = attn_type _snake_case = initializer_range _snake_case = layer_norm_eps _snake_case = dropout _snake_case = mem_len _snake_case = reuse_len _snake_case = bi_data _snake_case = clamp_len _snake_case = same_length _snake_case = summary_type _snake_case = summary_use_proj _snake_case = summary_activation _snake_case = summary_last_dropout _snake_case = start_n_top _snake_case = end_n_top _snake_case = bos_token_id _snake_case = pad_token_id _snake_case = eos_token_id if "use_cache" in kwargs: warnings.warn( 'The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`' ' instead.' , lowerCAmelCase_ , ) _snake_case = kwargs['use_cache'] _snake_case = use_mems_eval _snake_case = use_mems_train super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def lowerCamelCase ( self ): """simple docstring""" logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" raise NotImplementedError( F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
42
1
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase ( snake_case , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = LayoutLMTokenizer SCREAMING_SNAKE_CASE_ : Union[str, Any] = LayoutLMTokenizerFast SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : str = True def lowerCamelCase__ ( self ): super().setUp() _lowercase : Optional[int] = [ """[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] _lowercase : 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] ) ) def lowerCamelCase__ ( self ,**UpperCAmelCase_ ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ): _lowercase : Dict = """UNwant\u00E9d,running""" _lowercase : Any = """unwanted, running""" return input_text, output_text def lowerCamelCase__ ( self ): _lowercase : Dict = self.tokenizer_class(self.vocab_file ) _lowercase : Union[str, Any] = tokenizer.tokenize("""UNwant\u00E9d,running""" ) self.assertListEqual(UpperCAmelCase_ ,["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) ,[7, 4, 5, 10, 8, 9] ) def lowerCamelCase__ ( self ): pass
336
"""simple docstring""" import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase ( snake_case , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = LEDTokenizer SCREAMING_SNAKE_CASE_ : List[str] = LEDTokenizerFast SCREAMING_SNAKE_CASE_ : List[str] = True def lowerCamelCase__ ( self ): super().setUp() _lowercase : Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] _lowercase : List[Any] = dict(zip(UpperCAmelCase_ ,range(len(UpperCAmelCase_ ) ) ) ) _lowercase : Optional[int] = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] _lowercase : Dict = {"""unk_token""": """<unk>"""} _lowercase : Optional[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""vocab_file"""] ) _lowercase : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + """\n""" ) with open(self.merges_file ,"""w""" ,encoding="""utf-8""" ) as fp: fp.write("""\n""".join(UpperCAmelCase_ ) ) def lowerCamelCase__ ( self ,**UpperCAmelCase_ ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,**UpperCAmelCase_ ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname ,**UpperCAmelCase_ ) def lowerCamelCase__ ( self ,UpperCAmelCase_ ): return "lower newer", "lower newer" @cached_property def lowerCamelCase__ ( self ): return LEDTokenizer.from_pretrained("""allenai/led-base-16384""" ) @cached_property def lowerCamelCase__ ( self ): return LEDTokenizerFast.from_pretrained("""allenai/led-base-16384""" ) @require_torch def lowerCamelCase__ ( self ): _lowercase : Tuple = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] _lowercase : Any = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : Tuple = tokenizer(UpperCAmelCase_ ,max_length=len(UpperCAmelCase_ ) ,padding=UpperCAmelCase_ ,return_tensors="""pt""" ) self.assertIsInstance(UpperCAmelCase_ ,UpperCAmelCase_ ) self.assertEqual((2, 9) ,batch.input_ids.shape ) self.assertEqual((2, 9) ,batch.attention_mask.shape ) _lowercase : Optional[Any] = batch.input_ids.tolist()[0] self.assertListEqual(UpperCAmelCase_ ,UpperCAmelCase_ ) @require_torch def lowerCamelCase__ ( self ): _lowercase : Tuple = ["""A long paragraph for summarization.""", """Another paragraph for summarization."""] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : Dict = tokenizer(UpperCAmelCase_ ,padding=UpperCAmelCase_ ,return_tensors="""pt""" ) self.assertIn("""input_ids""" ,UpperCAmelCase_ ) self.assertIn("""attention_mask""" ,UpperCAmelCase_ ) self.assertNotIn("""labels""" ,UpperCAmelCase_ ) self.assertNotIn("""decoder_attention_mask""" ,UpperCAmelCase_ ) @require_torch def lowerCamelCase__ ( self ): _lowercase : Dict = [ """Summary of the text.""", """Another summary.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : Tuple = tokenizer(text_target=UpperCAmelCase_ ,max_length=32 ,padding="""max_length""" ,return_tensors="""pt""" ) self.assertEqual(32 ,targets["""input_ids"""].shape[1] ) @require_torch def lowerCamelCase__ ( self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : List[Any] = tokenizer( ["""I am a small frog""" * 10_24, """I am a small frog"""] ,padding=UpperCAmelCase_ ,truncation=UpperCAmelCase_ ,return_tensors="""pt""" ) self.assertIsInstance(UpperCAmelCase_ ,UpperCAmelCase_ ) self.assertEqual(batch.input_ids.shape ,(2, 51_22) ) @require_torch def lowerCamelCase__ ( self ): _lowercase : List[Any] = ["""A long paragraph for summarization."""] _lowercase : Dict = [ """Summary of the text.""", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : Dict = tokenizer(UpperCAmelCase_ ,return_tensors="""pt""" ) _lowercase : List[str] = tokenizer(text_target=UpperCAmelCase_ ,return_tensors="""pt""" ) _lowercase : Union[str, Any] = inputs["""input_ids"""] _lowercase : List[str] = targets["""input_ids"""] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCamelCase__ ( self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowercase : str = ["""Summary of the text.""", """Another summary."""] _lowercase : Optional[int] = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] _lowercase : Any = tokenizer(UpperCAmelCase_ ,padding=UpperCAmelCase_ ) _lowercase : str = [[0] * len(UpperCAmelCase_ ) for x in encoded_output["""input_ids"""]] _lowercase : Optional[int] = tokenizer.pad(UpperCAmelCase_ ) self.assertSequenceEqual(outputs["""global_attention_mask"""] ,UpperCAmelCase_ ) def lowerCamelCase__ ( self ): pass def lowerCamelCase__ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _lowercase : int = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_ ,**UpperCAmelCase_ ) _lowercase : Optional[int] = self.tokenizer_class.from_pretrained(UpperCAmelCase_ ,**UpperCAmelCase_ ) _lowercase : Dict = """A, <mask> AllenNLP sentence.""" _lowercase : List[Any] = tokenizer_r.encode_plus(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ ,return_token_type_ids=UpperCAmelCase_ ) _lowercase : Any = tokenizer_p.encode_plus(UpperCAmelCase_ ,add_special_tokens=UpperCAmelCase_ ,return_token_type_ids=UpperCAmelCase_ ) self.assertEqual(sum(tokens_r["""token_type_ids"""] ) ,sum(tokens_p["""token_type_ids"""] ) ) self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) ,sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) ,) _lowercase : str = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) _lowercase : str = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) self.assertSequenceEqual(tokens_p["""input_ids"""] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] ,[0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( UpperCAmelCase_ ,["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( UpperCAmelCase_ ,["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] )
336
1
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin 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 BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __snake_case : def __init__( self ,snake_case ,snake_case=3 ,snake_case=32 ,snake_case=3 ,snake_case=10 ,snake_case=[8, 16, 32, 64] ,snake_case=[1, 1, 2, 1] ,snake_case=True ,snake_case=True ,snake_case="relu" ,snake_case=3 ,snake_case=None ,snake_case=["stage2", "stage3", "stage4"] ,snake_case=[2, 3, 4] ,snake_case=1 ,): '''simple docstring''' lowercase : Union[str, Any] = parent lowercase : List[Any] = batch_size lowercase : Optional[Any] = image_size lowercase : str = num_channels lowercase : Union[str, Any] = embeddings_size lowercase : Any = hidden_sizes lowercase : Union[str, Any] = depths lowercase : int = is_training lowercase : List[Any] = use_labels lowercase : List[str] = hidden_act lowercase : Tuple = num_labels lowercase : Optional[Any] = scope lowercase : str = len(snake_case ) lowercase : int = out_features lowercase : Any = out_indices lowercase : Any = num_groups def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase : int = None if self.use_labels: lowercase : Dict = ids_tensor([self.batch_size] ,self.num_labels ) lowercase : Tuple = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return BitConfig( num_channels=self.num_channels ,embeddings_size=self.embeddings_size ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,hidden_act=self.hidden_act ,num_labels=self.num_labels ,out_features=self.out_features ,out_indices=self.out_indices ,num_groups=self.num_groups ,) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Tuple = BitModel(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[Any] = model(snake_case ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Optional[Any] = self.num_labels lowercase : List[str] = BitForImageClassification(snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Dict = BitBackbone(config=snake_case ) model.to(snake_case ) model.eval() lowercase : List[str] = model(snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowercase : Optional[Any] = None lowercase : List[str] = BitBackbone(config=snake_case ) model.to(snake_case ) model.eval() lowercase : Any = model(snake_case ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = self.prepare_config_and_inputs() lowercase , lowercase , lowercase : str = config_and_inputs lowercase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): _a : Optional[int]= (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () _a : Any= ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) _a : List[Any]= False _a : List[Any]= False _a : Optional[int]= False _a : Tuple= False _a : Optional[Any]= False def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Tuple = BitModelTester(self ) lowercase : Tuple = ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return @unittest.skip(reason="""Bit does not output attentions""" ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' pass @unittest.skip(reason="""Bit does not use inputs_embeds""" ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' pass @unittest.skip(reason="""Bit does not support input and output embeddings""" ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase , lowercase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : List[str] = model_class(snake_case ) lowercase : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase : int = [*signature.parameters.keys()] lowercase : List[Any] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] ,snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase , lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase : int = model_class(config=snake_case ) for name, module in model.named_modules(): if isinstance(snake_case ,(nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) ,msg=f"Parameter {name} of model {model_class} seems not properly initialized" ,) self.assertTrue( torch.all(module.bias == 0 ) ,msg=f"Parameter {name} of model {model_class} seems not properly initialized" ,) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' def check_hidden_states_output(snake_case ,snake_case ,snake_case ): lowercase : Any = model_class(snake_case ) model.to(snake_case ) model.eval() with torch.no_grad(): lowercase : str = model(**self._prepare_for_class(snake_case ,snake_case ) ) lowercase : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase : Optional[int] = self.model_tester.num_stages self.assertEqual(len(snake_case ) ,expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) lowercase , lowercase : int = self.model_tester.prepare_config_and_inputs_for_common() lowercase : Tuple = ["""preactivation""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: lowercase : Dict = layer_type lowercase : int = True check_hidden_states_output(snake_case ,snake_case ,snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase : Union[str, Any] = True check_hidden_states_output(snake_case ,snake_case ,snake_case ) @unittest.skip(reason="""Bit does not use feedforward chunking""" ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase : Optional[Any] = BitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def _snake_case( ) -> Optional[int]: lowercase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __snake_case ( unittest.TestCase ): @cached_property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[str] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(snake_case ) lowercase : Union[str, Any] = self.default_image_processor lowercase : int = prepare_img() lowercase : str = image_processor(images=snake_case ,return_tensors="""pt""" ).to(snake_case ) # forward pass with torch.no_grad(): lowercase : Optional[int] = model(**snake_case ) # verify the logits lowercase : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,snake_case ) lowercase : Optional[Any] = torch.tensor([[-0.6_526, -0.5_263, -1.4_398]] ).to(snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,snake_case ,atol=1e-4 ) ) @require_torch class __snake_case ( lowerCAmelCase , unittest.TestCase ): _a : Tuple= (BitBackbone,) if is_torch_available() else () _a : str= BitConfig _a : str= False def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = BitModelTester(self )
20
"""simple docstring""" import math 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 SchedulerMixin, SchedulerOutput class _A ( lowerCAmelCase , lowerCAmelCase ): snake_case__ : Tuple = 1 @register_to_config def __init__( self , __lowerCAmelCase = 1000 , __lowerCAmelCase = None ): """simple docstring""" self.set_timesteps(__lowerCAmelCase ) # standard deviation of the initial noise distribution lowercase = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. lowercase = 4 # running values lowercase = [] def A__ ( self , __lowerCAmelCase , __lowerCAmelCase = None ): """simple docstring""" lowercase = num_inference_steps lowercase = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] lowercase = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: lowercase = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: lowercase = torch.sin(steps * math.pi / 2 ) ** 2 lowercase = (1.0 - self.betas**2) ** 0.5 lowercase = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] lowercase = timesteps.to(__lowerCAmelCase ) lowercase = [] def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = True , ): """simple docstring""" if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) lowercase = (self.timesteps == timestep).nonzero().item() lowercase = timestep_index + 1 lowercase = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(__lowerCAmelCase ) if len(self.ets ) == 1: lowercase = self.ets[-1] elif len(self.ets ) == 2: lowercase = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: lowercase = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: lowercase = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) lowercase = self._get_prev_sample(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__lowerCAmelCase ) def A__ ( self , __lowerCAmelCase , *__lowerCAmelCase , **__lowerCAmelCase ): """simple docstring""" return sample def A__ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" lowercase = self.alphas[timestep_index] lowercase = self.betas[timestep_index] lowercase = self.alphas[prev_timestep_index] lowercase = self.betas[prev_timestep_index] lowercase = (sample - sigma * ets) / max(__lowerCAmelCase , 1E-8 ) lowercase = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self ): """simple docstring""" return self.config.num_train_timesteps
197
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case__ : def __init__( self : str , __a : Optional[int] , __a : str=3 , __a : Optional[int]=32 , __a : Optional[Any]=3 , __a : Optional[int]=10 , __a : List[Any]=[10, 20, 30, 40] , __a : Dict=[1, 1, 2, 1] , __a : Tuple=True , __a : Union[str, Any]=True , __a : Dict="relu" , __a : Any=3 , __a : str=None , ) -> int: '''simple docstring''' __snake_case : str = parent __snake_case : Union[str, Any] = batch_size __snake_case : List[str] = image_size __snake_case : Tuple = num_channels __snake_case : Any = embeddings_size __snake_case : List[Any] = hidden_sizes __snake_case : str = depths __snake_case : int = is_training __snake_case : List[str] = use_labels __snake_case : Tuple = hidden_act __snake_case : Any = num_labels __snake_case : List[str] = scope __snake_case : Dict = len(__a ) def A_ ( self : int ) -> Optional[int]: '''simple docstring''' __snake_case : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : str = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Tuple = self.get_config() return config, pixel_values, labels def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def A_ ( self : Optional[Any] , __a : Any , __a : Union[str, Any] , __a : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = TFRegNetModel(config=__a ) __snake_case : Union[str, Any] = model(__a , training=__a ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def A_ ( self : List[str] , __a : Dict , __a : Union[str, Any] , __a : Optional[Any] ) -> Tuple: '''simple docstring''' __snake_case : List[str] = self.num_labels __snake_case : List[Any] = TFRegNetForImageClassification(__a ) __snake_case : Optional[int] = model(__a , labels=__a , training=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case : Any = config_and_inputs __snake_case : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () A__ = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) A__ = False A__ = False A__ = False A__ = False A__ = False def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' __snake_case : str = TFRegNetModelTester(self ) __snake_case : Optional[Any] = ConfigTester(self , config_class=__a , has_text_modality=__a ) def A_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def A_ ( self : List[str] ) -> Any: '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def A_ ( self : str ) -> str: '''simple docstring''' pass def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Tuple = model_class(__a ) __snake_case : List[str] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : Optional[int] = [*signature.parameters.keys()] __snake_case : Any = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' def check_hidden_states_output(__a : List[str] , __a : List[Any] , __a : Optional[Any] ): __snake_case : List[Any] = model_class(__a ) __snake_case : int = model(**self._prepare_for_class(__a , __a ) , training=__a ) __snake_case : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __snake_case : List[Any] = self.model_tester.num_stages self.assertEqual(len(__a ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() __snake_case : Optional[int] = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: __snake_case : List[str] = layer_type __snake_case : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : str = True check_hidden_states_output(__a , __a , __a ) def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__a : Optional[int] , __a : Tuple , __a : Union[str, Any] , __a : List[Any]={} ): __snake_case : Optional[Any] = model(__a , return_dict=__a , **__a ) __snake_case : Tuple = model(__a , return_dict=__a , **__a ).to_tuple() def recursive_check(__a : Tuple , __a : Optional[int] ): if isinstance(__a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__a , __a ): recursive_check(__a , __a ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__a , __a ) ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(__a , __a ) for model_class in self.all_model_classes: __snake_case : List[str] = model_class(__a ) __snake_case : List[Any] = self._prepare_for_class(__a , __a ) __snake_case : str = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a ) __snake_case : List[str] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Tuple = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) __snake_case : Union[str, Any] = self._prepare_for_class(__a , __a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) __snake_case : Optional[Any] = self._prepare_for_class(__a , __a , return_labels=__a ) __snake_case : Any = self._prepare_for_class(__a , __a , return_labels=__a ) check_equivalence(__a , __a , __a , {'output_hidden_states': True} ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @slow def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = TFRegNetModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a_ ( ) -> Optional[int]: __snake_case : Any = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def A_ ( self : List[Any] ) -> str: '''simple docstring''' return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def A_ ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __snake_case : str = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : str = image_processor(images=__a , return_tensors='tf' ) # forward pass __snake_case : Optional[int] = model(**__a , training=__a ) # verify the logits __snake_case : List[str] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __snake_case : List[str] = tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , __a , atol=1e-4 )
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
1
'''simple docstring''' import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCAmelCase_ : def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int]=1_3 , UpperCAmelCase__ : Optional[int]=3_0 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Dict=3 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : str=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[str]=3_7 , UpperCAmelCase__ : Dict="gelu" , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Tuple=1_0 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Tuple=2 , ) -> Tuple: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = patch_size lowerCAmelCase = num_channels lowerCAmelCase = is_training lowerCAmelCase = use_labels 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 = type_sequence_label_size lowerCAmelCase = initializer_range lowerCAmelCase = scope lowerCAmelCase = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase = (image_size // patch_size) ** 2 lowerCAmelCase = num_patches + 1 def __UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase = None if self.use_labels: lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self : Tuple ) -> Optional[int]: return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Optional[Any]: lowerCAmelCase = ViTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] ) -> Union[str, Any]: lowerCAmelCase = ViTForMaskedImageModeling(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = model(UpperCAmelCase__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowerCAmelCase = 1 lowerCAmelCase = ViTForMaskedImageModeling(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __UpperCAmelCase ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str ) -> Tuple: lowerCAmelCase = self.type_sequence_label_size lowerCAmelCase = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCAmelCase = 1 lowerCAmelCase = ViTForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCAmelCase = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __UpperCAmelCase ( self : List[str] ) -> Optional[Any]: lowerCAmelCase = self.prepare_config_and_inputs() ( ( lowerCAmelCase ) , ( lowerCAmelCase ) , ( lowerCAmelCase ) , ) = config_and_inputs lowerCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( __lowercase , __lowercase , unittest.TestCase ): lowerCamelCase : Optional[Any] = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) lowerCamelCase : Union[str, Any] = ( {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification} if is_torch_available() else {} ) lowerCamelCase : int = True lowerCamelCase : str = False lowerCamelCase : List[str] = False lowerCamelCase : Optional[int] = False def __UpperCAmelCase ( self : Optional[Any] ) -> List[str]: lowerCAmelCase = ViTModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def __UpperCAmelCase ( self : str ) -> str: self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def __UpperCAmelCase ( self : List[str] ) -> List[Any]: pass def __UpperCAmelCase ( self : Union[str, Any] ) -> List[Any]: lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def __UpperCAmelCase ( self : List[str] ) -> List[Any]: lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = model_class(UpperCAmelCase__ ) lowerCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase = [*signature.parameters.keys()] lowerCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def __UpperCAmelCase ( self : int ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def __UpperCAmelCase ( self : Any ) -> Any: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def __UpperCAmelCase ( self : List[str] ) -> Optional[int]: for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = ViTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def a_ ( ): lowerCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): @cached_property def __UpperCAmelCase ( self : Optional[Any] ) -> List[Any]: return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None @slow def __UpperCAmelCase ( self : Dict ) -> Union[str, Any]: lowerCAmelCase = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ).to(UpperCAmelCase__ ) lowerCAmelCase = self.default_image_processor lowerCAmelCase = prepare_img() lowerCAmelCase = image_processor(images=UpperCAmelCase__ , return_tensors='pt' ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): lowerCAmelCase = model(**UpperCAmelCase__ ) # verify the logits lowerCAmelCase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor([-0.2_744, 0.8_215, -0.0_836] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def __UpperCAmelCase ( self : int ) -> List[Any]: # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. lowerCAmelCase = ViTModel.from_pretrained('facebook/dino-vits8' ).to(UpperCAmelCase__ ) lowerCAmelCase = ViTImageProcessor.from_pretrained('facebook/dino-vits8' , size=4_8_0 ) lowerCAmelCase = prepare_img() lowerCAmelCase = image_processor(images=UpperCAmelCase__ , return_tensors='pt' ) lowerCAmelCase = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): lowerCAmelCase = model(UpperCAmelCase__ , interpolate_pos_encoding=UpperCAmelCase__ ) # verify the logits lowerCAmelCase = torch.Size((1, 3_6_0_1, 3_8_4) ) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase__ ) lowerCAmelCase = torch.tensor( [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def __UpperCAmelCase ( self : Any ) -> Optional[int]: lowerCAmelCase = ViTModel.from_pretrained('facebook/dino-vits8' , torch_dtype=torch.floataa , device_map='auto' ) lowerCAmelCase = self.default_image_processor lowerCAmelCase = prepare_img() lowerCAmelCase = image_processor(images=UpperCAmelCase__ , return_tensors='pt' ) lowerCAmelCase = inputs.pixel_values.to(UpperCAmelCase__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): lowerCAmelCase = model(UpperCAmelCase__ )
4
from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class A ( UpperCAmelCase_ ): __UpperCAmelCase : Optional[torch.FloatTensor] = None __UpperCAmelCase : torch.FloatTensor = None __UpperCAmelCase : Optional[Tuple[torch.FloatTensor]] = None __UpperCAmelCase : Optional[Tuple[torch.FloatTensor]] = None class A ( UpperCAmelCase_ ): def __init__(self : Union[str, Any] , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : str=0 , __UpperCAmelCase : str=2 , __UpperCAmelCase : Union[str, Any]=5_1_2 , __UpperCAmelCase : List[str]="cls" , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : str=True , **__UpperCAmelCase : str , ) -> int: """simple docstring""" super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) UpperCAmelCase__ = project_dim UpperCAmelCase__ = pooler_fn UpperCAmelCase__ = learn_encoder UpperCAmelCase__ = use_attention_mask class A ( UpperCAmelCase_ ): __UpperCAmelCase : Tuple = [r'pooler', r'logit_scale'] __UpperCAmelCase : int = [r'position_ids', r'predictions.decoder.bias'] __UpperCAmelCase : Any = 'roberta' __UpperCAmelCase : List[str] = RobertaSeriesConfig def __init__(self : Tuple , __UpperCAmelCase : Optional[int] ) -> int: """simple docstring""" super().__init__(__UpperCAmelCase ) UpperCAmelCase__ = XLMRobertaModel(__UpperCAmelCase ) UpperCAmelCase__ = nn.Linear(config.hidden_size , config.project_dim ) UpperCAmelCase__ = getattr(__UpperCAmelCase , "has_pre_transformation" , __UpperCAmelCase ) if self.has_pre_transformation: UpperCAmelCase__ = nn.Linear(config.hidden_size , config.project_dim ) UpperCAmelCase__ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def lowercase_ (self : Optional[Any] , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[torch.Tensor] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[bool] = None , ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict UpperCAmelCase__ = self.base_model( input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , position_ids=__UpperCAmelCase , head_mask=__UpperCAmelCase , inputs_embeds=__UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase , encoder_attention_mask=__UpperCAmelCase , output_attentions=__UpperCAmelCase , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__UpperCAmelCase , ) if self.has_pre_transformation: UpperCAmelCase__ = outputs["hidden_states"][-2] UpperCAmelCase__ = self.pre_LN(__UpperCAmelCase ) UpperCAmelCase__ = self.transformation_pre(__UpperCAmelCase ) return TransformationModelOutput( projection_state=__UpperCAmelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: UpperCAmelCase__ = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__UpperCAmelCase , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
65
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def _snake_case ( lowercase__ : Union[str, Any] ) -> int: '''simple docstring''' lowerCAmelCase_ :List[Any] = 'huggingface/label-files' lowerCAmelCase_ :Union[str, Any] = 'imagenet-1k-id2label.json' lowerCAmelCase_ :int = json.load(open(hf_hub_download(_UpperCAmelCase , _UpperCAmelCase , repo_type="""dataset""" ) , """r""" ) ) lowerCAmelCase_ :Dict = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} lowerCAmelCase_ :Union[str, Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase_ :Optional[Any] = 'std_conv' if 'bit' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" lowerCAmelCase_ :Dict = BitConfig( conv_layer=_UpperCAmelCase , num_labels=1_0_0_0 , idalabel=_UpperCAmelCase , labelaid=_UpperCAmelCase , ) return config def _snake_case ( lowercase__ : int ) -> Union[str, Any]: '''simple docstring''' if "stem.conv" in name: lowerCAmelCase_ :Dict = name.replace("""stem.conv""" , """bit.embedder.convolution""" ) if "blocks" in name: lowerCAmelCase_ :Tuple = name.replace("""blocks""" , """layers""" ) if "head.fc" in name: lowerCAmelCase_ :Any = name.replace("""head.fc""" , """classifier.1""" ) if name.startswith("""norm""" ): lowerCAmelCase_ :List[Any] = 'bit.' + name if "bit" not in name and "classifier" not in name: lowerCAmelCase_ :Any = 'bit.encoder.' + name return name def _snake_case ( ) -> int: '''simple docstring''' lowerCAmelCase_ :Tuple = 'http://images.cocodataset.org/val2017/000000039769.jpg' lowerCAmelCase_ :List[str] = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ) return im @torch.no_grad() def _snake_case ( lowercase__ : Dict , lowercase__ : Any , lowercase__ : Any=False ) -> Tuple: '''simple docstring''' lowerCAmelCase_ :Any = get_config(_UpperCAmelCase ) # load original model from timm lowerCAmelCase_ :Union[str, Any] = create_model(_UpperCAmelCase , pretrained=_UpperCAmelCase ) timm_model.eval() # load state_dict of original model lowerCAmelCase_ :Tuple = timm_model.state_dict() for key in state_dict.copy().keys(): lowerCAmelCase_ :Union[str, Any] = state_dict.pop(_UpperCAmelCase ) lowerCAmelCase_ :Any = val.squeeze() if 'head' in key else val # load HuggingFace model lowerCAmelCase_ :Any = BitForImageClassification(_UpperCAmelCase ) model.eval() model.load_state_dict(_UpperCAmelCase ) # create image processor lowerCAmelCase_ :List[Any] = create_transform(**resolve_data_config({} , model=_UpperCAmelCase ) ) lowerCAmelCase_ :Tuple = transform.transforms lowerCAmelCase_ :Any = { 'bilinear': PILImageResampling.BILINEAR, 'bicubic': PILImageResampling.BICUBIC, 'nearest': PILImageResampling.NEAREST, } lowerCAmelCase_ :Union[str, Any] = BitImageProcessor( do_resize=_UpperCAmelCase , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_UpperCAmelCase , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=_UpperCAmelCase , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowerCAmelCase_ :Optional[int] = prepare_img() lowerCAmelCase_ :Optional[int] = transform(_UpperCAmelCase ).unsqueeze(0 ) lowerCAmelCase_ :str = processor(_UpperCAmelCase , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(_UpperCAmelCase , _UpperCAmelCase ) # verify logits with torch.no_grad(): lowerCAmelCase_ :Tuple = model(_UpperCAmelCase ) lowerCAmelCase_ :List[Any] = outputs.logits print("""Logits:""" , logits[0, :3] ) print("""Predicted class:""" , model.config.idalabel[logits.argmax(-1 ).item()] ) lowerCAmelCase_ :Any = timm_model(_UpperCAmelCase ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_UpperCAmelCase , outputs.logits , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCAmelCase ) processor.save_pretrained(_UpperCAmelCase ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) __UpperCAmelCase = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
350
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __UpperCAmelCase = 16 __UpperCAmelCase = 32 def _snake_case ( lowercase__ : Accelerator , lowercase__ : int = 1_6 , lowercase__ : str = "bert-base-cased" ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ :List[str] = AutoTokenizer.from_pretrained(lowercase__ ) lowerCAmelCase_ :Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(lowercase__ : List[str] ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase_ :str = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=lowercase__ , max_length=lowercase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset lowerCAmelCase_ :str = datasets.map( lowercase__ , batched=lowercase__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , load_from_cache_file=lowercase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase_ :List[str] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(lowercase__ : Union[str, Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase__ , padding="""max_length""" , max_length=1_2_8 , return_tensors="""pt""" ) return tokenizer.pad(lowercase__ , padding="""longest""" , return_tensors="""pt""" ) # Instantiate dataloaders. lowerCAmelCase_ :Optional[int] = DataLoader( tokenized_datasets["""train"""] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) lowerCAmelCase_ :Any = DataLoader( tokenized_datasets["""validation"""] , shuffle=lowercase__ , collate_fn=lowercase__ , batch_size=lowercase__ ) return train_dataloader, eval_dataloader def _snake_case ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : int ) -> List[str]: '''simple docstring''' model.eval() lowerCAmelCase_ :Dict = 0 for step, batch in enumerate(lowercase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase_ :Optional[int] = model(**lowercase__ ) lowerCAmelCase_ :Optional[int] = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times lowerCAmelCase_ , lowerCAmelCase_ :List[Any] = accelerator.gather( (predictions, batch["""labels"""]) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase__ ) - 1: lowerCAmelCase_ :Optional[Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] lowerCAmelCase_ :Any = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase__ , references=lowercase__ , ) lowerCAmelCase_ :Tuple = metric.compute() return eval_metric["accuracy"] def _snake_case ( lowercase__ : str , lowercase__ : List[str] ) -> Any: '''simple docstring''' lowerCAmelCase_ :Optional[int] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase_ :int = config["""lr"""] lowerCAmelCase_ :Union[str, Any] = int(config["""num_epochs"""] ) lowerCAmelCase_ :Optional[int] = int(config["""seed"""] ) lowerCAmelCase_ :Union[str, Any] = int(config["""batch_size"""] ) lowerCAmelCase_ :Optional[Any] = args.model_name_or_path set_seed(lowercase__ ) lowerCAmelCase_ , lowerCAmelCase_ :Dict = get_dataloaders(lowercase__ , lowercase__ , lowercase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase_ :str = AutoModelForSequenceClassification.from_pretrained(lowercase__ , return_dict=lowercase__ ) # Instantiate optimizer lowerCAmelCase_ :List[str] = ( AdamW if accelerator.state.deepspeed_plugin is None or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) lowerCAmelCase_ :str = optimizer_cls(params=model.parameters() , lr=lowercase__ ) if accelerator.state.deepspeed_plugin is not None: lowerCAmelCase_ :Union[str, Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ """gradient_accumulation_steps""" ] else: lowerCAmelCase_ :Any = 1 lowerCAmelCase_ :str = (len(lowercase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): lowerCAmelCase_ :List[str] = get_linear_schedule_with_warmup( optimizer=lowercase__ , num_warmup_steps=0 , num_training_steps=lowercase__ , ) else: lowerCAmelCase_ :int = DummyScheduler(lowercase__ , total_num_steps=lowercase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ :List[Any] = accelerator.prepare( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) # We need to keep track of how many total steps we have iterated over lowerCAmelCase_ :List[str] = 0 # We also need to keep track of the stating epoch so files are named properly lowerCAmelCase_ :List[Any] = 0 lowerCAmelCase_ :str = evaluate.load("""glue""" , """mrpc""" ) lowerCAmelCase_ :Optional[Any] = num_epochs if args.partial_train_epoch is not None: lowerCAmelCase_ :Dict = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) lowerCAmelCase_ :Optional[Any] = args.resume_from_checkpoint.split("""epoch_""" )[1] lowerCAmelCase_ :int = """""" for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break lowerCAmelCase_ :Union[str, Any] = int(lowercase__ ) + 1 lowerCAmelCase_ :Optional[int] = evaluation_loop(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.print("""resumed checkpoint performance:""" , lowercase__ ) accelerator.print("""resumed checkpoint's scheduler's lr:""" , lr_scheduler.get_lr()[0] ) accelerator.print("""resumed optimizers's lr:""" , optimizer.param_groups[0]["""lr"""] ) with open(os.path.join(args.output_dir , f"""state_{starting_epoch-1}.json""" ) , """r""" ) as f: lowerCAmelCase_ :List[str] = json.load(lowercase__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model lowerCAmelCase_ :List[Any] = {} for epoch in range(lowercase__ , lowercase__ ): model.train() for step, batch in enumerate(lowercase__ ): lowerCAmelCase_ :Optional[int] = model(**lowercase__ ) lowerCAmelCase_ :Dict = outputs.loss lowerCAmelCase_ :int = loss / gradient_accumulation_steps accelerator.backward(lowercase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 lowerCAmelCase_ :List[str] = f"""epoch_{epoch}""" lowerCAmelCase_ :Any = os.path.join(args.output_dir , lowercase__ ) accelerator.save_state(lowercase__ ) lowerCAmelCase_ :List[Any] = evaluation_loop(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) lowerCAmelCase_ :Union[str, Any] = accuracy lowerCAmelCase_ :Any = lr_scheduler.get_lr()[0] lowerCAmelCase_ :str = optimizer.param_groups[0]["""lr"""] lowerCAmelCase_ :List[Any] = epoch lowerCAmelCase_ :Tuple = overall_step accelerator.print(f"""epoch {epoch}:""" , lowercase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f"""state_{epoch}.json""" ) , """w""" ) as f: json.dump(lowercase__ , lowercase__ ) def _snake_case ( ) -> int: '''simple docstring''' lowerCAmelCase_ :List[Any] = argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage.""" ) parser.add_argument( """--model_name_or_path""" , type=lowercase__ , default="""bert-base-cased""" , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=lowercase__ , ) parser.add_argument( """--output_dir""" , type=lowercase__ , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=lowercase__ , default=lowercase__ , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--partial_train_epoch""" , type=lowercase__ , default=lowercase__ , help="""If passed, the training will stop after this number of epochs.""" , ) parser.add_argument( """--num_epochs""" , type=lowercase__ , default=2 , help="""Number of train epochs.""" , ) lowerCAmelCase_ :Optional[int] = parser.parse_args() lowerCAmelCase_ :List[Any] = {"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 4_2, """batch_size""": 1_6} training_function(lowercase__ , lowercase__ ) if __name__ == "__main__": main()
1
0