code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _a ( a :int ) -> List[str]: 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 ( a :Union[str, Any] , a :Dict ) -> str: for key in orig_state_dict.copy().keys(): a = orig_state_dict.pop(a ) 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 ( a :Any , a :int ) -> List[str]: a = ViTMAEConfig() if "large" in checkpoint_url: a = 1_024 a = 4_096 a = 24 a = 16 elif "huge" in checkpoint_url: a = 14 a = 1_280 a = 5_120 a = 32 a = 16 a = ViTMAEForPreTraining(a ) a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' )['''model'''] a = ViTMAEImageProcessor(size=config.image_size ) a = convert_state_dict(a , a ) model.load_state_dict(a ) model.eval() a = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) a = ViTMAEImageProcessor(size=config.image_size ) a = image_processor(images=a , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) a = model(**a ) a = outputs.logits if "large" in checkpoint_url: a = 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: a = 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: a = 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] , a , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = 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__ = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
0
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = set({'''(''', '''[''', '''{'''} ) __lowerCamelCase = set({''')''', ''']''', '''}'''} ) __lowerCamelCase = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def __lowerCAmelCase ( ) -> str: __lowerCamelCase = input('''Enter sequence of brackets: ''' ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , '''is balanced''' ) else: print(UpperCamelCase__ , '''is not balanced''' ) if __name__ == "__main__": main()
67
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class __A ( UpperCamelCase__ ): a__ : Dict = ["""image_processor""", """feature_extractor"""] a__ : List[str] = """TvltImageProcessor""" a__ : Tuple = """TvltFeatureExtractor""" def __init__(self : Tuple , __a : List[str] , __a : List[Any] ): super().__init__(image_processor=__a , feature_extractor=__a ) UpperCAmelCase_ = image_processor UpperCAmelCase_ = feature_extractor def __call__(self : Dict , __a : Dict=None , __a : Union[str, Any]=None , __a : str=None , __a : List[str]=None , __a : Tuple=False , __a : Dict=False , *__a : Optional[int] , **__a : List[Any] , ): if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) UpperCAmelCase_ = None if images is not None: UpperCAmelCase_ = self.image_processor(__a , mask_pixel=__a , *__a , **__a ) if images_mixed is not None: UpperCAmelCase_ = self.image_processor(__a , is_mixed=__a , *__a , **__a ) if audio is not None: UpperCAmelCase_ = self.feature_extractor( __a , *__a , sampling_rate=__a , mask_audio=__a , **__a ) UpperCAmelCase_ = {} if audio is not None: output_dict.update(__a ) if images is not None: output_dict.update(__a ) if images_mixed_dict is not None: output_dict.update(__a ) return output_dict @property def _lowercase (self : Any ): UpperCAmelCase_ = self.image_processor.model_input_names UpperCAmelCase_ = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
1
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict ="M-CLIP" def __init__( self : Tuple , a : Optional[int]=10_24 , a : Tuple=7_68 , **a : List[str] ): """simple docstring""" __lowerCamelCase = transformerDimSize __lowerCamelCase = imageDimSize super().__init__(**a ) class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =MCLIPConfig def __init__( self : str , a : List[Any] , *a : Dict , **a : str ): """simple docstring""" super().__init__(a , *a , **a ) __lowerCamelCase = XLMRobertaModel(a ) __lowerCamelCase = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.transformer(input_ids=a , attention_mask=a )[0] __lowerCamelCase = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a ), embs
67
0
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights lowercase__ = FlaxDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase , cache_dir=UpperCamelCase ) lowercase__ = [t[-1] for t in os.walk(os.path.join(UpperCamelCase , os.listdir(UpperCamelCase )[0] , '''snapshots''' ) )] lowercase__ = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('''.bin''' ) for f in files ) @slow @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 4 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_51_47_45 ) < 1E-3 assert np.abs(np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 4_99_47.8_75 ) < 5E-1 lowercase__ = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(UpperCamelCase ) == num_samples def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''flax''' , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_65_24_01) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_38_38_08.2) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , set_alpha_to_one=UpperCamelCase , steps_offset=1 , ) lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , scheduler=UpperCamelCase , safety_checker=UpperCamelCase , ) lowercase__ = scheduler.create_state() lowercase__ = scheduler_state lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_45_04_39_45) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_34_76_93.5) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = jax.random.split(jax.random.PRNGKey(0 ) , UpperCamelCase ) lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase , ) lowercase__ = replicate(UpperCamelCase ) lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) lowercase__ = images[2, 0, 256, 10:17, 1] # With memory efficient attention lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase , use_memory_efficient_attention=UpperCamelCase , ) lowercase__ = replicate(UpperCamelCase ) lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) lowercase__ = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
2
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
67
0
'''simple docstring''' from __future__ import annotations lowercase : Optional[Any] = list[tuple[int, int]] lowercase : Optional[Any] = [ [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], ] lowercase : List[str] = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" A : str = pos_x A : List[Any] = pos_y A : Union[str, Any] = (pos_y, pos_x) A : Tuple = goal_x A : Dict = goal_y A : Optional[int] = g_cost A : Union[str, Any] = parent A : Union[str, Any] = self.calculate_heuristic() def __lowerCAmelCase ( self ) -> float: """simple docstring""" A : List[Any] = abs(self.pos_x - self.goal_x ) A : str = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self , SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" return self.f_cost < other.f_cost class A : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" A : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE ) A : str = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE ) A : List[Any] = [self.start] A : list[Node] = [] A : List[Any] = False def __lowerCAmelCase ( self ) -> Path | None: """simple docstring""" while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() A : Tuple = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: A : List[Any] = True return self.retrace_path(SCREAMING_SNAKE_CASE ) self.closed_nodes.append(SCREAMING_SNAKE_CASE ) A : Tuple = self.get_successors(SCREAMING_SNAKE_CASE ) 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(SCREAMING_SNAKE_CASE ) else: # retrieve the best current path A : Optional[int] = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE ) if not self.reached: return [self.start.pos] return None def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> list[Node]: """simple docstring""" A : Union[str, Any] = [] for action in delta: A : Union[str, Any] = parent.pos_x + action[1] A : str = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE , ) ) return successors def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Path: """simple docstring""" A : Optional[Any] = node A : Any = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) A : str = current_node.parent path.reverse() return path if __name__ == "__main__": lowercase : Tuple = (0, 0) lowercase : Union[str, Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print('------') lowercase : List[str] = GreedyBestFirst(init, goal) lowercase : Any = greedy_bf.search() if path: for pos_x, pos_y in path: lowercase : Optional[Any] = 2 for elem in grid: print(elem)
3
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
'''simple docstring''' import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device 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 transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCAmelCase_ ( __lowercase ): def __UpperCAmelCase ( self : Union[str, Any] ) -> str: lowerCAmelCase = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase__ , 'embed_dim' ) ) self.parent.assertTrue(hasattr(UpperCAmelCase__ , 'num_heads' ) ) class UpperCAmelCase_ : def __init__( self : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : Dict=6_4 , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : Union[str, Any]=[1_6, 4_8, 9_6] , UpperCAmelCase__ : Dict=[1, 3, 6] , UpperCAmelCase__ : Optional[Any]=[1, 2, 1_0] , UpperCAmelCase__ : List[Any]=[7, 3, 3] , UpperCAmelCase__ : Union[str, Any]=[4, 2, 2] , UpperCAmelCase__ : List[Any]=[2, 1, 1] , UpperCAmelCase__ : Union[str, Any]=[2, 2, 2] , UpperCAmelCase__ : Dict=[False, False, True] , UpperCAmelCase__ : Any=[0.0, 0.0, 0.0] , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : str=1E-12 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Optional[Any]=2 , ) -> Tuple: lowerCAmelCase = parent lowerCAmelCase = batch_size lowerCAmelCase = image_size lowerCAmelCase = patch_sizes lowerCAmelCase = patch_stride lowerCAmelCase = patch_padding lowerCAmelCase = is_training lowerCAmelCase = use_labels lowerCAmelCase = num_labels lowerCAmelCase = num_channels lowerCAmelCase = embed_dim lowerCAmelCase = num_heads lowerCAmelCase = stride_kv lowerCAmelCase = depth lowerCAmelCase = cls_token lowerCAmelCase = attention_drop_rate lowerCAmelCase = initializer_range lowerCAmelCase = layer_norm_eps def __UpperCAmelCase ( self : int ) -> List[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.num_labels ) lowerCAmelCase = self.get_config() return config, pixel_values, labels def __UpperCAmelCase ( self : str ) -> str: return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCAmelCase ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] ) -> Dict: lowerCAmelCase = CvtModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = model(UpperCAmelCase__ ) lowerCAmelCase = (self.image_size, self.image_size) lowerCAmelCase , lowerCAmelCase = image_size[0], image_size[1] for i in range(len(self.depth ) ): lowerCAmelCase = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) lowerCAmelCase = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCAmelCase ( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any ) -> List[str]: lowerCAmelCase = self.num_labels lowerCAmelCase = CvtForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() lowerCAmelCase = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCAmelCase ( self : Dict ) -> 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 : Any = (CvtModel, CvtForImageClassification) if is_torch_available() else () lowerCamelCase : str = ( {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification} if is_torch_available() else {} ) lowerCamelCase : Optional[Any] = False lowerCamelCase : Dict = False lowerCamelCase : List[str] = False lowerCamelCase : Union[str, Any] = False lowerCamelCase : Tuple = False def __UpperCAmelCase ( self : Dict ) -> Optional[Any]: lowerCAmelCase = CvtModelTester(self ) lowerCAmelCase = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def __UpperCAmelCase ( self : Optional[Any] ) -> int: 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 __UpperCAmelCase ( self : List[Any] ) -> List[str]: return @unittest.skip(reason='Cvt does not output attentions' ) def __UpperCAmelCase ( self : Tuple ) -> List[Any]: pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def __UpperCAmelCase ( self : Union[str, Any] ) -> str: pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def __UpperCAmelCase ( self : Tuple ) -> Any: pass def __UpperCAmelCase ( self : Any ) -> int: 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 : Dict ) -> Dict: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def __UpperCAmelCase ( self : Optional[int] ) -> List[str]: def check_hidden_states_output(UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any ): lowerCAmelCase = model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() with torch.no_grad(): lowerCAmelCase = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) lowerCAmelCase = outputs.hidden_states lowerCAmelCase = len(self.model_tester.depth ) self.assertEqual(len(UpperCAmelCase__ ) , UpperCAmelCase__ ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) lowerCAmelCase , lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def __UpperCAmelCase ( self : int ) -> Dict: lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __UpperCAmelCase ( self : List[str] ) -> Optional[int]: pass @slow def __UpperCAmelCase ( self : Tuple ) -> Union[str, Any]: for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase = CvtModel.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 : Tuple ) -> Optional[int]: return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCAmelCase ( self : Tuple ) -> Optional[Any]: lowerCAmelCase = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).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.9_285, 0.9_015, -0.3_150] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
4
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
0
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class lowerCamelCase__ : def __init__(self , UpperCAmelCase , UpperCAmelCase=1_3 , UpperCAmelCase=7 , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=9_9 , UpperCAmelCase=3_2 , UpperCAmelCase=2 , UpperCAmelCase=4 , UpperCAmelCase=3_7 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.1 , UpperCAmelCase=5_1_2 , UpperCAmelCase=1_6 , UpperCAmelCase=2 , UpperCAmelCase=0.02 , UpperCAmelCase=3 , UpperCAmelCase=4 , UpperCAmelCase=None , ) -> str: _lowercase =parent _lowercase =1_3 _lowercase =7 _lowercase =True _lowercase =True _lowercase =True _lowercase =True _lowercase =9_9 _lowercase =3_2 _lowercase =2 _lowercase =4 _lowercase =3_7 _lowercase ='''gelu''' _lowercase =0.1 _lowercase =0.1 _lowercase =5_1_2 _lowercase =1_6 _lowercase =2 _lowercase =0.02 _lowercase =3 _lowercase =4 _lowercase =None def __A (self ) -> Any: _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowercase =None if self.use_input_mask: _lowercase =random_attention_mask([self.batch_size, self.seq_length] ) _lowercase =None if self.use_token_type_ids: _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _lowercase =None _lowercase =None _lowercase =None if self.use_labels: _lowercase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowercase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowercase =ids_tensor([self.batch_size] , self.num_choices ) _lowercase =RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCAmelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> str: _lowercase =TFRoFormerModel(config=UpperCAmelCase ) _lowercase ={'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} _lowercase =[input_ids, input_mask] _lowercase =model(UpperCAmelCase ) _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Dict: _lowercase =True _lowercase =TFRoFormerForCausalLM(config=UpperCAmelCase ) _lowercase ={ '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _lowercase =model(UpperCAmelCase )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Tuple: _lowercase =TFRoFormerForMaskedLM(config=UpperCAmelCase ) _lowercase ={ '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]: _lowercase =self.num_labels _lowercase =TFRoFormerForSequenceClassification(config=UpperCAmelCase ) _lowercase ={ '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Any: _lowercase =self.num_choices _lowercase =TFRoFormerForMultipleChoice(config=UpperCAmelCase ) _lowercase =tf.tile(tf.expand_dims(UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) _lowercase =tf.tile(tf.expand_dims(UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) _lowercase =tf.tile(tf.expand_dims(UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) _lowercase ={ '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> int: _lowercase =self.num_labels _lowercase =TFRoFormerForTokenClassification(config=UpperCAmelCase ) _lowercase ={ '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: _lowercase =TFRoFormerForQuestionAnswering(config=UpperCAmelCase ) _lowercase ={ '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } _lowercase =model(UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A (self ) -> int: _lowercase =self.prepare_config_and_inputs() ( ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ( _lowercase ) , ) =config_and_inputs _lowercase ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class lowerCamelCase__ ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase): SCREAMING_SNAKE_CASE__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) SCREAMING_SNAKE_CASE__ = ( { '''feature-extraction''': TFRoFormerModel, '''fill-mask''': TFRoFormerForMaskedLM, '''question-answering''': TFRoFormerForQuestionAnswering, '''text-classification''': TFRoFormerForSequenceClassification, '''text-generation''': TFRoFormerForCausalLM, '''token-classification''': TFRoFormerForTokenClassification, '''zero-shot''': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False def __A (self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def __A (self ) -> Tuple: _lowercase =TFRoFormerModelTester(self ) _lowercase =ConfigTester(self , config_class=UpperCAmelCase , hidden_size=3_7 ) def __A (self ) -> str: self.config_tester.run_common_tests() def __A (self ) -> List[Any]: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase ) def __A (self ) -> Dict: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase ) def __A (self ) -> Any: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*UpperCAmelCase ) def __A (self ) -> List[Any]: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase ) def __A (self ) -> Tuple: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase ) def __A (self ) -> Any: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase ) def __A (self ) -> List[str]: _lowercase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase ) @slow def __A (self ) -> Optional[int]: _lowercase =TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(UpperCAmelCase ) @require_tf class lowerCamelCase__ ( unittest.TestCase): @slow def __A (self ) -> Dict: _lowercase =TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) _lowercase =tf.constant([[0, 1, 2, 3, 4, 5]] ) _lowercase =model(UpperCAmelCase )[0] # TODO Replace vocab size _lowercase =5_0_0_0_0 _lowercase =[1, 6, vocab_size] self.assertEqual(output.shape , UpperCAmelCase ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. _lowercase =tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase , atol=1e-4 ) @require_tf class lowerCamelCase__ ( unittest.TestCase): SCREAMING_SNAKE_CASE__ = 1E-4 def __A (self ) -> List[Any]: _lowercase =tf.constant([[4, 1_0]] ) _lowercase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) _lowercase =emba(input_ids.shape ) _lowercase =tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(UpperCAmelCase , UpperCAmelCase , atol=self.tolerance ) def __A (self ) -> Optional[Any]: _lowercase =tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) _lowercase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) _lowercase =emba.weight[:3, :5] tf.debugging.assert_near(UpperCAmelCase , UpperCAmelCase , atol=self.tolerance ) @require_tf class lowerCamelCase__ ( unittest.TestCase): SCREAMING_SNAKE_CASE__ = 1E-4 def __A (self ) -> List[Any]: # 2,12,16,64 _lowercase =tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 _lowercase =-tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 _lowercase =TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) _lowercase =embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] _lowercase , _lowercase =TFRoFormerSelfAttention.apply_rotary_position_embeddings( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) _lowercase =tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) _lowercase =tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , UpperCAmelCase , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , UpperCAmelCase , atol=self.tolerance )
5
'''simple docstring''' 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_barthez import BarthezTokenizer else: __UpperCAmelCase =None __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __UpperCAmelCase ={ "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } __UpperCAmelCase ={ "moussaKam/mbarthez": 1_0_2_4, "moussaKam/barthez": 1_0_2_4, "moussaKam/barthez-orangesum-title": 1_0_2_4, } __UpperCAmelCase ="▁" class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] =["input_ids", "attention_mask"] lowerCamelCase : Union[str, Any] =BarthezTokenizer def __init__( self : Optional[Any] , a : Dict=None , a : str=None , a : List[Any]="<s>" , a : Optional[int]="</s>" , a : List[str]="</s>" , a : Tuple="<s>" , a : str="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , **a : Union[str, Any] , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Optional[str] = None ): """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(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
67
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A : List[str] = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Union[str, Any] = [ 'GIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GitForCausalLM', 'GitModel', 'GitPreTrainedModel', 'GitVisionModel', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys A : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
6
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00_00 ) -> int: __lowerCamelCase = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , UpperCamelCase__ , UpperCamelCase__ ) ) ) __lowerCamelCase = [float(UpperCamelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCamelCase__ , limit + 1 , UpperCamelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'{solution() = }')
67
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class A ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = StableDiffusionXLImgaImgPipeline lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} lowerCamelCase = PipelineTesterMixin.required_optional_params - {'latents'} lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def snake_case__ ( self : Union[str, Any] )-> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) A__ = UNetaDConditionModel( block_out_channels=(3_2, 6_4),layers_per_block=2,sample_size=3_2,in_channels=4,out_channels=4,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'),up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'),attention_head_dim=(2, 4),use_linear_projection=lowercase_,addition_embed_type='text_time',addition_time_embed_dim=8,transformer_layers_per_block=(1, 2),projection_class_embeddings_input_dim=8_0,cross_attention_dim=6_4,) A__ = EulerDiscreteScheduler( beta_start=0.00_085,beta_end=0.012,steps_offset=1,beta_schedule='scaled_linear',timestep_spacing='leading',) torch.manual_seed(0 ) A__ = AutoencoderKL( block_out_channels=[3_2, 6_4],in_channels=3,out_channels=3,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'],up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'],latent_channels=4,sample_size=1_2_8,) torch.manual_seed(0 ) A__ = CLIPTextConfig( bos_token_id=0,eos_token_id=2,hidden_size=3_2,intermediate_size=3_7,layer_norm_eps=1E-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,hidden_act='gelu',projection_dim=3_2,) A__ = CLIPTextModel(lowercase_ ) A__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip',local_files_only=lowercase_ ) A__ = CLIPTextModelWithProjection(lowercase_ ) A__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip',local_files_only=lowercase_ ) A__ = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'text_encoder_2': text_encoder_a, 'tokenizer_2': tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def snake_case__ ( self : List[str],lowercase_ : Optional[Any],lowercase_ : str=0 )-> Optional[int]: '''simple docstring''' A__ = floats_tensor((1, 3, 3_2, 3_2),rng=random.Random(lowercase_ ) ).to(lowercase_ ) A__ = image / 2 + 0.5 if str(lowercase_ ).startswith('mps' ): A__ = torch.manual_seed(lowercase_ ) else: A__ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) A__ = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 5.0, 'output_type': 'numpy', 'strength': 0.75, } return inputs def snake_case__ ( self : Union[str, Any] )-> str: '''simple docstring''' A__ = 'cpu' # ensure determinism for the device-dependent torch.Generator A__ = self.get_dummy_components() A__ = StableDiffusionXLImgaImgPipeline(**lowercase_ ) A__ = sd_pipe.to(lowercase_ ) sd_pipe.set_progress_bar_config(disable=lowercase_ ) A__ = self.get_dummy_inputs(lowercase_ ) A__ = sd_pipe(**lowercase_ ).images A__ = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) A__ = np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case__ ( self : List[Any] )-> str: '''simple docstring''' super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def snake_case__ ( self : Tuple )-> Dict: '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def snake_case__ ( self : int )-> Tuple: '''simple docstring''' pass def snake_case__ ( self : List[str] )-> Tuple: '''simple docstring''' A__ = self.get_dummy_components() A__ = StableDiffusionXLImgaImgPipeline(**lowercase_ ) A__ = sd_pipe.to(lowercase_ ) A__ = sd_pipe.to(lowercase_ ) sd_pipe.set_progress_bar_config(disable=lowercase_ ) # forward without prompt embeds A__ = self.get_dummy_inputs(lowercase_ ) A__ = 3 * ['this is a negative prompt'] A__ = negative_prompt A__ = 3 * [inputs['prompt']] A__ = sd_pipe(**lowercase_ ) A__ = output.images[0, -3:, -3:, -1] # forward with prompt embeds A__ = self.get_dummy_inputs(lowercase_ ) A__ = 3 * ['this is a negative prompt'] A__ = 3 * [inputs.pop('prompt' )] ( ( A__ ) , ( A__ ) , ( A__ ) , ( A__ ) , ) = sd_pipe.encode_prompt(lowercase_,negative_prompt=lowercase_ ) A__ = sd_pipe( **lowercase_,prompt_embeds=lowercase_,negative_prompt_embeds=lowercase_,pooled_prompt_embeds=lowercase_,negative_pooled_prompt_embeds=lowercase_,) A__ = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class A ( unittest.TestCase ): """simple docstring""" def snake_case__ ( self : Union[str, Any] )-> List[Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case__ ( self : Optional[Any],lowercase_ : Union[str, Any],lowercase_ : Any="cpu",lowercase_ : str=torch.floataa,lowercase_ : str=0 )-> List[str]: '''simple docstring''' A__ = torch.Generator(device=lowercase_ ).manual_seed(lowercase_ ) A__ = np.random.RandomState(lowercase_ ).standard_normal((1, 4, 6_4, 6_4) ) A__ = torch.from_numpy(lowercase_ ).to(device=lowercase_,dtype=lowercase_ ) A__ = { 'prompt': 'a photograph of an astronaut riding a horse', 'latents': latents, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def snake_case__ ( self : List[Any] )-> Dict: '''simple docstring''' A__ = DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base' ) pipe.to(lowercase_ ) pipe.set_progress_bar_config(disable=lowercase_ ) A__ = self.get_inputs(lowercase_ ) A__ = pipe(**lowercase_ ).images A__ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) A__ = np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
7
'''simple docstring''' 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 a__ : def __init__( self : Union[str, Any] , a : Union[str, Any] , a : Tuple=13 , a : Optional[Any]=7 , a : List[Any]=True , a : Optional[Any]=True , a : Any=True , a : Union[str, Any]=99 , a : Any=32 , a : int=5 , a : Optional[int]=4 , a : Union[str, Any]=37 , a : Optional[Any]="gelu" , a : Union[str, Any]=0.1 , a : Any=0.1 , a : Optional[int]=5_12 , a : int=16 , a : Optional[Any]=2 , a : Union[str, Any]=0.02 , a : Any=3 , a : Dict=4 , a : Any=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = self.vocab_size - 1 def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __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 = 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 , ) __lowerCamelCase = 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 : Union[str, Any] , a : Dict , a : List[str] , a : Tuple , a : List[Any] , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , head_mask=a ) __lowerCamelCase = model(a , token_type_ids=a ) __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Union[str, Any] , a : Dict , a : Union[str, Any] , a : Tuple , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Optional[Any] , *a : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTDoubleHeadsModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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 : List[str] , a : int , a : Dict , a : Optional[Any] , a : str , *a : int ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = OpenAIGPTForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """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, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : List[str] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCamelCase : str =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCamelCase : Optional[int] =( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple , a : Optional[int] , a : int , a : str , a : Any ): """simple docstring""" 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 : Optional[int] , a : int , a : Optional[int] , a : str=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a , ) __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a , ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , n_embd=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = OpenAIGPTModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(a ) __lowerCamelCase = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=a ) # the president is __lowerCamelCase = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the __lowerCamelCase = model.generate(a , do_sample=a ) self.assertListEqual(output_ids[0].tolist() , a )
67
0
def __SCREAMING_SNAKE_CASE (SCREAMING_SNAKE_CASE__ = 1000 ): snake_case_, snake_case_ = 1, 1 snake_case_ = [] for i in range(1 , n + 1 ): snake_case_ = prev_numerator + 2 * prev_denominator snake_case_ = prev_numerator + prev_denominator if len(str(SCREAMING_SNAKE_CASE__ ) ) > len(str(SCREAMING_SNAKE_CASE__ ) ): result.append(SCREAMING_SNAKE_CASE__ ) snake_case_ = numerator snake_case_ = denominator return len(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(f"""{solution() = }""")
8
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =["image_processor", "tokenizer"] lowerCamelCase : Union[str, Any] ="LayoutLMv2ImageProcessor" lowerCamelCase : int =("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , a : Any=None , a : Any=None , **a : Union[str, Any] ): """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a , a ) def __call__( self : Tuple , a : Optional[int] , a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a : Union[List[List[int]], List[List[List[int]]]] = None , a : Optional[Union[List[int], List[List[int]]]] = None , a : bool = True , a : Union[bool, str, PaddingStrategy] = False , a : Union[bool, str, TruncationStrategy] = None , a : Optional[int] = None , a : int = 0 , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[bool] = None , a : bool = False , a : bool = False , a : bool = False , a : bool = False , a : bool = True , a : Optional[Union[str, TensorType]] = None , **a : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=a , return_tensors=a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a , a ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features['''words'''] __lowerCamelCase = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel values __lowerCamelCase = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(a , encoded_inputs['''overflow_to_sample_mapping'''] ) __lowerCamelCase = images return encoded_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Optional[Any] , a : str ): """simple docstring""" __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a ) != len(a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(a )} and {len(a )}""" ) return images_with_overflow def SCREAMING_SNAKE_CASE__ ( self : List[str] , *a : Optional[Any] , **a : Union[str, Any] ): """simple docstring""" return self.tokenizer.batch_decode(*a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *a : Union[str, Any] , **a : Tuple ): """simple docstring""" return self.tokenizer.decode(*a , **a ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a , ) return self.image_processor
67
0
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''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): """simple docstring""" super().__init__() __lowerCamelCase = nn.ModuleList(a ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : torch.FloatTensor , a : Union[torch.Tensor, float, int] , a : torch.Tensor , a : List[torch.tensor] , a : List[float] , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[Dict[str, Any]] = None , a : bool = False , a : bool = True , ): """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets ) ): __lowerCamelCase , __lowerCamelCase = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: __lowerCamelCase , __lowerCamelCase = down_samples, mid_sample else: __lowerCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self : Any , a : Union[str, os.PathLike] , a : bool = True , a : Callable = None , a : bool = False , a : Optional[str] = None , ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 __lowerCamelCase = model_path_to_save + f"""_{idx}""" @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[str] , a : Optional[Union[str, os.PathLike]] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __lowerCamelCase = pretrained_model_path while os.path.isdir(a ): __lowerCamelCase = ControlNetModel.from_pretrained(a , **a ) controlnets.append(a ) idx += 1 __lowerCamelCase = pretrained_model_path + f"""_{idx}""" logger.info(f"""{len(a )} controlnets loaded from {pretrained_model_path}.""" ) if len(a ) == 0: raise ValueError( f"""No ControlNets found under {os.path.dirname(a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(a )
67
0
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() __A = logging.get_logger(__name__) __A = { "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", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "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", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } __A = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> Optional[Any]: """simple docstring""" for attribute in key.split("." ): lowerCamelCase__: str =getattr(__a , __a ) if weight_type is not None: lowerCamelCase__: Tuple =getattr(__a , __a ).shape else: lowerCamelCase__: List[str] =hf_pointer.shape if hf_shape != value.shape: raise ValueError( 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": lowerCamelCase__: List[Any] =value elif weight_type == "weight_g": lowerCamelCase__: Tuple =value elif weight_type == "weight_v": lowerCamelCase__: List[str] =value elif weight_type == "bias": lowerCamelCase__: List[str] =value else: lowerCamelCase__: str =value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Tuple =[] lowerCamelCase__: List[str] =fairseq_model.state_dict() lowerCamelCase__: Any =hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): lowerCamelCase__: Tuple =False if "conv_layers" in name: load_conv_layer( __a , __a , __a , __a , hf_model.config.feat_extract_norm == "group" , ) lowerCamelCase__: Optional[int] =True else: for key, mapped_key in MAPPING.items(): lowerCamelCase__: List[Any] ="unispeech_sat." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: if "layer_norm_for_extract" in name and (".".join(name.split("." )[:-1] ) != key): # special case since naming is very similar continue lowerCamelCase__: str =True if "*" in mapped_key: lowerCamelCase__: List[str] =name.split(__a )[0].split("." )[-2] lowerCamelCase__: Tuple =mapped_key.replace("*" , __a ) if "weight_g" in name: lowerCamelCase__: str ="weight_g" elif "weight_v" in name: lowerCamelCase__: Union[str, Any] ="weight_v" elif "bias" in name: lowerCamelCase__: Dict ="bias" elif "weight" in name: # TODO: don't match quantizer.weight_proj lowerCamelCase__: Dict ="weight" else: lowerCamelCase__: Any =None set_recursively(__a , __a , __a , __a , __a ) continue if not is_used: unused_weights.append(__a ) logger.warning(F"""Unused weights: {unused_weights}""" ) def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =full_name.split("conv_layers." )[-1] lowerCamelCase__: Tuple =name.split("." ) lowerCamelCase__: Any =int(items[0] ) lowerCamelCase__: Optional[int] =int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) lowerCamelCase__: List[Any] =value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) lowerCamelCase__: Any =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: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) lowerCamelCase__: Optional[int] =value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) lowerCamelCase__: str =value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(__a ) @torch.no_grad() def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=True ) -> Optional[Any]: """simple docstring""" if config_path is not None: lowerCamelCase__: Dict =UniSpeechSatConfig.from_pretrained(__a ) else: lowerCamelCase__: Union[str, Any] =UniSpeechSatConfig() lowerCamelCase__: Any ="" if is_finetuned: lowerCamelCase__: Optional[int] =UniSpeechSatForCTC(__a ) else: lowerCamelCase__: Optional[int] =UniSpeechSatForPreTraining(__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) lowerCamelCase__: Optional[Any] =model[0].eval() recursively_load_weights(__a , __a ) hf_wavavec.save_pretrained(__a ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) __A = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
10
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
0
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowerCAmelCase__ = 10 def _UpperCAmelCase (UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): for i in range(UpperCamelCase__ , UpperCamelCase__ ): if array[i] == target: return i return -1 def _UpperCAmelCase (UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): _A : Any = 0 _A : Union[str, Any] = len(UpperCamelCase__ ) while left <= right: if right - left < precision: return lin_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _A : Dict = (left + right) // 3 + 1 _A : Any = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: _A : Optional[Any] = one_third - 1 elif array[two_third] < target: _A : List[Any] = two_third + 1 else: _A : int = one_third + 1 _A : List[Any] = two_third - 1 else: return -1 def _UpperCAmelCase (UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : list[int] , UpperCamelCase__ : int ): if left < right: if right - left < precision: return lin_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) _A : Optional[int] = (left + right) // 3 + 1 _A : Tuple = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(UpperCamelCase__ , one_third - 1 , UpperCamelCase__ , UpperCamelCase__ ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , UpperCamelCase__ , UpperCamelCase__ ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ = input('Enter numbers separated by comma:\n').strip() lowerCAmelCase__ = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." lowerCAmelCase__ = int(input('Enter the number to be found in the list:\n').strip()) lowerCAmelCase__ = ite_ternary_search(collection, target) lowerCAmelCase__ = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"Iterative search: {target} found at positions: {resulta}") print(f"Recursive search: {target} found at positions: {resulta}") else: print('Not found')
11
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness UpperCAmelCase_ = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' UpperCAmelCase_ = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' UpperCAmelCase_ = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' UpperCAmelCase_ = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' UpperCAmelCase_ = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class lowerCamelCase__( datasets.Metric): def lowerCAmelCase__ ( self: Dict ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Sequence(datasets.Value("""string""" ) ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/openai/human-eval""" , codebase_urls=["""https://github.com/openai/human-eval"""] , reference_urls=["""https://github.com/openai/human-eval"""] , license=_LICENSE , ) def lowerCAmelCase__ ( self: Optional[int] , UpperCamelCase_: Any , UpperCamelCase_: Tuple , UpperCamelCase_: Union[str, Any]=[1, 10, 1_00] , UpperCamelCase_: str=4 , UpperCamelCase_: Optional[Any]=3.0 ): if os.getenv("""HF_ALLOW_CODE_EVAL""" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("""This metric is currently not supported on Windows.""" ) with ThreadPoolExecutor(max_workers=UpperCamelCase_ ) as executor: __lowerCamelCase = [] __lowerCamelCase = Counter() __lowerCamelCase = 0 __lowerCamelCase = defaultdict(UpperCamelCase_ ) for task_id, (candidates, test_case) in enumerate(zip(UpperCamelCase_ , UpperCamelCase_ ) ): for candidate in candidates: __lowerCamelCase = candidate + """\n""" + test_case __lowerCamelCase = (test_program, timeout, task_id, completion_id[task_id]) __lowerCamelCase = executor.submit(UpperCamelCase_ , *UpperCamelCase_ ) futures.append(UpperCamelCase_ ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(UpperCamelCase_ ): __lowerCamelCase = future.result() results[result["task_id"]].append((result["""completion_id"""], result) ) __lowerCamelCase, __lowerCamelCase = [], [] for result in results.values(): result.sort() __lowerCamelCase = [r[1]["""passed"""] for r in result] total.append(len(UpperCamelCase_ ) ) correct.append(sum(UpperCamelCase_ ) ) __lowerCamelCase = np.array(UpperCamelCase_ ) __lowerCamelCase = np.array(UpperCamelCase_ ) __lowerCamelCase = k __lowerCamelCase = {F'pass@{k}': estimate_pass_at_k(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCamelCase__ ( A__ : int , A__ : List[Any] , A__ : List[Any] ): '''simple docstring''' def estimator(A__ : int , A__ : int , A__ : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(A__ , A__ ): __lowerCamelCase = itertools.repeat(A__ , len(A__ ) ) else: assert len(A__ ) == len(A__ ) __lowerCamelCase = iter(A__ ) return np.array([estimator(int(A__ ) , int(A__ ) , A__ ) for n, c in zip(A__ , A__ )] )
12
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = '''ylacombe/bark-small''' __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = '''en_speaker_1''' __lowerCamelCase = '''This is a test string''' __lowerCamelCase = '''speaker_embeddings_path.json''' __lowerCamelCase = '''speaker_embeddings''' def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Dict ): """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __lowerCamelCase = 35 __lowerCamelCase = 2 __lowerCamelCase = 8 __lowerCamelCase = { '''semantic_prompt''': np.ones(a ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from npz file __lowerCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(a , **a ) __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from the hub __lowerCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) __lowerCamelCase = processor(text=self.input_string ) __lowerCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
67
0
from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. lowerCAmelCase : Optional[int] = 10 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): for i in range(_UpperCAmelCase , _UpperCAmelCase ): if array[i] == target: return i return -1 def A_ ( _UpperCAmelCase , _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Optional[int] = 0 SCREAMING_SNAKE_CASE_: str = len(_UpperCAmelCase ) while left <= right: if right - left < precision: return lin_search(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] = (left + right) // 3 + 1 SCREAMING_SNAKE_CASE_: Optional[Any] = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: SCREAMING_SNAKE_CASE_: Optional[Any] = one_third - 1 elif array[two_third] < target: SCREAMING_SNAKE_CASE_: Dict = two_third + 1 else: SCREAMING_SNAKE_CASE_: List[Any] = one_third + 1 SCREAMING_SNAKE_CASE_: Any = two_third - 1 else: return -1 def A_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if left < right: if right - left < precision: return lin_search(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) SCREAMING_SNAKE_CASE_: str = (left + right) // 3 + 1 SCREAMING_SNAKE_CASE_: int = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(_UpperCAmelCase , one_third - 1 , _UpperCAmelCase , _UpperCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , _UpperCAmelCase , _UpperCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase : int = input("""Enter numbers separated by comma:\n""").strip() lowerCAmelCase : Any = [int(item.strip()) for item in user_input.split(""",""")] assert collection == sorted(collection), f"List must be ordered.\n{collection}." lowerCAmelCase : Optional[int] = int(input("""Enter the number to be found in the list:\n""").strip()) lowerCAmelCase : List[Any] = ite_ternary_search(collection, target) lowerCAmelCase : Dict = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f'''Iterative search: {target} found at positions: {resulta}''') print(f'''Recursive search: {target} found at positions: {resulta}''') else: print("""Not found""")
13
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
from __future__ import annotations _lowerCamelCase : Union[str, Any] = 10 def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[int]: """simple docstring""" A__ = 1 A__ = max(lowercase_ ) while placement <= max_digit: # declare and initialize empty buckets A__ = [[] for _ in range(lowercase_ )] # split list_of_ints between the buckets for i in list_of_ints: A__ = int((i / placement) % RADIX ) buckets[tmp].append(lowercase_ ) # put each buckets' contents into list_of_ints A__ = 0 for b in range(lowercase_ ): for i in buckets[b]: A__ = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
14
'''simple docstring''' import re from filelock import FileLock try: import nltk __UpperCAmelCase =True except (ImportError, ModuleNotFoundError): __UpperCAmelCase =False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: re.sub('''<n>''' , '''''' , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
67
0
def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = len(a_ ) __A = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): __A = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): __A = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: __A = subset[i - 1][j] if arr[i - 1] <= j: __A = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
15
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] ="gpt_neox_japanese" def __init__( self : List[Any] , a : Tuple=3_20_00 , a : Dict=25_60 , a : Union[str, Any]=32 , a : Dict=32 , a : Dict=4 , a : Optional[Any]="gelu" , a : Any=1.00 , a : str=1_00_00 , a : List[str]=20_48 , a : str=0.02 , a : Union[str, Any]=1e-5 , a : Optional[Any]=True , a : str=3_19_96 , a : List[str]=3_19_99 , a : str=0.1 , a : Union[str, Any]=0.0 , **a : Optional[Any] , ): """simple docstring""" super().__init__(bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_multiple_size __lowerCamelCase = hidden_act __lowerCamelCase = rotary_pct __lowerCamelCase = rotary_emb_base __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = attention_dropout __lowerCamelCase = hidden_dropout
67
0
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase_ = { 'configuration_cpmant': ['CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CpmAntConfig'], 'tokenization_cpmant': ['CpmAntTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ 'CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST', 'CpmAntForCausalLM', 'CpmAntModel', 'CpmAntPreTrainedModel', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
16
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase =int(input("Enter the first number: ").strip()) __UpperCAmelCase =int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
67
0
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _a = logging.get_logger() @dataclass class _lowerCAmelCase : """simple docstring""" __UpperCAmelCase : nn.Module __UpperCAmelCase : List[nn.Module] = field(default_factory=lowercase ) __UpperCAmelCase : list = field(default_factory=lowercase ) def _lowercase ( self : Dict, UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : Tensor, UpperCAmelCase__ : Tensor ): __lowercase = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__, nn.Convad ) or isinstance(UpperCAmelCase__, nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Optional[Any], UpperCAmelCase__ : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def _lowercase ( self : int ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0, self.traced ) ) @dataclass class _lowerCAmelCase : """simple docstring""" __UpperCAmelCase : nn.Module __UpperCAmelCase : nn.Module __UpperCAmelCase : int = 1 __UpperCAmelCase : List = field(default_factory=lowercase ) __UpperCAmelCase : List = field(default_factory=lowercase ) __UpperCAmelCase : bool = True def __call__( self : str, UpperCAmelCase__ : Tensor ): __lowercase = Tracker(self.dest )(UpperCAmelCase__ ).parametrized __lowercase = Tracker(self.src )(UpperCAmelCase__ ).parametrized __lowercase = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip, UpperCAmelCase__ ) ) __lowercase = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip, UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ) and self.raise_if_mismatch: raise Exception( F"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" F""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__, UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F"""Transfered from={src_m} to={dest_m}""" ) class _lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self : Any, UpperCAmelCase__ : nn.Module ): super().__init__() __lowercase = [] # - get the stem feature_blocks.append(("conv1", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("block" ), F"""Unexpected layer name {k}""" __lowercase = len(UpperCAmelCase__ ) + 1 feature_blocks.append((F"""res{block_index}""", v) ) __lowercase = nn.ModuleDict(UpperCAmelCase__ ) def _lowercase ( self : Tuple, UpperCAmelCase__ : Tensor ): return get_trunk_forward_outputs( UpperCAmelCase__, out_feat_keys=UpperCAmelCase__, feature_blocks=self._feature_blocks, ) class _lowerCAmelCase ( lowercase ): """simple docstring""" def _lowercase ( self : Dict, UpperCAmelCase__ : str ): __lowercase = x.split("-" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : List[Any], UpperCAmelCase__ : str ): # default to timm! if x not in self: __lowercase = self.convert_name_to_timm(UpperCAmelCase__ ) __lowercase = partial(lambda: (timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ).eval(), None) ) else: __lowercase = super().__getitem__(UpperCAmelCase__ ) return val class _lowerCAmelCase ( lowercase ): """simple docstring""" def __getitem__( self : str, UpperCAmelCase__ : str ): if "seer" in x and "in1k" not in x: __lowercase = RegNetModel else: __lowercase = RegNetForImageClassification return val def _A ( UpperCamelCase_ : Any, UpperCamelCase_ : Optional[int], UpperCamelCase_ : List[Tuple[str, str]]) -> List[Any]: '''simple docstring''' for from_key, to_key in keys: __lowercase = from_state_dict[from_key].clone() print(F"""Copied key={from_key} to={to_key}""") return to_state_dict def _A ( UpperCamelCase_ : str, UpperCamelCase_ : Callable[[], nn.Module], UpperCamelCase_ : Callable[[], nn.Module], UpperCamelCase_ : RegNetConfig, UpperCamelCase_ : Path, UpperCamelCase_ : bool = True, ) -> Any: '''simple docstring''' print(F"""Converting {name}...""") with torch.no_grad(): __lowercase ,__lowercase = from_model_func() __lowercase = our_model_func(UpperCamelCase_).eval() __lowercase = ModuleTransfer(src=UpperCamelCase_, dest=UpperCamelCase_, raise_if_mismatch=UpperCamelCase_) __lowercase = torch.randn((1, 3, 224, 224)) module_transfer(UpperCamelCase_) if from_state_dict is not None: __lowercase = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: __lowercase = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] __lowercase = manually_copy_vissl_head(UpperCamelCase_, our_model.state_dict(), UpperCamelCase_) our_model.load_state_dict(UpperCamelCase_) __lowercase = our_model(UpperCamelCase_, output_hidden_states=UpperCamelCase_) __lowercase = ( our_outputs.logits if isinstance(UpperCamelCase_, UpperCamelCase_) else our_outputs.last_hidden_state ) __lowercase = from_model(UpperCamelCase_) __lowercase = from_output[-1] if type(UpperCamelCase_) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: __lowercase = our_outputs.hidden_states[-1] assert torch.allclose(UpperCamelCase_, UpperCamelCase_), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message="Add model", use_temp_dir=UpperCamelCase_, ) __lowercase = 224 if "seer" not in name else 384 # we can use the convnext one __lowercase = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k", size=UpperCamelCase_) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message="Add image processor", use_temp_dir=UpperCamelCase_, ) print(F"""Pushed {name}""") def _A ( UpperCamelCase_ : Path, UpperCamelCase_ : str = None, UpperCamelCase_ : bool = True) -> List[str]: '''simple docstring''' __lowercase = "imagenet-1k-id2label.json" __lowercase = 1000 __lowercase = (1, num_labels) __lowercase = "huggingface/label-files" __lowercase = num_labels __lowercase = json.load(open(cached_download(hf_hub_url(UpperCamelCase_, UpperCamelCase_, repo_type="dataset")), "r")) __lowercase = {int(UpperCamelCase_): v for k, v in idalabel.items()} __lowercase = idalabel __lowercase = {v: k for k, v in idalabel.items()} __lowercase = partial(UpperCamelCase_, num_labels=UpperCamelCase_, idalabel=UpperCamelCase_, labelaid=UpperCamelCase_) __lowercase = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type="x"), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type="x"), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type="x"), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type="x"), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type="x"), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type="x"), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type="x"), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type="x"), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type="x"), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type="x"), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type="x"), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type="x"), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010), } __lowercase = NameToOurModelFuncMap() __lowercase = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(UpperCamelCase_ : str, UpperCamelCase_ : Callable[[], nn.Module]) -> Tuple[nn.Module, Dict]: __lowercase = torch.hub.load_state_dict_from_url(UpperCamelCase_, model_dir=str(UpperCamelCase_), map_location="cpu") __lowercase = model_func() # check if we have a head, if yes add it __lowercase = files["classy_state_dict"]["base_model"]["model"] __lowercase = model_state_dict["trunk"] model.load_state_dict(UpperCamelCase_) return model.eval(), model_state_dict["heads"] # pretrained __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch", lambda: FakeRegNetVisslWrapper(RegNetYaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch", lambda: FakeRegNetVisslWrapper(RegNetYaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch", lambda: FakeRegNetVisslWrapper(RegNetYaaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch", lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52))), ) # IN1K finetuned __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch", lambda: FakeRegNetVisslWrapper(RegNetYaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch", lambda: FakeRegNetVisslWrapper(RegNetYaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch", lambda: FakeRegNetVisslWrapper(RegNetYaaagf()), ) __lowercase = partial( UpperCamelCase_, "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch", lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52))), ) if model_name: convert_weight_and_push( UpperCamelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], UpperCamelCase_, UpperCamelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( UpperCamelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], UpperCamelCase_, UpperCamelCase_, UpperCamelCase_, ) return config, expected_shape if __name__ == "__main__": _a = 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 regnet* architecture,' ' currently: regnetx-*, regnety-*. 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 = parser.parse_args() _a = 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)
17
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
import numpy # List of input, output pairs __lowerCamelCase : List[Any] = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) __lowerCamelCase : Dict = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) __lowerCamelCase : List[str] = [2, 4, 1, 5] __lowerCamelCase : int = len(train_data) __lowerCamelCase : str = 0.009 def _snake_case ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : Dict="train" ): """simple docstring""" return calculate_hypothesis_value(lowerCAmelCase , lowerCAmelCase ) - output( lowerCAmelCase , lowerCAmelCase ) def _snake_case ( lowerCAmelCase : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : int = 0 for i in range(len(lowerCAmelCase ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def _snake_case ( lowerCAmelCase : Union[str, Any] , lowerCAmelCase : List[str] ): """simple docstring""" if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def _snake_case ( lowerCAmelCase : Tuple , lowerCAmelCase : Tuple ): """simple docstring""" if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : str=m ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = 0 for i in range(lowerCAmelCase ): if index == -1: summation_value += _error(lowerCAmelCase ) else: summation_value += _error(lowerCAmelCase ) * train_data[i][0][index] return summation_value def _snake_case ( lowerCAmelCase : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = summation_of_cost_derivative(lowerCAmelCase , lowerCAmelCase ) / m return cost_derivative_value def _snake_case ( ): """simple docstring""" global parameter_vector # Tune these values to set a tolerance value for predicted output SCREAMING_SNAKE_CASE_ : List[str] = 0.000002 SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : str = 0 while True: j += 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = [0, 0, 0, 0] for i in range(0 , len(lowerCAmelCase ) ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = get_cost_derivative(i - 1 ) SCREAMING_SNAKE_CASE_ : Optional[int] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( lowerCAmelCase , lowerCAmelCase , atol=lowerCAmelCase , rtol=lowerCAmelCase , ): break SCREAMING_SNAKE_CASE_ : Union[str, Any] = temp_parameter_vector print(("Number of iterations:", j) ) def _snake_case ( ): """simple docstring""" for i in range(len(lowerCAmelCase ) ): print(("Actual output value:", output(lowerCAmelCase , "test" )) ) print(("Hypothesis output:", calculate_hypothesis_value(lowerCAmelCase , "test" )) ) if __name__ == "__main__": run_gradient_descent() print('''\nTesting gradient descent for a linear hypothesis function.\n''') test_gradient_descent()
18
'''simple docstring''' import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ), f"""{len(UpperCamelCase__ )} != {len(UpperCamelCase__ )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __UpperCAmelCase ={ # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __UpperCAmelCase ={ # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: try: __lowerCamelCase = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" f""" {n_student}""" ) return list(range(UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[int]: if n_student > n_teacher: raise ValueError(f"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(UpperCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = "student" , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__=False , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __lowerCamelCase = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(UpperCamelCase__ , UpperCamelCase__ ): AutoTokenizer.from_pretrained(UpperCamelCase__ ).save_pretrained(UpperCamelCase__ ) # purely for convenience __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ).eval() else: assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), f"""teacher must be a model or string got type {type(UpperCamelCase__ )}""" __lowerCamelCase = teacher.config.to_diff_dict() try: __lowerCamelCase , __lowerCamelCase = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): __lowerCamelCase , __lowerCamelCase = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __lowerCamelCase , __lowerCamelCase = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(UpperCamelCase__ ) # Copy weights __lowerCamelCase = teacher.config_class(**UpperCamelCase__ ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_config(UpperCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __lowerCamelCase = student.load_state_dict(teacher.state_dict() , strict=UpperCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __lowerCamelCase , __lowerCamelCase = list(range(UpperCamelCase__ ) ), list(range(UpperCamelCase__ ) ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" f""" {save_path}""" ) student.save_pretrained(UpperCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) if d_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) try: if hasattr( UpperCamelCase__ , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , UpperCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , UpperCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , UpperCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , UpperCamelCase__ ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __lowerCamelCase = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(UpperCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
67
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def lowerCamelCase_ ( lowerCamelCase__ ): return (data["data"], data["target"]) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = XGBClassifier() classifier.fit(lowerCamelCase__ , lowerCamelCase__ ) return classifier def lowerCamelCase_ ( ): lowerCamelCase_ = load_iris() lowerCamelCase_ , lowerCamelCase_ = data_handling(lowerCamelCase__ ) lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = train_test_split( lowerCamelCase__ , lowerCamelCase__ , test_size=0.25 ) lowerCamelCase_ = iris["target_names"] # Create an XGBoost Classifier from the training data lowerCamelCase_ = xgboost(lowerCamelCase__ , lowerCamelCase__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , display_labels=lowerCamelCase__ , cmap="Blues" , normalize="true" , ) plt.title("Normalized Confusion Matrix - IRIS Dataset" ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
19
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __UpperCAmelCase =["gpt2"] __UpperCAmelCase ="gpt2" if is_tf_available(): class a__ ( tf.Module ): def __init__( self : str , a : Union[str, Any] ): """simple docstring""" super().__init__() __lowerCamelCase = tokenizer __lowerCamelCase = AutoConfig.from_pretrained(a ) __lowerCamelCase = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = self.tokenizer(a ) __lowerCamelCase = tokenized['''input_ids'''].to_tensor() __lowerCamelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase = self.model(input_ids=a , attention_mask=a )['''logits'''] return outputs @require_tf @require_keras_nlp class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" super().setUp() __lowerCamelCase = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowerCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase = tokenizer([test_inputs] , return_tensors='''tf''' ) __lowerCamelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase = python_outputs[key].numpy() __lowerCamelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase = tf.constant(a ) __lowerCamelCase = compiled_tokenizer(a ) __lowerCamelCase = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = ModelToSave(tokenizer=a ) __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase = Path(a ) / '''saved.model''' tf.saved_model.save(a , a , signatures={'''serving_default''': model.serving} ) __lowerCamelCase = tf.saved_model.load(a ) __lowerCamelCase = loaded_model.signatures['''serving_default'''](a )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase = tf_tokenizer.get_config() __lowerCamelCase = TFGPTaTokenizer.from_config(a ) __lowerCamelCase = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase = 12_31_23 for max_length in [3, 5, 10_24]: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a , max_length=a ) __lowerCamelCase = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
67
0
class __snake_case : def __init__( self ,snake_case ): '''simple docstring''' lowercase : List[str] = size lowercase : List[Any] = [0] * size lowercase : Optional[int] = [0] * size @staticmethod def _SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' return index | (index + 1) @staticmethod def _SCREAMING_SNAKE_CASE ( snake_case ): '''simple docstring''' return (index & (index + 1)) - 1 def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' lowercase : List[str] = value while index < self.size: lowercase : Optional[Any] = self.get_prev(snake_case ) + 1 if current_left_border == index: lowercase : List[Any] = value else: lowercase : List[str] = max(snake_case ,snake_case ,snake_case ) lowercase : int = self.get_next(snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' right -= 1 # Because of right is exclusive lowercase : List[Any] = 0 while left <= right: lowercase : Optional[Any] = self.get_prev(snake_case ) if left <= current_left: lowercase : Dict = max(snake_case ,self.tree[right] ) lowercase : Any = current_left else: lowercase : str = max(snake_case ,self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
20
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
67
0
import heapq def UpperCamelCase_( lowerCamelCase_ ) -> set[int]: _lowercase : list[list] = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowerCamelCase_ , [-1 * len(lowerCamelCase_ ), (key, value)] ) # chosen_vertices = set of chosen vertices _lowercase : List[str] = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices _lowercase : Any = heapq.heappop(lowerCamelCase_ )[1][0] chosen_vertices.add(lowerCamelCase_ ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: _lowercase : List[str] = elem[1][1].index(lowerCamelCase_ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowerCamelCase_ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE : Dict = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}")
21
'''simple docstring''' import logging import os from .state import PartialState class a__ ( logging.LoggerAdapter ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a : Optional[Any] ): """simple docstring""" __lowerCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[int] , a : str , *a : Optional[int] , **a : List[Any] ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __lowerCamelCase = kwargs.pop('''main_process_only''' , a ) __lowerCamelCase = kwargs.pop('''in_order''' , a ) if self.isEnabledFor(a ): if self._should_log(a ): __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) elif in_order: __lowerCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) state.wait_for_everyone() def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = None ) -> Optional[int]: if log_level is None: __lowerCamelCase = os.environ.get('''ACCELERATE_LOG_LEVEL''' , UpperCamelCase__ ) __lowerCamelCase = logging.getLogger(UpperCamelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(UpperCamelCase__ , {} )
67
0
'''simple docstring''' import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset __SCREAMING_SNAKE_CASE :int = '''bert-base-cased''' __SCREAMING_SNAKE_CASE :Any = '''google/pegasus-xsum''' __SCREAMING_SNAKE_CASE :Optional[int] = [''' Sam ate lunch today.''', '''Sams lunch ingredients.'''] __SCREAMING_SNAKE_CASE :Union[str, Any] = ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee'''] __SCREAMING_SNAKE_CASE :str = '''patrickvonplaten/t5-tiny-random''' __SCREAMING_SNAKE_CASE :List[Any] = '''sshleifer/bart-tiny-random''' __SCREAMING_SNAKE_CASE :List[str] = '''sshleifer/tiny-mbart''' __SCREAMING_SNAKE_CASE :Dict = '''sshleifer/tiny-marian-en-de''' def UpperCAmelCase_ ( __lowercase : Path , __lowercase : list ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = "\n".join(__lowercase ) Path(__lowercase ).open("w" ).writelines(__lowercase ) def UpperCAmelCase_ ( __lowercase : List[str] ) -> Any: '''simple docstring''' for split in ["train", "val", "test"]: _dump_articles(os.path.join(__lowercase , f'{split}.source' ) , __lowercase ) _dump_articles(os.path.join(__lowercase , f'{split}.target' ) , __lowercase ) return tmp_dir class A_ ( lowerCAmelCase_ ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def lowercase ( self : str , snake_case_ : str ): _UpperCAmelCase = AutoTokenizer.from_pretrained(snake_case_ ) _UpperCAmelCase = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _UpperCAmelCase = max(len(tokenizer.encode(snake_case_ ) ) for a in ARTICLES ) _UpperCAmelCase = max(len(tokenizer.encode(snake_case_ ) ) for a in SUMMARIES ) _UpperCAmelCase = 4 _UpperCAmelCase = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _UpperCAmelCase , _UpperCAmelCase = "ro_RO", "de_DE" # ignored for all but mbart, but never causes error. _UpperCAmelCase = SeqaSeqDataset( snake_case_ , data_dir=snake_case_ , type_path="train" , max_source_length=snake_case_ , max_target_length=snake_case_ , src_lang=snake_case_ , tgt_lang=snake_case_ , ) _UpperCAmelCase = DataLoader(snake_case_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(snake_case_ , snake_case_ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _UpperCAmelCase = shift_tokens_right(batch["labels"] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def lowercase ( self : Union[str, Any] , snake_case_ : List[Any] ): _UpperCAmelCase = AutoTokenizer.from_pretrained(snake_case_ ) _UpperCAmelCase = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _UpperCAmelCase = max(len(tokenizer.encode(snake_case_ ) ) for a in ARTICLES ) _UpperCAmelCase = max(len(tokenizer.encode(snake_case_ ) ) for a in SUMMARIES ) _UpperCAmelCase = 4 _UpperCAmelCase = LegacySeqaSeqDataset( snake_case_ , data_dir=snake_case_ , type_path="train" , max_source_length=2_0 , max_target_length=snake_case_ , ) _UpperCAmelCase = DataLoader(snake_case_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def lowercase ( self : Any ): _UpperCAmelCase = AutoTokenizer.from_pretrained("facebook/mbart-large-cc25" ) _UpperCAmelCase = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) _UpperCAmelCase = tmp_dir.joinpath("train.source" ).open().readlines() _UpperCAmelCase = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(snake_case_ , snake_case_ , 1_2_8 , snake_case_ ) _UpperCAmelCase = {x.name for x in tmp_dir.iterdir()} _UpperCAmelCase = {x.name for x in save_dir.iterdir()} _UpperCAmelCase = save_dir.joinpath("train.source" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(snake_case_ ) < len(snake_case_ ) assert len(snake_case_ ) == 1 assert len(packed_examples[0] ) == sum(len(snake_case_ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="This test requires fairseq" ) def lowercase ( self : Optional[int] ): if not FAIRSEQ_AVAILABLE: return _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self._get_dataset(max_len=6_4 ) _UpperCAmelCase = 6_4 _UpperCAmelCase = ds.make_dynamic_sampler(snake_case_ , required_batch_size_multiple=snake_case_ ) _UpperCAmelCase = [len(snake_case_ ) for x in batch_sampler] assert len(set(snake_case_ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(snake_case_ ) == len(snake_case_ ) # no dropped or added examples _UpperCAmelCase = DataLoader(snake_case_ , batch_sampler=snake_case_ , collate_fn=ds.collate_fn , num_workers=2 ) _UpperCAmelCase = [] _UpperCAmelCase = [] for batch in data_loader: _UpperCAmelCase = batch["input_ids"].shape _UpperCAmelCase = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _UpperCAmelCase = np.product(batch["input_ids"].shape ) num_src_per_batch.append(snake_case_ ) if num_src_tokens > (max_tokens * 1.1): failures.append(snake_case_ ) assert num_src_per_batch[0] == max(snake_case_ ) if failures: raise AssertionError(f'too many tokens in {len(snake_case_ )} batches' ) def lowercase ( self : Optional[Any] ): _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self._get_dataset(max_len=5_1_2 ) _UpperCAmelCase = 2 _UpperCAmelCase = ds.make_sortish_sampler(snake_case_ , shuffle=snake_case_ ) _UpperCAmelCase = DataLoader(snake_case_ , batch_size=snake_case_ , collate_fn=ds.collate_fn , num_workers=2 ) _UpperCAmelCase = DataLoader(snake_case_ , batch_size=snake_case_ , collate_fn=ds.collate_fn , num_workers=2 , sampler=snake_case_ ) _UpperCAmelCase = tokenizer.pad_token_id def count_pad_tokens(snake_case_ : List[Any] , snake_case_ : Dict="input_ids" ): return [batch[k].eq(snake_case_ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(snake_case_ , k="labels" ) ) < sum(count_pad_tokens(snake_case_ , k="labels" ) ) assert sum(count_pad_tokens(snake_case_ ) ) < sum(count_pad_tokens(snake_case_ ) ) assert len(snake_case_ ) == len(snake_case_ ) def lowercase ( self : List[Any] , snake_case_ : List[str]=1_0_0_0 , snake_case_ : List[Any]=1_2_8 ): if os.getenv("USE_REAL_DATA" , snake_case_ ): _UpperCAmelCase = "examples/seq2seq/wmt_en_ro" _UpperCAmelCase = max_len * 2 * 6_4 if not Path(snake_case_ ).joinpath("train.len" ).exists(): save_len_file(snake_case_ , snake_case_ ) else: _UpperCAmelCase = "examples/seq2seq/test_data/wmt_en_ro" _UpperCAmelCase = max_len * 4 save_len_file(snake_case_ , snake_case_ ) _UpperCAmelCase = AutoTokenizer.from_pretrained(snake_case_ ) _UpperCAmelCase = SeqaSeqDataset( snake_case_ , data_dir=snake_case_ , type_path="train" , max_source_length=snake_case_ , max_target_length=snake_case_ , n_obs=snake_case_ , ) return ds, max_tokens, tokenizer def lowercase ( self : List[Any] ): _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self._get_dataset() _UpperCAmelCase = set(DistributedSortishSampler(snake_case_ , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=snake_case_ ) ) _UpperCAmelCase = set(DistributedSortishSampler(snake_case_ , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=snake_case_ ) ) assert idsa.intersection(snake_case_ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def lowercase ( self : str , snake_case_ : Union[str, Any] ): _UpperCAmelCase = AutoTokenizer.from_pretrained(snake_case_ , use_fast=snake_case_ ) if tok_name == MBART_TINY: _UpperCAmelCase = SeqaSeqDataset( snake_case_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , src_lang="EN" , tgt_lang="FR" , ) _UpperCAmelCase = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _UpperCAmelCase = SeqaSeqDataset( snake_case_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="train" , max_source_length=4 , max_target_length=8 , ) _UpperCAmelCase = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(snake_case_ ) == 1 if tok_name == BART_TINY else len(snake_case_ ) == 0
22
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = set({'''(''', '''[''', '''{'''} ) __lowerCamelCase = set({''')''', ''']''', '''}'''} ) __lowerCamelCase = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def __lowerCAmelCase ( ) -> str: __lowerCamelCase = input('''Enter sequence of brackets: ''' ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , '''is balanced''' ) else: print(UpperCamelCase__ , '''is not balanced''' ) if __name__ == "__main__": main()
67
0
'''simple docstring''' def snake_case_ ( _lowerCAmelCase : int ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") UpperCamelCase__: int = int(input("Enter number: ").strip()) print(F"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
23
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict ="M-CLIP" def __init__( self : Tuple , a : Optional[int]=10_24 , a : Tuple=7_68 , **a : List[str] ): """simple docstring""" __lowerCamelCase = transformerDimSize __lowerCamelCase = imageDimSize super().__init__(**a ) class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =MCLIPConfig def __init__( self : str , a : List[Any] , *a : Dict , **a : str ): """simple docstring""" super().__init__(a , *a , **a ) __lowerCamelCase = XLMRobertaModel(a ) __lowerCamelCase = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.transformer(input_ids=a , attention_mask=a )[0] __lowerCamelCase = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a ), embs
67
0
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): A_ : Union[str, Any] = AutoencoderKL A_ : List[Any] = 'sample' A_ : List[Any] = 1e-2 @property def a (self : Dict ): """simple docstring""" __snake_case = 4 __snake_case = 3 __snake_case = (32, 32) __snake_case = floats_tensor((batch_size, num_channels) + sizes ).to(a__ ) return {"sample": image} @property def a (self : Any ): """simple docstring""" return (3, 32, 32) @property def a (self : Optional[Any] ): """simple docstring""" return (3, 32, 32) def a (self : int ): """simple docstring""" __snake_case = { '''block_out_channels''': [32, 64], '''in_channels''': 3, '''out_channels''': 3, '''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''], '''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''], '''latent_channels''': 4, } __snake_case = self.dummy_input return init_dict, inputs_dict def a (self : Tuple ): """simple docstring""" pass def a (self : int ): """simple docstring""" pass @unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''' ) def a (self : int ): """simple docstring""" __snake_case , __snake_case = self.prepare_init_args_and_inputs_for_common() __snake_case = self.model_class(**a__ ) model.to(a__ ) assert not model.is_gradient_checkpointing and model.training __snake_case = model(**a__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __snake_case = torch.randn_like(a__ ) __snake_case = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case = self.model_class(**a__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(a__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case = model_a(**a__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __snake_case = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case = dict(model.named_parameters() ) __snake_case = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def a (self : Tuple ): """simple docstring""" __snake_case , __snake_case = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=a__ ) self.assertIsNotNone(a__ ) self.assertEqual(len(loading_info['''missing_keys'''] ) , 0 ) model.to(a__ ) __snake_case = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def a (self : Union[str, Any] ): """simple docstring""" __snake_case = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' ) __snake_case = model.to(a__ ) model.eval() if torch_device == "mps": __snake_case = torch.manual_seed(0 ) else: __snake_case = torch.Generator(device=a__ ).manual_seed(0 ) __snake_case = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case = image.to(a__ ) with torch.no_grad(): __snake_case = model(a__ , sample_posterior=a__ , generator=a__ ).sample __snake_case = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __snake_case = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __snake_case = torch.tensor( [-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6] ) else: __snake_case = torch.tensor( [-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5] ) self.assertTrue(torch_all_close(a__ , a__ , rtol=1E-2 ) ) @slow class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def a (self : Tuple , a__ : Optional[Any] , a__ : List[str] ): """simple docstring""" return f"""gaussian_noise_s={seed}_shape={'_'.join([str(a__ ) for s in shape] )}.npy""" def a (self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def a (self : Optional[int] , a__ : Optional[Any]=0 , a__ : List[Any]=(4, 3, 512, 512) , a__ : Optional[Any]=False ): """simple docstring""" __snake_case = torch.floataa if fpaa else torch.floataa __snake_case = torch.from_numpy(load_hf_numpy(self.get_file_format(a__ , a__ ) ) ).to(a__ ).to(a__ ) return image def a (self : Optional[Any] , a__ : Dict="CompVis/stable-diffusion-v1-4" , a__ : List[Any]=False ): """simple docstring""" __snake_case = '''fp16''' if fpaa else None __snake_case = torch.floataa if fpaa else torch.floataa __snake_case = AutoencoderKL.from_pretrained( a__ , subfolder='''vae''' , torch_dtype=a__ , revision=a__ , ) model.to(a__ ).eval() return model def a (self : Union[str, Any] , a__ : int=0 ): """simple docstring""" if torch_device == "mps": return torch.manual_seed(a__ ) return torch.Generator(device=a__ ).manual_seed(a__ ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def a (self : Optional[int] , a__ : int , a__ : Union[str, Any] , a__ : Optional[int] ): """simple docstring""" __snake_case = self.get_sd_vae_model() __snake_case = self.get_sd_image(a__ ) __snake_case = self.get_generator(a__ ) with torch.no_grad(): __snake_case = model(a__ , generator=a__ , sample_posterior=a__ ).sample assert sample.shape == image.shape __snake_case = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(a__ , a__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]], [47, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]], # fmt: on ] ) @require_torch_gpu def a (self : Union[str, Any] , a__ : Union[str, Any] , a__ : str ): """simple docstring""" __snake_case = self.get_sd_vae_model(fpaa=a__ ) __snake_case = self.get_sd_image(a__ , fpaa=a__ ) __snake_case = self.get_generator(a__ ) with torch.no_grad(): __snake_case = model(a__ , generator=a__ , sample_posterior=a__ ).sample assert sample.shape == image.shape __snake_case = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case = torch.tensor(a__ ) assert torch_all_close(a__ , a__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def a (self : Optional[Any] , a__ : str , a__ : Tuple , a__ : List[Any] ): """simple docstring""" __snake_case = self.get_sd_vae_model() __snake_case = self.get_sd_image(a__ ) with torch.no_grad(): __snake_case = model(a__ ).sample assert sample.shape == image.shape __snake_case = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice ) assert torch_all_close(a__ , a__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]], [37, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]], # fmt: on ] ) @require_torch_gpu def a (self : str , a__ : Optional[int] , a__ : Any ): """simple docstring""" __snake_case = self.get_sd_vae_model() __snake_case = self.get_sd_image(a__ , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case = model.decode(a__ ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case = torch.tensor(a__ ) assert torch_all_close(a__ , a__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]], [16, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]], # fmt: on ] ) @require_torch_gpu def a (self : List[Any] , a__ : Any , a__ : Optional[int] ): """simple docstring""" __snake_case = self.get_sd_vae_model(fpaa=a__ ) __snake_case = self.get_sd_image(a__ , shape=(3, 4, 64, 64) , fpaa=a__ ) with torch.no_grad(): __snake_case = model.decode(a__ ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case = torch.tensor(a__ ) assert torch_all_close(a__ , a__ , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def a (self : Tuple , a__ : Any ): """simple docstring""" __snake_case = self.get_sd_vae_model(fpaa=a__ ) __snake_case = self.get_sd_image(a__ , shape=(3, 4, 64, 64) , fpaa=a__ ) with torch.no_grad(): __snake_case = model.decode(a__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case = model.decode(a__ ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(a__ , a__ , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''' ) def a (self : int , a__ : Optional[int] ): """simple docstring""" __snake_case = self.get_sd_vae_model() __snake_case = self.get_sd_image(a__ , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case = model.decode(a__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case = model.decode(a__ ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(a__ , a__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]], [47, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]], # fmt: on ] ) def a (self : str , a__ : Optional[Any] , a__ : List[str] ): """simple docstring""" __snake_case = self.get_sd_vae_model() __snake_case = self.get_sd_image(a__ ) __snake_case = self.get_generator(a__ ) with torch.no_grad(): __snake_case = model.encode(a__ ).latent_dist __snake_case = dist.sample(generator=a__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case = torch.tensor(a__ ) __snake_case = 3E-3 if torch_device != '''mps''' else 1E-2 assert torch_all_close(a__ , a__ , atol=a__ )
24
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
67
0
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = 384 SCREAMING_SNAKE_CASE__ : Tuple = 7 if "tiny" in model_name: SCREAMING_SNAKE_CASE__ : int = 96 SCREAMING_SNAKE_CASE__ : str = (2, 2, 6, 2) SCREAMING_SNAKE_CASE__ : List[Any] = (3, 6, 12, 24) elif "small" in model_name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 96 SCREAMING_SNAKE_CASE__ : Any = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : Tuple = (3, 6, 12, 24) elif "base" in model_name: SCREAMING_SNAKE_CASE__ : Tuple = 128 SCREAMING_SNAKE_CASE__ : List[Any] = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : int = (4, 8, 16, 32) SCREAMING_SNAKE_CASE__ : Optional[int] = 12 SCREAMING_SNAKE_CASE__ : Optional[int] = 512 elif "large" in model_name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 192 SCREAMING_SNAKE_CASE__ : int = (2, 2, 18, 2) SCREAMING_SNAKE_CASE__ : int = (6, 12, 24, 48) SCREAMING_SNAKE_CASE__ : List[Any] = 12 SCREAMING_SNAKE_CASE__ : Optional[Any] = 768 # set label information SCREAMING_SNAKE_CASE__ : Optional[Any] = 150 SCREAMING_SNAKE_CASE__ : Tuple = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ : List[str] = """ade20k-id2label.json""" SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(_snake_case ,_snake_case ,repo_type="""dataset""" ) ,"""r""" ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(_snake_case ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[Any] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = SwinConfig( embed_dim=_snake_case ,depths=_snake_case ,num_heads=_snake_case ,window_size=_snake_case ,out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ,) SCREAMING_SNAKE_CASE__ : int = UperNetConfig( backbone_config=_snake_case ,auxiliary_in_channels=_snake_case ,num_labels=_snake_case ,idalabel=_snake_case ,labelaid=_snake_case ,) return config def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [] # fmt: off # stem rename_keys.append(("""backbone.patch_embed.projection.weight""", """backbone.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.projection.bias""", """backbone.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """backbone.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """backbone.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((f'''backbone.stages.{i}.downsample.reduction.weight''', f'''backbone.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.weight''', f'''backbone.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((f'''backbone.stages.{i}.downsample.norm.bias''', f'''backbone.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') ) rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') ) # decode head rename_keys.extend( [ ("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""), ("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""), ("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""), ("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""), ] ) # fmt: on return rename_keys def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : Optional[Any] = dct.pop(_snake_case ) SCREAMING_SNAKE_CASE__ : Tuple = val def lowercase_ ( _snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : int = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : List[Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[:dim, :] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[: dim] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ dim : dim * 2 ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_weight[ -dim :, : ] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_bias[-dim :] # fmt: on def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = x.shape SCREAMING_SNAKE_CASE__ : List[Any] = x.reshape(_snake_case ,4 ,in_channel // 4 ) SCREAMING_SNAKE_CASE__ : Dict = x[:, [0, 2, 1, 3], :].transpose(1 ,2 ).reshape(_snake_case ,_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = x.shape SCREAMING_SNAKE_CASE__ : Any = x.reshape(_snake_case ,in_channel // 4 ,4 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = x[:, :, [0, 2, 1, 3]].transpose(1 ,2 ).reshape(_snake_case ,_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : Tuple = x.shape[0] SCREAMING_SNAKE_CASE__ : List[str] = x.reshape(4 ,in_channel // 4 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = x[[0, 2, 1, 3], :].transpose(0 ,1 ).reshape(_snake_case ) return x def lowercase_ ( _snake_case ): SCREAMING_SNAKE_CASE__ : int = x.shape[0] SCREAMING_SNAKE_CASE__ : List[str] = x.reshape(in_channel // 4 ,4 ) SCREAMING_SNAKE_CASE__ : Tuple = x[:, [0, 2, 1, 3]].transpose(0 ,1 ).reshape(_snake_case ) return x def lowercase_ ( _snake_case ,_snake_case ,_snake_case ): SCREAMING_SNAKE_CASE__ : List[Any] = { """upernet-swin-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth""", """upernet-swin-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth""", """upernet-swin-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth""", """upernet-swin-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth""", } SCREAMING_SNAKE_CASE__ : Optional[int] = model_name_to_url[model_name] SCREAMING_SNAKE_CASE__ : Optional[int] = torch.hub.load_state_dict_from_url(_snake_case ,map_location="""cpu""" ,file_name=_snake_case )[ """state_dict""" ] for name, param in state_dict.items(): print(_snake_case ,param.shape ) SCREAMING_SNAKE_CASE__ : Optional[Any] = get_upernet_config(_snake_case ) SCREAMING_SNAKE_CASE__ : List[str] = UperNetForSemanticSegmentation(_snake_case ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(_snake_case ) if "bn" in key: SCREAMING_SNAKE_CASE__ : Optional[int] = key.replace("""bn""" ,"""batch_norm""" ) SCREAMING_SNAKE_CASE__ : Dict = val # rename keys SCREAMING_SNAKE_CASE__ : str = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case ,_snake_case ,_snake_case ) read_in_q_k_v(_snake_case ,config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] = reverse_correct_unfold_reduction_order(_snake_case ) if "norm" in key: SCREAMING_SNAKE_CASE__ : Tuple = reverse_correct_unfold_norm_order(_snake_case ) model.load_state_dict(_snake_case ) # verify on image SCREAMING_SNAKE_CASE__ : List[str] = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg""" SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(_snake_case ,stream=_snake_case ).raw ).convert("""RGB""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SegformerImageProcessor() SCREAMING_SNAKE_CASE__ : Optional[int] = processor(_snake_case ,return_tensors="""pt""" ).pixel_values with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Tuple = model(_snake_case ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits print(logits.shape ) print("""First values of logits:""" ,logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ) elif model_name == "upernet-swin-small": SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor( [[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]] ) elif model_name == "upernet-swin-base": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]] ) elif model_name == "upernet-swin-large": SCREAMING_SNAKE_CASE__ : Dict = torch.tensor( [[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]] ) print("""Logits:""" ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,_snake_case ,atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_snake_case ) if push_to_hub: print(f'''Pushing model and processor for {model_name} to hub''' ) model.push_to_hub(f'''openmmlab/{model_name}''' ) processor.push_to_hub(f'''openmmlab/{model_name}''' ) if __name__ == "__main__": UpperCAmelCase__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='upernet-swin-tiny', type=str, choices=[f"""upernet-swin-{size}""" for size in ['tiny', 'small', 'base', 'large']], help='Name of the Swin + UperNet model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) UpperCAmelCase__ : List[str] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
25
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
from math import isclose, sqrt def lowerCAmelCase_ ( snake_case_,snake_case_,snake_case_ ): _A : str = point_y / 4 / point_x _A : Any = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) _A : Dict = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) _A : Optional[int] = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 _A : List[Any] = outgoing_gradient**2 + 4 _A : Union[str, Any] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) _A : List[str] = (point_y - outgoing_gradient * point_x) ** 2 - 100 _A : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) _A : int = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point _A : Optional[int] = x_minus if isclose(snake_case_,snake_case_ ) else x_plus _A : str = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def lowerCAmelCase_ ( snake_case_ = 1.4,snake_case_ = -9.6 ): _A : int = 0 _A : float = first_x_coord _A : float = first_y_coord _A : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): _A , _A , _A : Tuple = next_point(snake_case_,snake_case_,snake_case_ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"""{solution() = }""")
26
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
0
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def lowerCamelCase (_SCREAMING_SNAKE_CASE : int ): __a : Tuple = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCamelCase (_SCREAMING_SNAKE_CASE : Optional[Any] ): __a , __a : Dict = emb.weight.shape __a : Optional[Any] = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE ) __a : Tuple = emb.weight.data return lin_layer def lowerCamelCase (_SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : Union[str, Any]="facebook/mbart-large-en-ro" , _SCREAMING_SNAKE_CASE : int=False , _SCREAMING_SNAKE_CASE : Tuple=False ): __a : Tuple = torch.load(_SCREAMING_SNAKE_CASE , map_location='cpu' )['model'] remove_ignore_keys_(_SCREAMING_SNAKE_CASE ) __a : Optional[Any] = state_dict['encoder.embed_tokens.weight'].shape[0] __a : int = MBartConfig.from_pretrained(_SCREAMING_SNAKE_CASE , vocab_size=_SCREAMING_SNAKE_CASE ) if mbart_aa and finetuned: __a : Union[str, Any] = 'relu' __a : Tuple = state_dict['decoder.embed_tokens.weight'] __a : Union[str, Any] = MBartForConditionalGeneration(_SCREAMING_SNAKE_CASE ) model.model.load_state_dict(_SCREAMING_SNAKE_CASE ) if finetuned: __a : int = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": __lowercase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') __lowercase : Any = parser.parse_args() __lowercase : int = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
27
'''simple docstring''' 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_barthez import BarthezTokenizer else: __UpperCAmelCase =None __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __UpperCAmelCase ={ "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } __UpperCAmelCase ={ "moussaKam/mbarthez": 1_0_2_4, "moussaKam/barthez": 1_0_2_4, "moussaKam/barthez-orangesum-title": 1_0_2_4, } __UpperCAmelCase ="▁" class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] =["input_ids", "attention_mask"] lowerCamelCase : Union[str, Any] =BarthezTokenizer def __init__( self : Optional[Any] , a : Dict=None , a : str=None , a : List[Any]="<s>" , a : Optional[int]="</s>" , a : List[str]="</s>" , a : Tuple="<s>" , a : str="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , **a : Union[str, Any] , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Optional[str] = None ): """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(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
67
0
'''simple docstring''' def __lowerCamelCase ( A__ ) -> bool: """simple docstring""" if not isinstance(A__ , A__ ): UpperCamelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(A__ ) if number < 0: return False UpperCamelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
28
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00_00 ) -> int: __lowerCamelCase = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , UpperCamelCase__ , UpperCamelCase__ ) ) ) __lowerCamelCase = [float(UpperCamelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCamelCase__ , limit + 1 , UpperCamelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'{solution() = }')
67
0
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def lowercase__ ( __snake_case : List[Any] , __snake_case : List[str]=False ): '''simple docstring''' try: UpperCAmelCase_ : int = os.environ[key] except KeyError: # KEY isn't set, default to `default`. UpperCAmelCase_ : Optional[int] = default else: # KEY is set, convert it to True or False. try: UpperCAmelCase_ : List[Any] = strtobool(__snake_case ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"If set, {key} must be yes or no." ) return _value __UpperCAmelCase = parse_flag_from_env('RUN_SLOW', default=False) def lowercase__ ( __snake_case : int ): '''simple docstring''' return unittest.skip('Test was skipped' )(__snake_case ) def lowercase__ ( __snake_case : Tuple ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests , 'test is slow' )(__snake_case ) def lowercase__ ( __snake_case : List[str] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() , 'test requires only a CPU' )(__snake_case ) def lowercase__ ( __snake_case : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() , 'test requires a GPU' )(__snake_case ) def lowercase__ ( __snake_case : List[str] ): '''simple docstring''' return unittest.skipUnless(is_xpu_available() , 'test requires a XPU' )(__snake_case ) def lowercase__ ( __snake_case : str ): '''simple docstring''' return unittest.skipUnless(is_mps_available() , 'test requires a `mps` backend support in `torch`' )(__snake_case ) def lowercase__ ( __snake_case : Tuple ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() , 'test requires the Hugging Face suite' )(__snake_case ) def lowercase__ ( __snake_case : str ): '''simple docstring''' return unittest.skipUnless(is_bnb_available() , 'test requires the bitsandbytes library' )(__snake_case ) def lowercase__ ( __snake_case : Dict ): '''simple docstring''' return unittest.skipUnless(is_tpu_available() , 'test requires TPU' )(__snake_case ) def lowercase__ ( __snake_case : Tuple ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 , 'test requires a GPU' )(__snake_case ) def lowercase__ ( __snake_case : Dict ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 , 'test requires a XPU' )(__snake_case ) def lowercase__ ( __snake_case : Optional[int] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 , 'test requires multiple GPUs' )(__snake_case ) def lowercase__ ( __snake_case : int ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 , 'test requires multiple XPUs' )(__snake_case ) def lowercase__ ( __snake_case : Dict ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available() , 'test requires safetensors' )(__snake_case ) def lowercase__ ( __snake_case : Tuple ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() , 'test requires DeepSpeed' )(__snake_case ) def lowercase__ ( __snake_case : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_torch_version('>=' , '1.12.0' ) , 'test requires torch version >= 1.12.0' )(__snake_case ) def lowercase__ ( __snake_case : Dict=None , __snake_case : Dict=None ): '''simple docstring''' if test_case is None: return partial(__snake_case , version=__snake_case ) return unittest.skipUnless(is_torch_version('>=' , __snake_case ) , F"test requires torch version >= {version}" )(__snake_case ) def lowercase__ ( __snake_case : str ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() , 'test requires Tensorboard' )(__snake_case ) def lowercase__ ( __snake_case : List[str] ): '''simple docstring''' return unittest.skipUnless(is_wandb_available() , 'test requires wandb' )(__snake_case ) def lowercase__ ( __snake_case : str ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() , 'test requires comet_ml' )(__snake_case ) __UpperCAmelCase = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def lowercase__ ( __snake_case : List[Any] ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available , 'test requires at least one tracker to be available and for `comet_ml` to not be installed' , )(__snake_case ) class lowerCamelCase (unittest.TestCase ): '''simple docstring''' _snake_case : Union[str, Any] = True @classmethod def __UpperCAmelCase ( cls ) -> Union[str, Any]: UpperCAmelCase_ : List[Any] = tempfile.mkdtemp() @classmethod def __UpperCAmelCase ( cls ) -> List[str]: if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def __UpperCAmelCase ( self ) -> str: if self.clear_on_setup: for path in Path(self.tmpdir ).glob('**/*' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(_UpperCamelCase ) class lowerCamelCase (unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ) -> Optional[int]: super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class lowerCamelCase (unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self , _UpperCamelCase ) -> Any: UpperCAmelCase_ : List[Any] = mocks if isinstance(_UpperCamelCase , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def lowercase__ ( __snake_case : int ): '''simple docstring''' UpperCAmelCase_ : int = AcceleratorState() UpperCAmelCase_ : str = tensor[None].clone().to(state.device ) UpperCAmelCase_ : List[str] = gather(__snake_case ).cpu() UpperCAmelCase_ : List[Any] = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , __snake_case ): return False return True class lowerCamelCase : '''simple docstring''' def __init__( self , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: UpperCAmelCase_ : str = returncode UpperCAmelCase_ : Optional[Any] = stdout UpperCAmelCase_ : Optional[Any] = stderr async def lowercase__ ( __snake_case : Optional[Any] , __snake_case : Optional[int] ): '''simple docstring''' while True: UpperCAmelCase_ : Dict = await stream.readline() if line: callback(__snake_case ) else: break async def lowercase__ ( __snake_case : Optional[int] , __snake_case : Dict=None , __snake_case : str=None , __snake_case : Dict=None , __snake_case : List[str]=False , __snake_case : Optional[int]=False ): '''simple docstring''' if echo: print('\nRunning: ' , ' '.join(__snake_case ) ) UpperCAmelCase_ : Optional[Any] = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=__snake_case , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=__snake_case , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) UpperCAmelCase_ : Any = [] UpperCAmelCase_ : str = [] def tee(__snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Tuple , __snake_case : Optional[int]="" ): UpperCAmelCase_ : List[str] = line.decode('utf-8' ).rstrip() sink.append(__snake_case ) if not quiet: print(__snake_case , __snake_case , file=__snake_case ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda __snake_case : tee(__snake_case , __snake_case , sys.stdout , label='stdout:' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda __snake_case : tee(__snake_case , __snake_case , sys.stderr , label='stderr:' ) ) ), ] , timeout=__snake_case , ) return _RunOutput(await p.wait() , __snake_case , __snake_case ) def lowercase__ ( __snake_case : Optional[Any] , __snake_case : List[Any]=None , __snake_case : str=None , __snake_case : Tuple=180 , __snake_case : Dict=False , __snake_case : Optional[Any]=True ): '''simple docstring''' UpperCAmelCase_ : str = asyncio.get_event_loop() UpperCAmelCase_ : int = loop.run_until_complete( _stream_subprocess(__snake_case , env=__snake_case , stdin=__snake_case , timeout=__snake_case , quiet=__snake_case , echo=__snake_case ) ) UpperCAmelCase_ : int = ' '.join(__snake_case ) if result.returncode > 0: UpperCAmelCase_ : int = '\n'.join(result.stderr ) raise RuntimeError( F"'{cmd_str}' failed with returncode {result.returncode}\n\n" F"The combined stderr from workers follows:\n{stderr}" ) return result class lowerCamelCase (_snake_case ): '''simple docstring''' pass def lowercase__ ( __snake_case : List[str] , __snake_case : List[Any]=False ): '''simple docstring''' try: UpperCAmelCase_ : List[Any] = subprocess.check_output(__snake_case , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(__snake_case , 'decode' ): UpperCAmelCase_ : str = output.decode('utf-8' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F"Command `{' '.join(__snake_case )}` failed with the following error:\n\n{e.output.decode()}" ) from e
29
'''simple docstring''' 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 a__ : def __init__( self : Union[str, Any] , a : Union[str, Any] , a : Tuple=13 , a : Optional[Any]=7 , a : List[Any]=True , a : Optional[Any]=True , a : Any=True , a : Union[str, Any]=99 , a : Any=32 , a : int=5 , a : Optional[int]=4 , a : Union[str, Any]=37 , a : Optional[Any]="gelu" , a : Union[str, Any]=0.1 , a : Any=0.1 , a : Optional[int]=5_12 , a : int=16 , a : Optional[Any]=2 , a : Union[str, Any]=0.02 , a : Any=3 , a : Dict=4 , a : Any=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = self.vocab_size - 1 def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __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 = 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 , ) __lowerCamelCase = 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 : Union[str, Any] , a : Dict , a : List[str] , a : Tuple , a : List[Any] , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , head_mask=a ) __lowerCamelCase = model(a , token_type_ids=a ) __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Union[str, Any] , a : Dict , a : Union[str, Any] , a : Tuple , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Optional[Any] , *a : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTDoubleHeadsModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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 : List[str] , a : int , a : Dict , a : Optional[Any] , a : str , *a : int ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = OpenAIGPTForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """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, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : List[str] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCamelCase : str =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCamelCase : Optional[int] =( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple , a : Optional[int] , a : int , a : str , a : Any ): """simple docstring""" 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 : Optional[int] , a : int , a : Optional[int] , a : str=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a , ) __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a , ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , n_embd=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = OpenAIGPTModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(a ) __lowerCamelCase = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=a ) # the president is __lowerCamelCase = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the __lowerCamelCase = model.generate(a , do_sample=a ) self.assertListEqual(output_ids[0].tolist() , a )
67
0
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def a ( snake_case__: Optional[int] ): '''simple docstring''' return EnvironmentCommand() class lowercase__( UpperCAmelCase ): """simple docstring""" @staticmethod def _lowercase ( SCREAMING_SNAKE_CASE_ : ArgumentParser ) -> Tuple: lowercase_ = parser.add_parser('''env''' ) download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ ) def _lowercase ( self : Dict ) -> int: lowercase_ = huggingface_hub.__version__ lowercase_ = '''not installed''' lowercase_ = '''NA''' if is_torch_available(): import torch lowercase_ = torch.__version__ lowercase_ = torch.cuda.is_available() lowercase_ = '''not installed''' if is_transformers_available(): import transformers lowercase_ = transformers.__version__ lowercase_ = '''not installed''' if is_accelerate_available(): import accelerate lowercase_ = accelerate.__version__ lowercase_ = '''not installed''' if is_xformers_available(): import xformers lowercase_ = xformers.__version__ lowercase_ = { '''`diffusers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''PyTorch version (GPU?)''': f'''{pt_version} ({pt_cuda_available})''', '''Huggingface_hub version''': hub_version, '''Transformers version''': transformers_version, '''Accelerate version''': accelerate_version, '''xFormers version''': xformers_version, '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(SCREAMING_SNAKE_CASE_ ) ) return info @staticmethod def _lowercase ( SCREAMING_SNAKE_CASE_ : int ) -> Any: return "\n".join([f'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
30
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =["image_processor", "tokenizer"] lowerCamelCase : Union[str, Any] ="LayoutLMv2ImageProcessor" lowerCamelCase : int =("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , a : Any=None , a : Any=None , **a : Union[str, Any] ): """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a , a ) def __call__( self : Tuple , a : Optional[int] , a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a : Union[List[List[int]], List[List[List[int]]]] = None , a : Optional[Union[List[int], List[List[int]]]] = None , a : bool = True , a : Union[bool, str, PaddingStrategy] = False , a : Union[bool, str, TruncationStrategy] = None , a : Optional[int] = None , a : int = 0 , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[bool] = None , a : bool = False , a : bool = False , a : bool = False , a : bool = False , a : bool = True , a : Optional[Union[str, TensorType]] = None , **a : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=a , return_tensors=a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a , a ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features['''words'''] __lowerCamelCase = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel values __lowerCamelCase = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(a , encoded_inputs['''overflow_to_sample_mapping'''] ) __lowerCamelCase = images return encoded_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Optional[Any] , a : str ): """simple docstring""" __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a ) != len(a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(a )} and {len(a )}""" ) return images_with_overflow def SCREAMING_SNAKE_CASE__ ( self : List[str] , *a : Optional[Any] , **a : Union[str, Any] ): """simple docstring""" return self.tokenizer.batch_decode(*a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *a : Union[str, Any] , **a : Tuple ): """simple docstring""" return self.tokenizer.decode(*a , **a ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a , ) return self.image_processor
67
0
'''simple docstring''' import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {"""dataset""": """wikipedia""", """config_name""": """20220301.de"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.en"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.fr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.frr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.it"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.simple"""}, {"""dataset""": """snli""", """config_name""": """plain_text"""}, {"""dataset""": """eli5""", """config_name""": """LFQA_reddit"""}, {"""dataset""": """wiki40b""", """config_name""": """en"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.compressed"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.no_index"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.multiset.no_index"""}, {"""dataset""": """natural_questions""", """config_name""": """default"""}, ] def UpperCamelCase_ ( _UpperCAmelCase : Optional[int]=True ) -> Tuple: """simple docstring""" if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=snake_case__ ) ) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: Optional[Any] = None __UpperCamelCase: int = None def _A ( self : str , A : str , A : List[Any] ): with TemporaryDirectory() as tmp_dir: _UpperCAmelCase : int = dataset_module_factory(A , cache_dir=A ) _UpperCAmelCase : List[Any] = import_main_class(dataset_module.module_path , dataset=A ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=A , config_name=A , hash=dataset_module.hash , ) _UpperCAmelCase : Tuple = "/".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=A ).replace(os.sep , "/" ), config.DATASET_INFO_FILENAME, ] ) _UpperCAmelCase : Optional[Any] = cached_path(A , cache_dir=A ) self.assertTrue(os.path.exists(A ) ) @pytest.mark.integration def UpperCamelCase_ ( _UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" _UpperCAmelCase : int = tmp_path_factory.mktemp("test_hf_gcp" ) / "test_wikipedia_simple" _UpperCAmelCase : Union[str, Any] = dataset_module_factory("wikipedia" , cache_dir=_UpperCAmelCase ) _UpperCAmelCase : str = import_main_class(dataset_module.module_path ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=_UpperCAmelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam _UpperCAmelCase : Dict = None builder_instance.download_and_prepare() _UpperCAmelCase : List[str] = builder_instance.as_dataset() assert ds @pytest.mark.integration def UpperCamelCase_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: """simple docstring""" _UpperCAmelCase : List[str] = dataset_module_factory("wikipedia" , cache_dir=_UpperCAmelCase ) _UpperCAmelCase : List[Any] = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=_UpperCAmelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) _UpperCAmelCase : Dict = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) assert "train" in ds assert isinstance(ds["train"] , _UpperCAmelCase ) assert next(iter(ds["train"] ) )
31
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): """simple docstring""" super().__init__() __lowerCamelCase = nn.ModuleList(a ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : torch.FloatTensor , a : Union[torch.Tensor, float, int] , a : torch.Tensor , a : List[torch.tensor] , a : List[float] , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[Dict[str, Any]] = None , a : bool = False , a : bool = True , ): """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets ) ): __lowerCamelCase , __lowerCamelCase = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: __lowerCamelCase , __lowerCamelCase = down_samples, mid_sample else: __lowerCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self : Any , a : Union[str, os.PathLike] , a : bool = True , a : Callable = None , a : bool = False , a : Optional[str] = None , ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 __lowerCamelCase = model_path_to_save + f"""_{idx}""" @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[str] , a : Optional[Union[str, os.PathLike]] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __lowerCamelCase = pretrained_model_path while os.path.isdir(a ): __lowerCamelCase = ControlNetModel.from_pretrained(a , **a ) controlnets.append(a ) idx += 1 __lowerCamelCase = pretrained_model_path + f"""_{idx}""" logger.info(f"""{len(a )} controlnets loaded from {pretrained_model_path}.""" ) if len(a ) == 0: raise ValueError( f"""No ControlNets found under {os.path.dirname(a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(a )
67
0
def SCREAMING_SNAKE_CASE_ ( __A : str ) -> bool: """simple docstring""" return credit_card_number.startswith(('34', '35', '37', '4', '5', '6') ) def SCREAMING_SNAKE_CASE_ ( __A : str ) -> bool: """simple docstring""" a_ : List[Any] = credit_card_number a_ : Optional[int] = 0 a_ : str = len(__A ) - 2 for i in range(__A , -1 , -2 ): # double the value of every second digit a_ : Union[str, Any] = int(cc_number[i] ) digit *= 2 # If doubling of a number results in a two digit number # i.e greater than 9(e.g., 6 × 2 = 12), # then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6), # to get a single digit number. if digit > 9: digit %= 10 digit += 1 a_ : List[Any] = cc_number[:i] + str(__A ) + cc_number[i + 1 :] total += digit # Sum up the remaining digits for i in range(len(__A ) - 1 , -1 , -2 ): total += int(cc_number[i] ) return total % 10 == 0 def SCREAMING_SNAKE_CASE_ ( __A : str ) -> bool: """simple docstring""" a_ : List[Any] = F"""{credit_card_number} is an invalid credit card number because""" if not credit_card_number.isdigit(): print(F"""{error_message} it has nonnumerical characters.""" ) return False if not 13 <= len(__A ) <= 16: print(F"""{error_message} of its length.""" ) return False if not validate_initial_digits(__A ): print(F"""{error_message} of its first two digits.""" ) return False if not luhn_validation(__A ): print(F"""{error_message} it fails the Luhn check.""" ) return False print(F"""{credit_card_number} is a valid credit card number.""" ) return True if __name__ == "__main__": import doctest doctest.testmod() validate_credit_card_number('4111111111111111') validate_credit_card_number('32323')
32
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class _UpperCAmelCase ( metaclass=_A ): SCREAMING_SNAKE_CASE_ : Any = ["keras_nlp"] def __init__( self : Dict , *A : str , **A : List[str] ) -> str: requires_backends(self , ['''keras_nlp'''] )
33
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A =logging.get_logger(__name__) A ={ 'tiiuae/falcon-40b': 'https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json', 'tiiuae/falcon-7b': 'https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json', } class _a ( __a ): __a : Optional[int] = """falcon""" __a : Tuple = ["""past_key_values"""] def __init__( self : Dict , lowercase : str=65_024 , lowercase : Dict=4_544 , lowercase : Optional[int]=32 , lowercase : Any=71 , lowercase : List[Any]=1E-5 , lowercase : Union[str, Any]=0.02 , lowercase : int=True , lowercase : Union[str, Any]=0.0 , lowercase : str=0.0 , lowercase : List[Any]=None , lowercase : List[str]=False , lowercase : List[Any]=False , lowercase : List[str]=True , lowercase : Dict=True , lowercase : Tuple=False , lowercase : int=11 , lowercase : Any=11 , **lowercase : str , ): '''simple docstring''' UpperCAmelCase = vocab_size # Backward compatibility with n_embed kwarg UpperCAmelCase = kwargs.pop('''n_embed''' , lowercase ) UpperCAmelCase = hidden_size if n_embed is None else n_embed UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = layer_norm_epsilon UpperCAmelCase = initializer_range UpperCAmelCase = use_cache UpperCAmelCase = hidden_dropout UpperCAmelCase = attention_dropout UpperCAmelCase = bos_token_id UpperCAmelCase = eos_token_id UpperCAmelCase = num_attention_heads if num_kv_heads is None else num_kv_heads UpperCAmelCase = alibi UpperCAmelCase = new_decoder_architecture UpperCAmelCase = multi_query # Ignored when new_decoder_architecture is True UpperCAmelCase = parallel_attn UpperCAmelCase = bias super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) @property def A ( self : Any ): '''simple docstring''' return self.hidden_size // self.num_attention_heads @property def A ( self : Union[str, Any] ): '''simple docstring''' return not self.alibi
34
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = '''ylacombe/bark-small''' __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = '''en_speaker_1''' __lowerCamelCase = '''This is a test string''' __lowerCamelCase = '''speaker_embeddings_path.json''' __lowerCamelCase = '''speaker_embeddings''' def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Dict ): """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __lowerCamelCase = 35 __lowerCamelCase = 2 __lowerCamelCase = 8 __lowerCamelCase = { '''semantic_prompt''': np.ones(a ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from npz file __lowerCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(a , **a ) __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from the hub __lowerCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) __lowerCamelCase = processor(text=self.input_string ) __lowerCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
67
0
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __a = logging.get_logger(__name__) @add_end_docstrings( _a , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class UpperCAmelCase_ ( _a ): """simple docstring""" def lowerCamelCase ( self : Union[str, Any] , snake_case_ : GenericTensor ): if self.framework == "tf": snake_case__ : Optional[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": snake_case__ : Tuple = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=snake_case_ ) else: raise ValueError("""Unsupported framework""" ) return masked_index def lowerCamelCase ( self : Optional[Any] , snake_case_ : GenericTensor ): snake_case__ : List[Any] = self.get_masked_index(snake_case_ ) snake_case__ : List[Any] = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , f"No mask_token ({self.tokenizer.mask_token}) found on the input" , ) def lowerCamelCase ( self : Tuple , snake_case_ : GenericTensor ): if isinstance(snake_case_ , snake_case_ ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(snake_case_ ) def lowerCamelCase ( self : List[Any] , snake_case_ : Any , snake_case_ : Optional[int]=None , **snake_case_ : Optional[Any] ): if return_tensors is None: snake_case__ : Tuple = self.framework snake_case__ : Optional[Any] = self.tokenizer(snake_case_ , return_tensors=snake_case_ ) self.ensure_exactly_one_mask_token(snake_case_ ) return model_inputs def lowerCamelCase ( self : str , snake_case_ : str ): snake_case__ : Union[str, Any] = self.model(**snake_case_ ) snake_case__ : Dict = model_inputs["""input_ids"""] return model_outputs def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Union[str, Any] , snake_case_ : str=5 , snake_case_ : List[Any]=None ): # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: snake_case__ : Any = target_ids.shape[0] snake_case__ : List[Any] = model_outputs["""input_ids"""][0] snake_case__ : Optional[Any] = model_outputs["""logits"""] if self.framework == "tf": snake_case__ : Optional[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] snake_case__ : Optional[int] = outputs.numpy() snake_case__ : Optional[int] = outputs[0, masked_index, :] snake_case__ : Optional[int] = stable_softmax(snake_case_ , axis=-1 ) if target_ids is not None: snake_case__ : Optional[Any] = tf.gather_nd(tf.squeeze(snake_case_ , 0 ) , target_ids.reshape(-1 , 1 ) ) snake_case__ : Optional[int] = tf.expand_dims(snake_case_ , 0 ) snake_case__ : int = tf.math.top_k(snake_case_ , k=snake_case_ ) snake_case__ , snake_case__ : Any = topk.values.numpy(), topk.indices.numpy() else: snake_case__ : List[Any] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=snake_case_ ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample snake_case__ : Tuple = outputs[0, masked_index, :] snake_case__ : Tuple = logits.softmax(dim=-1 ) if target_ids is not None: snake_case__ : List[str] = probs[..., target_ids] snake_case__ , snake_case__ : List[str] = probs.topk(snake_case_ ) snake_case__ : Tuple = [] snake_case__ : List[str] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): snake_case__ : Union[str, Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place snake_case__ : Dict = input_ids.numpy().copy() if target_ids is not None: snake_case__ : Any = target_ids[p].tolist() snake_case__ : Union[str, Any] = p # Filter padding out: snake_case__ : List[str] = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back snake_case__ : str = self.tokenizer.decode(snake_case_ , skip_special_tokens=snake_case_ ) snake_case__ : Union[str, Any] = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence} row.append(snake_case_ ) result.append(snake_case_ ) if single_mask: return result[0] return result def lowerCamelCase ( self : int , snake_case_ : Any , snake_case_ : str=None ): if isinstance(snake_case_ , snake_case_ ): snake_case__ : Union[str, Any] = [targets] try: snake_case__ : Any = self.tokenizer.get_vocab() except Exception: snake_case__ : str = {} snake_case__ : List[Any] = [] for target in targets: snake_case__ : List[str] = vocab.get(snake_case_ , snake_case_ ) if id_ is None: snake_case__ : int = self.tokenizer( snake_case_ , add_special_tokens=snake_case_ , return_attention_mask=snake_case_ , return_token_type_ids=snake_case_ , max_length=1 , truncation=snake_case_ , )["""input_ids"""] if len(snake_case_ ) == 0: logger.warning( f"The specified target token `{target}` does not exist in the model vocabulary. " """We cannot replace it with anything meaningful, ignoring it""" ) continue snake_case__ : Optional[Any] = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f"The specified target token `{target}` does not exist in the model vocabulary. " f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`." ) target_ids.append(id_ ) snake_case__ : Optional[Any] = list(set(snake_case_ ) ) if len(snake_case_ ) == 0: raise ValueError("""At least one target must be provided when passed.""" ) snake_case__ : Dict = np.array(snake_case_ ) return target_ids def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Tuple=None , snake_case_ : Union[str, Any]=None ): snake_case__ : Union[str, Any] = {} if targets is not None: snake_case__ : List[str] = self.get_target_ids(snake_case_ , snake_case_ ) snake_case__ : Union[str, Any] = target_ids if top_k is not None: snake_case__ : Optional[int] = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""" ) return {}, {}, postprocess_params def __call__( self : List[str] , snake_case_ : Union[str, Any] , *snake_case_ : Tuple , **snake_case_ : List[Any] ): snake_case__ : Optional[int] = super().__call__(snake_case_ , **snake_case_ ) if isinstance(snake_case_ , snake_case_ ) and len(snake_case_ ) == 1: return outputs[0] return outputs
35
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
import math import unittest def A ( _lowerCamelCase ): '''simple docstring''' assert isinstance(_lowerCamelCase , _lowerCamelCase ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_lowerCamelCase ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True class UpperCAmelCase_ ( unittest.TestCase): def snake_case__ ( self): '''simple docstring''' self.assertTrue(is_prime(2)) self.assertTrue(is_prime(3)) self.assertTrue(is_prime(5)) self.assertTrue(is_prime(7)) self.assertTrue(is_prime(11)) self.assertTrue(is_prime(13)) self.assertTrue(is_prime(17)) self.assertTrue(is_prime(19)) self.assertTrue(is_prime(23)) self.assertTrue(is_prime(29)) def snake_case__ ( self): '''simple docstring''' with self.assertRaises(__a): is_prime(-19) self.assertFalse( is_prime(0), "Zero doesn't have any positive factors, primes must have exactly two.", ) self.assertFalse( is_prime(1), "One only has 1 positive factor, primes must have exactly two.", ) self.assertFalse(is_prime(2 * 2)) self.assertFalse(is_prime(2 * 3)) self.assertFalse(is_prime(3 * 3)) self.assertFalse(is_prime(3 * 5)) self.assertFalse(is_prime(3 * 5 * 7)) if __name__ == "__main__": unittest.main()
36
'''simple docstring''' import re from filelock import FileLock try: import nltk __UpperCAmelCase =True except (ImportError, ModuleNotFoundError): __UpperCAmelCase =False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: re.sub('''<n>''' , '''''' , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
67
0
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase_: '''simple docstring''' def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=2 ,__UpperCAmelCase=8 ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=True ,__UpperCAmelCase=99 ,__UpperCAmelCase=16 ,__UpperCAmelCase=5 ,__UpperCAmelCase=2 ,__UpperCAmelCase=36 ,__UpperCAmelCase="gelu" ,__UpperCAmelCase=0.0 ,__UpperCAmelCase=0.0 ,__UpperCAmelCase=512 ,__UpperCAmelCase=16 ,__UpperCAmelCase=2 ,__UpperCAmelCase=0.0_2 ,__UpperCAmelCase=3 ,__UpperCAmelCase=4 ,__UpperCAmelCase=None ,) -> Dict: lowerCAmelCase__ : Dict = parent lowerCAmelCase__ : Optional[int] = batch_size lowerCAmelCase__ : Optional[int] = seq_length lowerCAmelCase__ : Any = is_training lowerCAmelCase__ : str = use_input_mask lowerCAmelCase__ : Any = use_token_type_ids lowerCAmelCase__ : Union[str, Any] = use_labels lowerCAmelCase__ : List[Any] = vocab_size lowerCAmelCase__ : str = hidden_size lowerCAmelCase__ : Tuple = num_hidden_layers lowerCAmelCase__ : Any = num_attention_heads lowerCAmelCase__ : Union[str, Any] = intermediate_size lowerCAmelCase__ : List[Any] = hidden_act lowerCAmelCase__ : Tuple = hidden_dropout_prob lowerCAmelCase__ : int = attention_probs_dropout_prob lowerCAmelCase__ : Dict = max_position_embeddings lowerCAmelCase__ : Optional[int] = type_vocab_size lowerCAmelCase__ : Optional[int] = type_sequence_label_size lowerCAmelCase__ : int = initializer_range lowerCAmelCase__ : Dict = num_labels lowerCAmelCase__ : List[str] = num_choices lowerCAmelCase__ : str = scope def UpperCAmelCase_ ( self ) -> int: lowerCAmelCase__ : int = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) lowerCAmelCase__ : Union[str, Any] = None if self.use_input_mask: lowerCAmelCase__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ : Tuple = None if self.use_token_type_ids: lowerCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) lowerCAmelCase__ : int = None lowerCAmelCase__ : str = None lowerCAmelCase__ : int = None if self.use_labels: lowerCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) lowerCAmelCase__ : int = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) lowerCAmelCase__ : Any = ids_tensor([self.batch_size] ,self.num_choices ) lowerCAmelCase__ : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self ) -> int: return MraConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=__UpperCAmelCase ,initializer_range=self.initializer_range ,) def UpperCAmelCase_ ( self ) -> Optional[int]: lowerCAmelCase__ : Dict = self.get_config() lowerCAmelCase__ : Union[str, Any] = 300 return config def UpperCAmelCase_ ( self ) -> Optional[int]: ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) : int = self.prepare_config_and_inputs() lowerCAmelCase__ : int = True lowerCAmelCase__ : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[int]: lowerCAmelCase__ : Optional[int] = MraModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Optional[int] = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) lowerCAmelCase__ : List[Any] = model(__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) lowerCAmelCase__ : List[Any] = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,) -> int: lowerCAmelCase__ : List[str] = True lowerCAmelCase__ : Union[str, Any] = MraModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Optional[Any] = model( __UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,encoder_hidden_states=__UpperCAmelCase ,encoder_attention_mask=__UpperCAmelCase ,) lowerCAmelCase__ : str = model( __UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,encoder_hidden_states=__UpperCAmelCase ,) lowerCAmelCase__ : Any = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> int: lowerCAmelCase__ : Tuple = MraForMaskedLM(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Any = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : List[Any] = MraForQuestionAnswering(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : int = model( __UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,start_positions=__UpperCAmelCase ,end_positions=__UpperCAmelCase ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> str: lowerCAmelCase__ : Optional[Any] = self.num_labels lowerCAmelCase__ : Union[str, Any] = MraForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : int = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[int]: lowerCAmelCase__ : List[Any] = self.num_labels lowerCAmelCase__ : Optional[Any] = MraForTokenClassification(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : Any = model(__UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Optional[Any]: lowerCAmelCase__ : Any = self.num_choices lowerCAmelCase__ : Optional[Any] = MraForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCAmelCase__ : int = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowerCAmelCase__ : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowerCAmelCase__ : List[Any] = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() lowerCAmelCase__ : Tuple = model( __UpperCAmelCase ,attention_mask=__UpperCAmelCase ,token_type_ids=__UpperCAmelCase ,labels=__UpperCAmelCase ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self ) -> List[str]: lowerCAmelCase__ : Optional[int] = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ( lowerCAmelCase__ ) , ) : Optional[Any] = config_and_inputs lowerCAmelCase__ : Tuple = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): '''simple docstring''' __lowercase : Dict = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) __lowercase : str = False __lowercase : Union[str, Any] = False __lowercase : Optional[Any] = False __lowercase : int = False __lowercase : int = () def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : List[str] = MraModelTester(self ) lowerCAmelCase__ : Dict = ConfigTester(self ,config_class=__UpperCAmelCase ,hidden_size=37 ) def UpperCAmelCase_ ( self ) -> Tuple: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self ) -> List[Any]: lowerCAmelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Union[str, Any]: lowerCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCAmelCase__ : str = type self.model_tester.create_and_check_model(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> List[Any]: lowerCAmelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> str: lowerCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Dict: lowerCAmelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> Dict: lowerCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase ) @slow def UpperCAmelCase_ ( self ) -> Optional[Any]: for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ : Any = MraModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip(reason="""MRA does not output attentions""" ) def UpperCAmelCase_ ( self ) -> Union[str, Any]: return @require_torch class lowerCAmelCase_( unittest.TestCase ): '''simple docstring''' @slow def UpperCAmelCase_ ( self ) -> Dict: lowerCAmelCase__ : str = MraModel.from_pretrained("""uw-madison/mra-base-512-4""" ) lowerCAmelCase__ : List[Any] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): lowerCAmelCase__ : int = model(__UpperCAmelCase )[0] lowerCAmelCase__ : Optional[int] = torch.Size((1, 256, 768) ) self.assertEqual(output.shape ,__UpperCAmelCase ) lowerCAmelCase__ : str = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__UpperCAmelCase ,atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Any = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-512-4""" ) lowerCAmelCase__ : Tuple = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): lowerCAmelCase__ : List[Any] = model(__UpperCAmelCase )[0] lowerCAmelCase__ : List[str] = 5_0265 lowerCAmelCase__ : int = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape ,__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__UpperCAmelCase ,atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self ) -> Tuple: lowerCAmelCase__ : Union[str, Any] = MraForMaskedLM.from_pretrained("""uw-madison/mra-base-4096-8-d3""" ) lowerCAmelCase__ : Optional[int] = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): lowerCAmelCase__ : Optional[int] = model(__UpperCAmelCase )[0] lowerCAmelCase__ : Optional[Any] = 5_0265 lowerCAmelCase__ : Tuple = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape ,__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__UpperCAmelCase ,atol=1E-4 ) )
37
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] ="gpt_neox_japanese" def __init__( self : List[Any] , a : Tuple=3_20_00 , a : Dict=25_60 , a : Union[str, Any]=32 , a : Dict=32 , a : Dict=4 , a : Optional[Any]="gelu" , a : Any=1.00 , a : str=1_00_00 , a : List[str]=20_48 , a : str=0.02 , a : Union[str, Any]=1e-5 , a : Optional[Any]=True , a : str=3_19_96 , a : List[str]=3_19_99 , a : str=0.1 , a : Union[str, Any]=0.0 , **a : Optional[Any] , ): """simple docstring""" super().__init__(bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_multiple_size __lowerCamelCase = hidden_act __lowerCamelCase = rotary_pct __lowerCamelCase = rotary_emb_base __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = attention_dropout __lowerCamelCase = hidden_dropout
67
0
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase_ : Dict = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } UpperCAmelCase_ : Any = { '''allenai/led-base-16384''': 1_63_84, } class _SCREAMING_SNAKE_CASE ( _a ): snake_case__ : int = VOCAB_FILES_NAMES snake_case__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : int = LEDTokenizer snake_case__ : str = ["""input_ids""", """attention_mask"""] def __init__( self : List[str] , __lowerCamelCase : Dict=None , __lowerCamelCase : Any=None , __lowerCamelCase : int=None , __lowerCamelCase : Any="replace" , __lowerCamelCase : Union[str, Any]="<s>" , __lowerCamelCase : str="</s>" , __lowerCamelCase : Tuple="</s>" , __lowerCamelCase : List[Any]="<s>" , __lowerCamelCase : Optional[int]="<unk>" , __lowerCamelCase : Any="<pad>" , __lowerCamelCase : Tuple="<mask>" , __lowerCamelCase : List[str]=False , __lowerCamelCase : List[Any]=True , **__lowerCamelCase : str , ): super().__init__( __lowerCamelCase , __lowerCamelCase , tokenizer_file=__lowerCamelCase , errors=__lowerCamelCase , bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , unk_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , add_prefix_space=__lowerCamelCase , trim_offsets=__lowerCamelCase , **__lowerCamelCase , ) UpperCamelCase :Dict = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __lowerCamelCase ) != add_prefix_space: UpperCamelCase :Union[str, Any] = getattr(__lowerCamelCase , pre_tok_state.pop("""type""" ) ) UpperCamelCase :Optional[Any] = add_prefix_space UpperCamelCase :Tuple = pre_tok_class(**__lowerCamelCase ) UpperCamelCase :Optional[Any] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCamelCase :str = """post_processor""" UpperCamelCase :List[str] = getattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) if tokenizer_component_instance: UpperCamelCase :Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCamelCase :int = tuple(state["""sep"""] ) if "cls" in state: UpperCamelCase :Optional[int] = tuple(state["""cls"""] ) UpperCamelCase :Optional[Any] = False if state.get("""add_prefix_space""" , __lowerCamelCase ) != add_prefix_space: UpperCamelCase :Optional[Any] = add_prefix_space UpperCamelCase :Union[str, Any] = True if state.get("""trim_offsets""" , __lowerCamelCase ) != trim_offsets: UpperCamelCase :Tuple = trim_offsets UpperCamelCase :Tuple = True if changes_to_apply: UpperCamelCase :Tuple = getattr(__lowerCamelCase , state.pop("""type""" ) ) UpperCamelCase :int = component_class(**__lowerCamelCase ) setattr(self.backend_tokenizer , __lowerCamelCase , __lowerCamelCase ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def _A ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _A ( self : Dict , __lowerCamelCase : List[str] ): UpperCamelCase :Dict = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ) else value UpperCamelCase :List[Any] = value def _A ( self : Union[str, Any] , *__lowerCamelCase : List[Any] , **__lowerCamelCase : Optional[int] ): UpperCamelCase :Optional[int] = kwargs.get("""is_split_into_words""" , __lowerCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Tuple , *__lowerCamelCase : Union[str, Any] , **__lowerCamelCase : str ): UpperCamelCase :Tuple = kwargs.get("""is_split_into_words""" , __lowerCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ """to use it with pretokenized inputs.""" ) return super()._encode_plus(*__lowerCamelCase , **__lowerCamelCase ) def _A ( self : Optional[int] , __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ): UpperCamelCase :List[str] = self._tokenizer.model.save(__lowerCamelCase , name=__lowerCamelCase ) return tuple(__lowerCamelCase ) def _A ( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any]=None ): UpperCamelCase :List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _A ( self : List[Any] , __lowerCamelCase : List[int] , __lowerCamelCase : Optional[List[int]] = None ): UpperCamelCase :Dict = [self.sep_token_id] UpperCamelCase :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 + sep + token_ids_a + sep ) * [0] def _A ( self : Tuple , __lowerCamelCase : Union[Dict[str, EncodedInput], BatchEncoding] , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : Optional[bool] = None , ): UpperCamelCase :List[Any] = super()._pad( encoded_inputs=__lowerCamelCase , max_length=__lowerCamelCase , padding_strategy=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) # Load from model defaults if return_attention_mask is None: UpperCamelCase :List[Any] = """attention_mask""" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCamelCase :str = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCamelCase :Union[str, Any] = len(encoded_inputs["""global_attention_mask"""] ) != len(__lowerCamelCase ) if needs_to_be_padded: UpperCamelCase :Optional[int] = len(__lowerCamelCase ) - len(encoded_inputs["""global_attention_mask"""] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCamelCase :Optional[Any] = ( encoded_inputs["""global_attention_mask"""] + [-1] * difference ) elif self.padding_side == "left": UpperCamelCase :Union[str, Any] = [-1] * difference + encoded_inputs[ """global_attention_mask""" ] else: raise ValueError("""Invalid padding strategy:""" + str(self.padding_side ) ) return encoded_inputs
38
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase =int(input("Enter the first number: ").strip()) __UpperCAmelCase =int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
67
0
import importlib.metadata import operator import re import sys from typing import Optional from packaging import version _a = { '''<''': operator.lt, '''<=''': operator.le, '''==''': operator.eq, '''!=''': operator.ne, '''>=''': operator.ge, '''>''': operator.gt, } def __A ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )-> Optional[Any]: """simple docstring""" if got_ver is None or want_ver is None: raise ValueError( F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider""" F""" reinstalling {pkg}.""" ) if not ops[op](version.parse(__lowerCAmelCase ) , version.parse(__lowerCAmelCase ) ): raise ImportError( F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" ) def __A ( __lowerCAmelCase , __lowerCAmelCase = None )-> None: """simple docstring""" _UpperCAmelCase = F"""\n{hint}""" if hint is not None else '' # non-versioned check if re.match(R'^[\w_\-\d]+$' , __lowerCAmelCase ): _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = requirement, None, None else: _UpperCAmelCase = re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)' , __lowerCAmelCase ) if not match: raise ValueError( 'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but' F""" got {requirement}""" ) _UpperCAmelCase , _UpperCAmelCase = match[0] _UpperCAmelCase = want_full.split(',' ) # there could be multiple requirements _UpperCAmelCase = {} for w in want_range: _UpperCAmelCase = re.findall(R'^([\s!=<>]{1,2})(.+)' , __lowerCAmelCase ) if not match: raise ValueError( 'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,' F""" but got {requirement}""" ) _UpperCAmelCase , _UpperCAmelCase = match[0] _UpperCAmelCase = want_ver if op not in ops: raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" ) # special case if pkg == "python": _UpperCAmelCase = '.'.join([str(__lowerCAmelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return # check if any version is installed try: _UpperCAmelCase = importlib.metadata.version(__lowerCAmelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def __A ( __lowerCAmelCase )-> Tuple: """simple docstring""" _UpperCAmelCase = 'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main' return require_version(__lowerCAmelCase , __lowerCAmelCase )
39
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _A : """simple docstring""" def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : int , __UpperCAmelCase : int): if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0") a : Union[str, Any] = img a : Optional[int] = img.shape[1] a : Dict = img.shape[0] a : Dict = dst_width a : Any = dst_height a : str = self.src_w / self.dst_w a : Dict = self.src_h / self.dst_h a : Dict = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta) * 255 ) def __snake_case ( self : Tuple): for i in range(self.dst_h): for j in range(self.dst_w): a : List[str] = self.img[self.get_y(__UpperCAmelCase)][self.get_x(__UpperCAmelCase)] def __snake_case ( self : Dict , __UpperCAmelCase : int): return int(self.ratio_x * x) def __snake_case ( self : Optional[int] , __UpperCAmelCase : int): return int(self.ratio_y * y) if __name__ == "__main__": __lowercase , __lowercase = 800, 600 __lowercase = imread("""image_data/lena.jpg""", 1) __lowercase = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f'''Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}''', n.output ) waitKey(0) destroyAllWindows()
40
'''simple docstring''' import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ), f"""{len(UpperCamelCase__ )} != {len(UpperCamelCase__ )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __UpperCAmelCase ={ # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __UpperCAmelCase ={ # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: try: __lowerCamelCase = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" f""" {n_student}""" ) return list(range(UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[int]: if n_student > n_teacher: raise ValueError(f"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(UpperCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = "student" , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__=False , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __lowerCamelCase = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(UpperCamelCase__ , UpperCamelCase__ ): AutoTokenizer.from_pretrained(UpperCamelCase__ ).save_pretrained(UpperCamelCase__ ) # purely for convenience __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ).eval() else: assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), f"""teacher must be a model or string got type {type(UpperCamelCase__ )}""" __lowerCamelCase = teacher.config.to_diff_dict() try: __lowerCamelCase , __lowerCamelCase = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): __lowerCamelCase , __lowerCamelCase = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __lowerCamelCase , __lowerCamelCase = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(UpperCamelCase__ ) # Copy weights __lowerCamelCase = teacher.config_class(**UpperCamelCase__ ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_config(UpperCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __lowerCamelCase = student.load_state_dict(teacher.state_dict() , strict=UpperCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __lowerCamelCase , __lowerCamelCase = list(range(UpperCamelCase__ ) ), list(range(UpperCamelCase__ ) ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" f""" {save_path}""" ) student.save_pretrained(UpperCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) if d_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) try: if hasattr( UpperCamelCase__ , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , UpperCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , UpperCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , UpperCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , UpperCamelCase__ ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __lowerCamelCase = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(UpperCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
67
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _lowercase ( unittest.TestCase , _lowercase ): def lowerCamelCase_ ( self: str ): lowerCamelCase__ : Union[str, Any] = load_tool("""text-classification""" ) self.tool.setup() lowerCamelCase__ : Optional[int] = load_tool("""text-classification""" , remote=UpperCamelCase__ ) def lowerCamelCase_ ( self: Dict ): lowerCamelCase__ : Optional[int] = self.tool("""That's quite cool""" , ["""positive""", """negative"""] ) self.assertEqual(UpperCamelCase__ , """positive""" ) def lowerCamelCase_ ( self: Tuple ): lowerCamelCase__ : Optional[int] = self.remote_tool("""That's quite cool""" , ["""positive""", """negative"""] ) self.assertEqual(UpperCamelCase__ , """positive""" ) def lowerCamelCase_ ( self: Optional[Any] ): lowerCamelCase__ : str = self.tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] ) self.assertEqual(UpperCamelCase__ , """positive""" ) def lowerCamelCase_ ( self: str ): lowerCamelCase__ : List[Any] = self.remote_tool(text="""That's quite cool""" , labels=["""positive""", """negative"""] ) self.assertEqual(UpperCamelCase__ , """positive""" )
41
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __UpperCAmelCase =["gpt2"] __UpperCAmelCase ="gpt2" if is_tf_available(): class a__ ( tf.Module ): def __init__( self : str , a : Union[str, Any] ): """simple docstring""" super().__init__() __lowerCamelCase = tokenizer __lowerCamelCase = AutoConfig.from_pretrained(a ) __lowerCamelCase = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = self.tokenizer(a ) __lowerCamelCase = tokenized['''input_ids'''].to_tensor() __lowerCamelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase = self.model(input_ids=a , attention_mask=a )['''logits'''] return outputs @require_tf @require_keras_nlp class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" super().setUp() __lowerCamelCase = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowerCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase = tokenizer([test_inputs] , return_tensors='''tf''' ) __lowerCamelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase = python_outputs[key].numpy() __lowerCamelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase = tf.constant(a ) __lowerCamelCase = compiled_tokenizer(a ) __lowerCamelCase = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = ModelToSave(tokenizer=a ) __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase = Path(a ) / '''saved.model''' tf.saved_model.save(a , a , signatures={'''serving_default''': model.serving} ) __lowerCamelCase = tf.saved_model.load(a ) __lowerCamelCase = loaded_model.signatures['''serving_default'''](a )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase = tf_tokenizer.get_config() __lowerCamelCase = TFGPTaTokenizer.from_config(a ) __lowerCamelCase = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase = 12_31_23 for max_length in [3, 5, 10_24]: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a , max_length=a ) __lowerCamelCase = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
67
0
'''simple docstring''' import glob import os import random from string import ascii_lowercase, digits import cva lowercase : Dict = "" lowercase : List[Any] = "" lowercase : Tuple = "" lowercase : Dict = 1 # (0 is vertical, 1 is horizontal) def SCREAMING_SNAKE_CASE__ ( ) -> None: _snake_case , _snake_case = get_dataset(__A , __A ) print('Processing...' ) _snake_case , _snake_case , _snake_case = update_image_and_anno(__A , __A , __A ) for index, image in enumerate(__A ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' _snake_case = random_chars(32 ) _snake_case = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0] _snake_case = F'{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}' cva.imwrite(F'/{file_root}.jpg' , __A , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'Success {index+1}/{len(__A )} with {file_name}' ) _snake_case = [] for anno in new_annos[index]: _snake_case = F'{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}' annos_list.append(__A ) with open(F'/{file_root}.txt' , 'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> tuple[list, list]: _snake_case = [] _snake_case = [] for label_file in glob.glob(os.path.join(__A , '*.txt' ) ): _snake_case = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0] with open(__A ) as in_file: _snake_case = in_file.readlines() _snake_case = os.path.join(__A , F'{label_name}.jpg' ) _snake_case = [] for obj_list in obj_lists: _snake_case = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__A ) labels.append(__A ) return img_paths, labels def SCREAMING_SNAKE_CASE__ ( __A , __A , __A = 1 ) -> tuple[list, list, list]: _snake_case = [] _snake_case = [] _snake_case = [] for idx in range(len(__A ) ): _snake_case = [] _snake_case = img_list[idx] path_list.append(__A ) _snake_case = anno_list[idx] _snake_case = cva.imread(__A ) if flip_type == 1: _snake_case = cva.flip(__A , __A ) for bbox in img_annos: _snake_case = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: _snake_case = cva.flip(__A , __A ) for bbox in img_annos: _snake_case = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__A ) new_imgs_list.append(__A ) return new_imgs_list, new_annos_lists, path_list def SCREAMING_SNAKE_CASE__ ( __A = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" _snake_case = ascii_lowercase + digits return "".join(random.choice(__A ) for _ in range(__A ) ) if __name__ == "__main__": main() print("DONE ✅")
42
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
67
0
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 lowerCamelCase_ : '''simple docstring''' def __init__( self , __lowercase , __lowercase=3 , __lowercase=32 , __lowercase=3 , __lowercase=10 , __lowercase=[8, 16, 32, 64] , __lowercase=[1, 1, 2, 1] , __lowercase=True , __lowercase=True , __lowercase="relu" , __lowercase=3 , __lowercase=None , __lowercase=["stage2", "stage3", "stage4"] , __lowercase=[2, 3, 4] , __lowercase=1 , ) -> Dict: __UpperCamelCase :List[Any] = parent __UpperCamelCase :Optional[Any] = batch_size __UpperCamelCase :int = image_size __UpperCamelCase :Tuple = num_channels __UpperCamelCase :List[Any] = embeddings_size __UpperCamelCase :Dict = hidden_sizes __UpperCamelCase :List[Any] = depths __UpperCamelCase :str = is_training __UpperCamelCase :Optional[Any] = use_labels __UpperCamelCase :int = hidden_act __UpperCamelCase :str = num_labels __UpperCamelCase :Tuple = scope __UpperCamelCase :Dict = len(__lowercase) __UpperCamelCase :Any = out_features __UpperCamelCase :Any = out_indices __UpperCamelCase :Optional[int] = num_groups def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) __UpperCamelCase :List[Any] = None if self.use_labels: __UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_labels) __UpperCamelCase :Any = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self) -> Tuple: 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 UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> str: __UpperCamelCase :Tuple = BitModel(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :int = model(__lowercase) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> int: __UpperCamelCase :Dict = self.num_labels __UpperCamelCase :int = BitForImageClassification(__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :Tuple = model(__lowercase , labels=__lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase) -> Any: __UpperCamelCase :Dict = BitBackbone(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[str] = model(__lowercase) # 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 __UpperCamelCase :Dict = None __UpperCamelCase :str = BitBackbone(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :Any = model(__lowercase) # 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 UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Union[str, Any] = self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase :Union[str, Any] = config_and_inputs __UpperCamelCase :Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Optional[int] = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () a__ : Union[str, Any] = ( {"""feature-extraction""": BitModel, """image-classification""": BitForImageClassification} if is_torch_available() else {} ) a__ : List[str] = False a__ : Optional[Any] = False a__ : Any = False a__ : Union[str, Any] = False a__ : List[Any] = False def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Dict = BitModelTester(self) __UpperCamelCase :List[str] = ConfigTester(self , config_class=__lowercase , has_text_modality=__lowercase) def UpperCamelCase__ ( self) -> List[Any]: 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 UpperCamelCase__ ( self) -> Dict: return @unittest.skip(reason='''Bit does not output attentions''') def UpperCamelCase__ ( self) -> int: pass @unittest.skip(reason='''Bit does not use inputs_embeds''') def UpperCamelCase__ ( self) -> Any: pass @unittest.skip(reason='''Bit does not support input and output embeddings''') def UpperCamelCase__ ( self) -> Union[str, Any]: pass def UpperCamelCase__ ( self) -> Any: __UpperCamelCase , __UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :Optional[int] = model_class(__lowercase) __UpperCamelCase :int = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase :List[str] = [*signature.parameters.keys()] __UpperCamelCase :List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowercase) def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase) def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__lowercase) def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase , __UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase :Optional[Any] = model_class(config=__lowercase) for name, module in model.named_modules(): if isinstance(__lowercase , (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 UpperCamelCase__ ( self) -> Optional[Any]: def check_hidden_states_output(__lowercase , __lowercase , __lowercase): __UpperCamelCase :Dict = model_class(__lowercase) model.to(__lowercase) model.eval() with torch.no_grad(): __UpperCamelCase :Optional[int] = model(**self._prepare_for_class(__lowercase , __lowercase)) __UpperCamelCase :Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __UpperCamelCase :Any = self.model_tester.num_stages self.assertEqual(len(__lowercase) , 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] , ) __UpperCamelCase , __UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase :Tuple = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: __UpperCamelCase :str = layer_type __UpperCamelCase :Optional[Any] = True check_hidden_states_output(__lowercase , __lowercase , __lowercase) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCamelCase :Dict = True check_hidden_states_output(__lowercase , __lowercase , __lowercase) @unittest.skip(reason='''Bit does not use feedforward chunking''') def UpperCamelCase__ ( self) -> str: pass def UpperCamelCase__ ( self) -> int: __UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowercase) @slow def UpperCamelCase__ ( self) -> List[str]: for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase :Dict = BitModel.from_pretrained(__lowercase) self.assertIsNotNone(__lowercase) def lowerCamelCase ( ): '''simple docstring''' __UpperCamelCase :Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ ( self) -> int: return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def UpperCamelCase__ ( self) -> List[str]: __UpperCamelCase :List[str] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]).to(__lowercase) __UpperCamelCase :List[Any] = self.default_image_processor __UpperCamelCase :List[str] = prepare_img() __UpperCamelCase :Any = image_processor(images=__lowercase , return_tensors='''pt''').to(__lowercase) # forward pass with torch.no_grad(): __UpperCamelCase :Any = model(**__lowercase) # verify the logits __UpperCamelCase :Tuple = torch.Size((1, 1_000)) self.assertEqual(outputs.logits.shape , __lowercase) __UpperCamelCase :Union[str, Any] = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]]).to(__lowercase) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowercase , atol=1E-4)) @require_torch class lowerCamelCase_ ( UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : List[str] = (BitBackbone,) if is_torch_available() else () a__ : Dict = BitConfig a__ : Any = False def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :Optional[Any] = BitModelTester(self)
43
'''simple docstring''' import logging import os from .state import PartialState class a__ ( logging.LoggerAdapter ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a : Optional[Any] ): """simple docstring""" __lowerCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[int] , a : str , *a : Optional[int] , **a : List[Any] ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __lowerCamelCase = kwargs.pop('''main_process_only''' , a ) __lowerCamelCase = kwargs.pop('''in_order''' , a ) if self.isEnabledFor(a ): if self._should_log(a ): __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) elif in_order: __lowerCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) state.wait_for_everyone() def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = None ) -> Optional[int]: if log_level is None: __lowerCamelCase = os.environ.get('''ACCELERATE_LOG_LEVEL''' , UpperCamelCase__ ) __lowerCamelCase = logging.getLogger(UpperCamelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(UpperCamelCase__ , {} )
67
0
"""simple docstring""" def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list ,_lowerCamelCase : list ,_lowerCamelCase : int ) -> list: _lowerCAmelCase : List[str] = len(_lowerCamelCase ) _lowerCAmelCase : Dict = [[0] * n for i in range(_lowerCamelCase )] for i in range(_lowerCamelCase ): _lowerCAmelCase : int = y_points[i] for i in range(2 ,_lowerCamelCase ): for j in range(_lowerCamelCase ,_lowerCamelCase ): _lowerCAmelCase : Dict = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
44
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = set({'''(''', '''[''', '''{'''} ) __lowerCamelCase = set({''')''', ''']''', '''}'''} ) __lowerCamelCase = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def __lowerCAmelCase ( ) -> str: __lowerCamelCase = input('''Enter sequence of brackets: ''' ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , '''is balanced''' ) else: print(UpperCamelCase__ , '''is not balanced''' ) if __name__ == "__main__": main()
67
0
"""simple docstring""" import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "asapp/sew-tiny-100k": "https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json", # See all SEW models at https://huggingface.co/models?filter=sew } class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCAmelCase : int = 'sew' def __init__( self , _a=32 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a=2 , _a="gelu" , _a=0.1 , _a=0.1 , _a=0.1 , _a=0.0 , _a=0.1 , _a=0.1 , _a=0.02 , _a=1E-5 , _a="group" , _a="gelu" , _a=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , _a=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , _a=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , _a=False , _a=128 , _a=16 , _a=True , _a=0.05 , _a=10 , _a=2 , _a=0.0 , _a=10 , _a=0 , _a="mean" , _a=False , _a=False , _a=256 , _a=0 , _a=1 , _a=2 , **_a , ): super().__init__(**_a , pad_token_id=_a , bos_token_id=_a , eos_token_id=_a ) __a = hidden_size __a = feat_extract_norm __a = feat_extract_activation __a = list(_a ) __a = list(_a ) __a = list(_a ) __a = conv_bias __a = num_conv_pos_embeddings __a = num_conv_pos_embedding_groups __a = len(self.conv_dim ) __a = num_hidden_layers __a = intermediate_size __a = squeeze_factor __a = hidden_act __a = num_attention_heads __a = hidden_dropout __a = attention_dropout __a = activation_dropout __a = feat_proj_dropout __a = final_dropout __a = layerdrop __a = layer_norm_eps __a = initializer_range __a = vocab_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect.''' '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,''' f'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)''' f'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a = apply_spec_augment __a = mask_time_prob __a = mask_time_length __a = mask_time_min_masks __a = mask_feature_prob __a = mask_feature_length __a = mask_feature_min_masks # ctc loss __a = ctc_loss_reduction __a = ctc_zero_infinity # sequence classification __a = use_weighted_layer_sum __a = classifier_proj_size @property def __UpperCAmelCase ( self ): return functools.reduce(operator.mul , self.conv_stride , 1 )
45
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict ="M-CLIP" def __init__( self : Tuple , a : Optional[int]=10_24 , a : Tuple=7_68 , **a : List[str] ): """simple docstring""" __lowerCamelCase = transformerDimSize __lowerCamelCase = imageDimSize super().__init__(**a ) class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =MCLIPConfig def __init__( self : str , a : List[Any] , *a : Dict , **a : str ): """simple docstring""" super().__init__(a , *a , **a ) __lowerCamelCase = XLMRobertaModel(a ) __lowerCamelCase = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.transformer(input_ids=a , attention_mask=a )[0] __lowerCamelCase = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a ), embs
67
0
"""simple docstring""" import math def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float ): '''simple docstring''' return math.pow(SCREAMING_SNAKE_CASE , 2 ) - a def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : float ): '''simple docstring''' return 2 * x def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : float ): '''simple docstring''' lowerCAmelCase = 2.0 while start <= a: lowerCAmelCase = math.pow(SCREAMING_SNAKE_CASE , 2 ) return start def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : int = 99_99 , SCREAMING_SNAKE_CASE : float = 0.00_00_00_00_00_00_01 ): '''simple docstring''' if a < 0: raise ValueError("""math domain error""" ) lowerCAmelCase = get_initial_point(SCREAMING_SNAKE_CASE ) for _ in range(SCREAMING_SNAKE_CASE ): lowerCAmelCase = value lowerCAmelCase = value - fx(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) / fx_derivative(SCREAMING_SNAKE_CASE ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
46
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
67
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class A__ ( A__ ): A__ = 'deta' A__ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple , _a : Optional[int]=None , _a : int=900 , _a : Optional[Any]=2048 , _a : int=6 , _a : Tuple=2048 , _a : Optional[int]=8 , _a : Any=6 , _a : str=1024 , _a : int=8 , _a : int=0.0 , _a : Optional[Any]=True , _a : Tuple="relu" , _a : Union[str, Any]=256 , _a : Tuple=0.1 , _a : str=0.0 , _a : Dict=0.0 , _a : Tuple=0.02 , _a : Union[str, Any]=1.0 , _a : Any=True , _a : Tuple=False , _a : List[Any]="sine" , _a : str=5 , _a : List[Any]=4 , _a : str=4 , _a : Union[str, Any]=True , _a : Optional[int]=300 , _a : Dict=True , _a : List[Any]=True , _a : List[Any]=1 , _a : List[str]=5 , _a : int=2 , _a : Dict=1 , _a : str=1 , _a : Optional[Any]=5 , _a : Union[str, Any]=2 , _a : List[str]=0.1 , _a : List[Any]=0.25 , **_a : Union[str, Any] , ) -> List[str]: '''simple docstring''' if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =backbone_config.pop('model_type' ) _SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE =config_class.from_dict(_a ) _SCREAMING_SNAKE_CASE =backbone_config _SCREAMING_SNAKE_CASE =num_queries _SCREAMING_SNAKE_CASE =max_position_embeddings _SCREAMING_SNAKE_CASE =d_model _SCREAMING_SNAKE_CASE =encoder_ffn_dim _SCREAMING_SNAKE_CASE =encoder_layers _SCREAMING_SNAKE_CASE =encoder_attention_heads _SCREAMING_SNAKE_CASE =decoder_ffn_dim _SCREAMING_SNAKE_CASE =decoder_layers _SCREAMING_SNAKE_CASE =decoder_attention_heads _SCREAMING_SNAKE_CASE =dropout _SCREAMING_SNAKE_CASE =attention_dropout _SCREAMING_SNAKE_CASE =activation_dropout _SCREAMING_SNAKE_CASE =activation_function _SCREAMING_SNAKE_CASE =init_std _SCREAMING_SNAKE_CASE =init_xavier_std _SCREAMING_SNAKE_CASE =encoder_layerdrop _SCREAMING_SNAKE_CASE =auxiliary_loss _SCREAMING_SNAKE_CASE =position_embedding_type # deformable attributes _SCREAMING_SNAKE_CASE =num_feature_levels _SCREAMING_SNAKE_CASE =encoder_n_points _SCREAMING_SNAKE_CASE =decoder_n_points _SCREAMING_SNAKE_CASE =two_stage _SCREAMING_SNAKE_CASE =two_stage_num_proposals _SCREAMING_SNAKE_CASE =with_box_refine _SCREAMING_SNAKE_CASE =assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher _SCREAMING_SNAKE_CASE =class_cost _SCREAMING_SNAKE_CASE =bbox_cost _SCREAMING_SNAKE_CASE =giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE =mask_loss_coefficient _SCREAMING_SNAKE_CASE =dice_loss_coefficient _SCREAMING_SNAKE_CASE =bbox_loss_coefficient _SCREAMING_SNAKE_CASE =giou_loss_coefficient _SCREAMING_SNAKE_CASE =eos_coefficient _SCREAMING_SNAKE_CASE =focal_alpha super().__init__(is_encoder_decoder=_a , **_a ) @property def A ( self : Dict ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def A ( self : List[Any] ) -> int: '''simple docstring''' return self.d_model def A ( self : Optional[int] ) -> List[str]: '''simple docstring''' _SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE =self.__class__.model_type return output
47
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
from ..utils import DummyObject, requires_backends class UpperCamelCase__ (metaclass=lowerCAmelCase__ ): '''simple docstring''' lowerCamelCase_ : Tuple = ["""onnx"""] def __init__( self , *UpperCamelCase__ , **UpperCamelCase__ ) -> Tuple: requires_backends(self , ["onnx"] ) @classmethod def _lowercase ( cls , *UpperCamelCase__ , **UpperCamelCase__ ) -> Union[str, Any]: requires_backends(cls , ["onnx"] ) @classmethod def _lowercase ( cls , *UpperCamelCase__ , **UpperCamelCase__ ) -> Dict: requires_backends(cls , ["onnx"] )
48
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
0
from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=__UpperCAmelCase ) class _A ( __UpperCAmelCase ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization UpperCamelCase__ : str = field(default='''summarization''' ,metadata={'''include_in_asdict_even_if_is_default''': True} ) UpperCamelCase__ : ClassVar[Features] = Features({'''text''': Value('''string''' )} ) UpperCamelCase__ : ClassVar[Features] = Features({'''summary''': Value('''string''' )} ) UpperCamelCase__ : str = "text" UpperCamelCase__ : str = "summary" @property def _lowerCamelCase ( self : str): '''simple docstring''' return {self.text_column: "text", self.summary_column: "summary"}
49
'''simple docstring''' 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_barthez import BarthezTokenizer else: __UpperCAmelCase =None __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __UpperCAmelCase ={ "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } __UpperCAmelCase ={ "moussaKam/mbarthez": 1_0_2_4, "moussaKam/barthez": 1_0_2_4, "moussaKam/barthez-orangesum-title": 1_0_2_4, } __UpperCAmelCase ="▁" class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] =["input_ids", "attention_mask"] lowerCamelCase : Union[str, Any] =BarthezTokenizer def __init__( self : Optional[Any] , a : Dict=None , a : str=None , a : List[Any]="<s>" , a : Optional[int]="</s>" , a : List[str]="</s>" , a : Tuple="<s>" , a : str="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , **a : Union[str, Any] , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Optional[str] = None ): """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(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
67
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : str = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSeriesTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : List[str] = [ """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimeSeriesTransformerForPrediction""", """TimeSeriesTransformerModel""", """TimeSeriesTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys _UpperCAmelCase : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
50
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00_00 ) -> int: __lowerCamelCase = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , UpperCamelCase__ , UpperCamelCase__ ) ) ) __lowerCamelCase = [float(UpperCamelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCamelCase__ , limit + 1 , UpperCamelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'{solution() = }')
67
0
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def A (__A : Tuple ) -> int: """simple docstring""" return {key.lstrip('''-''' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def A () -> Dict: """simple docstring""" UpperCAmelCase_ = ArgumentParser( '''HuggingFace Datasets CLI tool''' , usage='''datasets-cli <command> [<args>]''' , allow_abbrev=__A ) UpperCAmelCase_ = parser.add_subparsers(help='''datasets-cli command helpers''' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(__A ) EnvironmentCommand.register_subcommand(__A ) TestCommand.register_subcommand(__A ) RunBeamCommand.register_subcommand(__A ) DummyDataCommand.register_subcommand(__A ) # Parse args UpperCAmelCase_ , UpperCAmelCase_ = parser.parse_known_args() if not hasattr(__A , '''func''' ): parser.print_help() exit(1 ) UpperCAmelCase_ = parse_unknown_args(__A ) # Run UpperCAmelCase_ = args.func(__A , **__A ) service.run() if __name__ == "__main__": main()
51
'''simple docstring''' 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 a__ : def __init__( self : Union[str, Any] , a : Union[str, Any] , a : Tuple=13 , a : Optional[Any]=7 , a : List[Any]=True , a : Optional[Any]=True , a : Any=True , a : Union[str, Any]=99 , a : Any=32 , a : int=5 , a : Optional[int]=4 , a : Union[str, Any]=37 , a : Optional[Any]="gelu" , a : Union[str, Any]=0.1 , a : Any=0.1 , a : Optional[int]=5_12 , a : int=16 , a : Optional[Any]=2 , a : Union[str, Any]=0.02 , a : Any=3 , a : Dict=4 , a : Any=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = self.vocab_size - 1 def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __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 = 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 , ) __lowerCamelCase = 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 : Union[str, Any] , a : Dict , a : List[str] , a : Tuple , a : List[Any] , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , head_mask=a ) __lowerCamelCase = model(a , token_type_ids=a ) __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Union[str, Any] , a : Dict , a : Union[str, Any] , a : Tuple , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Optional[Any] , *a : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTDoubleHeadsModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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 : List[str] , a : int , a : Dict , a : Optional[Any] , a : str , *a : int ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = OpenAIGPTForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """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, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : List[str] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCamelCase : str =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCamelCase : Optional[int] =( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple , a : Optional[int] , a : int , a : str , a : Any ): """simple docstring""" 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 : Optional[int] , a : int , a : Optional[int] , a : str=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a , ) __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a , ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , n_embd=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = OpenAIGPTModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(a ) __lowerCamelCase = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=a ) # the president is __lowerCamelCase = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the __lowerCamelCase = model.generate(a , do_sample=a ) self.assertListEqual(output_ids[0].tolist() , a )
67
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer UpperCamelCase : Optional[int] = flax_key_tuple[:-1] + ("weight",) UpperCamelCase : Union[str, Any] = torch.permute(_lowerCAmelCase , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(_lowerCAmelCase ): # linear layer UpperCamelCase : Optional[Any] = flax_key_tuple[:-1] + ("weight",) UpperCamelCase : Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: UpperCamelCase : int = flax_key_tuple[:-1] + ("weight",) return flax_key_tuple, flax_tensor def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Union[str, Any]: if "metadata" in layer: UpperCamelCase : List[str] = layer.split("metadata" ) UpperCamelCase : Union[str, Any] = "".join(split_layer[0] )[:-1] UpperCamelCase : Optional[int] = [tuple(("metadata" + split_layer[1]).split("/" ) )] elif "kvstore" in layer: UpperCamelCase : str = layer.split("kvstore" ) UpperCamelCase : List[str] = "".join(split_layer[0] )[:-1] UpperCamelCase : Tuple = [tuple(("kvstore" + split_layer[1]).split("/" ) )] else: UpperCamelCase : List[Any] = layer.split("/" ) UpperCamelCase : Union[str, Any] = "/".join(split_layer[:-1] ) UpperCamelCase : int = (split_layer[-1],) if "kvstore/path" in layer: UpperCamelCase : Union[str, Any] = F"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: UpperCamelCase : List[str] = "file" else: UpperCamelCase : Optional[int] = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def A_ ( _lowerCAmelCase , _lowerCAmelCase ) -> List[Any]: UpperCamelCase : Optional[int] = rename_keys(_lowerCAmelCase ) UpperCamelCase : Union[str, Any] = {} for k, v in current_block.items(): UpperCamelCase : Tuple = v UpperCamelCase : Union[str, Any] = new_current_block torch.save(_lowerCAmelCase , _lowerCAmelCase ) def A_ ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = WEIGHTS_NAME ) -> Union[str, Any]: UpperCamelCase : List[str] = convert_file_size_to_int(_lowerCAmelCase ) UpperCamelCase : Dict = [] UpperCamelCase : List[str] = {} UpperCamelCase : Any = 0 UpperCamelCase : Any = 0 os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase ) with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp: UpperCamelCase : Union[str, Any] = serialization.msgpack_restore(fp.read() )["optimizer"]["target"] UpperCamelCase : Optional[Any] = flatten_dict(_lowerCAmelCase , sep="/" ) UpperCamelCase : Tuple = {} for layer in checkpoint_info.keys(): UpperCamelCase , UpperCamelCase , UpperCamelCase : Optional[Any] = get_key_and_tensorstore_dict( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if curr_real_layer_name in all_layers: UpperCamelCase : int = content else: UpperCamelCase : Union[str, Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file UpperCamelCase : Optional[int] = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() UpperCamelCase : Any = torch.tensor(_lowerCAmelCase ) UpperCamelCase : Dict = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts UpperCamelCase , UpperCamelCase : str = rename_base_flax_keys(tuple(key.split("/" ) ) , _lowerCAmelCase ) UpperCamelCase : Optional[Any] = "/".join(_lowerCAmelCase ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: UpperCamelCase : Dict = os.path.join( _lowerCAmelCase , weights_name.replace(".bin" , F"""-{len(_lowerCAmelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(_lowerCAmelCase , _lowerCAmelCase ) sharded_state_dicts.append(current_block.keys() ) del current_block UpperCamelCase : List[str] = {} UpperCamelCase : Optional[Any] = 0 UpperCamelCase : List[Any] = raw_weights.to(getattr(_lowerCAmelCase , _lowerCAmelCase ) ) current_block_size += weight_size total_size += weight_size # Add the last block UpperCamelCase : Optional[int] = os.path.join(_lowerCAmelCase , weights_name.replace(".bin" , F"""-{len(_lowerCAmelCase )+1:05d}-of-???.bin""" ) ) rename_and_save_block(_lowerCAmelCase , _lowerCAmelCase ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(_lowerCAmelCase ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index UpperCamelCase : List[str] = {} UpperCamelCase : str = {} for idx, shard in enumerate(_lowerCAmelCase ): UpperCamelCase : List[str] = weights_name.replace( ".bin" , F"""-{idx+1:05d}-of-{len(_lowerCAmelCase ):05d}.bin""" ) # len(sharded_state_dicts):05d} UpperCamelCase : Optional[int] = os.path.join(_lowerCAmelCase , weights_name.replace(".bin" , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(_lowerCAmelCase , os.path.join(_lowerCAmelCase , _lowerCAmelCase ) ) UpperCamelCase : Any = shard for key in shard: UpperCamelCase : List[str] = shard_file # Add the metadata UpperCamelCase : Optional[int] = {"total_size": total_size} UpperCamelCase : Optional[Any] = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , "w" , encoding="utf-8" ) as f: UpperCamelCase : Dict = json.dumps(_lowerCAmelCase , indent=2 , sort_keys=_lowerCAmelCase ) + "\n" f.write(_lowerCAmelCase ) return metadata, index if __name__ == "__main__": __lowerCamelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) __lowerCamelCase : Union[str, Any] = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def A_ ( ) -> Union[str, Any]: from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer UpperCamelCase : Tuple = SwitchTransformersConfig.from_pretrained("google/switch-base-8" ) config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" ) UpperCamelCase : List[str] = SwitchTransformersForConditionalGeneration.from_pretrained( "/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" ) UpperCamelCase : List[str] = TaTokenizer.from_pretrained("t5-small" ) UpperCamelCase : Dict = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>." UpperCamelCase : Tuple = tokenizer(_lowerCAmelCase , return_tensors="pt" ).input_ids UpperCamelCase : Tuple = model.generate(_lowerCAmelCase , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
52
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =["image_processor", "tokenizer"] lowerCamelCase : Union[str, Any] ="LayoutLMv2ImageProcessor" lowerCamelCase : int =("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , a : Any=None , a : Any=None , **a : Union[str, Any] ): """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a , a ) def __call__( self : Tuple , a : Optional[int] , a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a : Union[List[List[int]], List[List[List[int]]]] = None , a : Optional[Union[List[int], List[List[int]]]] = None , a : bool = True , a : Union[bool, str, PaddingStrategy] = False , a : Union[bool, str, TruncationStrategy] = None , a : Optional[int] = None , a : int = 0 , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[bool] = None , a : bool = False , a : bool = False , a : bool = False , a : bool = False , a : bool = True , a : Optional[Union[str, TensorType]] = None , **a : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=a , return_tensors=a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a , a ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features['''words'''] __lowerCamelCase = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel values __lowerCamelCase = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(a , encoded_inputs['''overflow_to_sample_mapping'''] ) __lowerCamelCase = images return encoded_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Optional[Any] , a : str ): """simple docstring""" __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a ) != len(a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(a )} and {len(a )}""" ) return images_with_overflow def SCREAMING_SNAKE_CASE__ ( self : List[str] , *a : Optional[Any] , **a : Union[str, Any] ): """simple docstring""" return self.tokenizer.batch_decode(*a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *a : Union[str, Any] , **a : Tuple ): """simple docstring""" return self.tokenizer.decode(*a , **a ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a , ) return self.image_processor
67
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class snake_case : """simple docstring""" def __init__( self : Dict , __A : Tuple , ): __UpperCamelCase = parent __UpperCamelCase = 1_3 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = 2 __UpperCamelCase = 9_9 __UpperCamelCase = 0 __UpperCamelCase = 3_2 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 5_1_2 __UpperCamelCase = 1_6 __UpperCamelCase = 2 __UpperCamelCase = 0.02 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = 'last' __UpperCamelCase = True __UpperCamelCase = None __UpperCamelCase = 0 def _lowerCamelCase ( self : List[Any] ): __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) __UpperCamelCase = None if self.use_input_lengths: __UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def _lowerCamelCase ( self : Any , __A : Dict , __A : int , __A : Tuple , __A : Optional[int] , __A : Optional[int] , __A : Tuple , __A : List[str] , __A : Tuple , __A : Optional[int] , ): __UpperCamelCase = TFFlaubertModel(config=__A ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__A ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCamelCase ( self : str , __A : Any , __A : str , __A : List[str] , __A : Tuple , __A : List[str] , __A : Any , __A : str , __A : Dict , __A : int , ): __UpperCamelCase = TFFlaubertWithLMHeadModel(__A ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCamelCase ( self : Union[str, Any] , __A : int , __A : Tuple , __A : Dict , __A : int , __A : Tuple , __A : int , __A : Tuple , __A : Union[str, Any] , __A : Any , ): __UpperCamelCase = TFFlaubertForQuestionAnsweringSimple(__A ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = 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 : Dict , __A : List[str] , __A : List[Any] , __A : List[Any] , __A : Union[str, Any] , __A : str , __A : str , __A : List[str] , __A : Union[str, Any] , __A : List[Any] , ): __UpperCamelCase = TFFlaubertForSequenceClassification(__A ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _lowerCamelCase ( self : List[str] , __A : List[str] , __A : Dict , __A : Union[str, Any] , __A : List[Any] , __A : List[Any] , __A : str , __A : int , __A : int , __A : Union[str, Any] , ): __UpperCamelCase = self.num_labels __UpperCamelCase = TFFlaubertForTokenClassification(config=__A ) __UpperCamelCase = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __UpperCamelCase = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowerCamelCase ( self : int , __A : Dict , __A : List[str] , __A : List[str] , __A : Optional[Any] , __A : Union[str, Any] , __A : Optional[int] , __A : List[str] , __A : Optional[Any] , __A : Dict , ): __UpperCamelCase = self.num_choices __UpperCamelCase = TFFlaubertForMultipleChoice(config=__A ) __UpperCamelCase = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __UpperCamelCase = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowerCamelCase ( self : Dict ): __UpperCamelCase = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) = config_and_inputs __UpperCamelCase = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'langs': token_type_ids, 'lengths': input_lengths, } return config, inputs_dict @require_tf class snake_case ( __lowerCamelCase , __lowerCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any =( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) SCREAMING_SNAKE_CASE_ : List[Any] =( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable SCREAMING_SNAKE_CASE_ : Optional[Any] =( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ : List[str] =False SCREAMING_SNAKE_CASE_ : Optional[int] =False def _lowerCamelCase ( self : str , __A : Any , __A : int , __A : Optional[int] , __A : Tuple , __A : Optional[int] ): if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def _lowerCamelCase ( self : Tuple ): __UpperCamelCase = TFFlaubertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=__A , emb_dim=3_7 ) def _lowerCamelCase ( self : Optional[Any] ): self.config_tester.run_common_tests() def _lowerCamelCase ( self : Dict ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__A ) def _lowerCamelCase ( self : Union[str, Any] ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__A ) def _lowerCamelCase ( self : List[str] ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__A ) def _lowerCamelCase ( self : str ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__A ) def _lowerCamelCase ( self : Optional[int] ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*__A ) def _lowerCamelCase ( self : Union[str, Any] ): __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*__A ) @slow def _lowerCamelCase ( self : Optional[int] ): for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFFlaubertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_tf @require_sentencepiece @require_tokenizers class snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCamelCase ( self : Optional[int] ): __UpperCamelCase = TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased' ) __UpperCamelCase = tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" __UpperCamelCase = model(__A )[0] __UpperCamelCase = tf.TensorShape((1, 8, 5_1_2) ) self.assertEqual(output.shape , __A ) # compare the actual values for a slice. __UpperCamelCase = tf.convert_to_tensor( [ [ [-1.876_8773, -1.56_6555, 0.2707_2418], [-1.692_0038, -0.587_3505, 1.932_9599], [-2.956_3985, -1.699_3835, 1.797_2052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
53
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): """simple docstring""" super().__init__() __lowerCamelCase = nn.ModuleList(a ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : torch.FloatTensor , a : Union[torch.Tensor, float, int] , a : torch.Tensor , a : List[torch.tensor] , a : List[float] , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[Dict[str, Any]] = None , a : bool = False , a : bool = True , ): """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets ) ): __lowerCamelCase , __lowerCamelCase = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: __lowerCamelCase , __lowerCamelCase = down_samples, mid_sample else: __lowerCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self : Any , a : Union[str, os.PathLike] , a : bool = True , a : Callable = None , a : bool = False , a : Optional[str] = None , ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 __lowerCamelCase = model_path_to_save + f"""_{idx}""" @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[str] , a : Optional[Union[str, os.PathLike]] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __lowerCamelCase = pretrained_model_path while os.path.isdir(a ): __lowerCamelCase = ControlNetModel.from_pretrained(a , **a ) controlnets.append(a ) idx += 1 __lowerCamelCase = pretrained_model_path + f"""_{idx}""" logger.info(f"""{len(a )} controlnets loaded from {pretrained_model_path}.""" ) if len(a ) == 0: raise ValueError( f"""No ControlNets found under {os.path.dirname(a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(a )
67
0
"""simple docstring""" import numpy as np def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = int(np.ceil((x_end - xa) / h ) ) __SCREAMING_SNAKE_CASE = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE = ya __SCREAMING_SNAKE_CASE = xa for k in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f(lowerCAmelCase_ , y[k] ) __SCREAMING_SNAKE_CASE = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __SCREAMING_SNAKE_CASE = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) __SCREAMING_SNAKE_CASE = f(x + h , y[k] + h * ka ) __SCREAMING_SNAKE_CASE = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
54
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
0
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __snake_case ( UpperCAmelCase_ : Dict ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def __snake_case ( UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): lowerCamelCase_ = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue lowerCamelCase_ = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) lowerCamelCase_ = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) lowerCamelCase_ = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) lowerCamelCase_ = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) lowerCamelCase_ = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) lowerCamelCase_ = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) lowerCamelCase_ = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) lowerCamelCase_ = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) lowerCamelCase_ = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) lowerCamelCase_ = key.replace("image_encoder.module" , "flava.image_model" ) lowerCamelCase_ = key.replace("text_encoder.module" , "flava.text_model" ) lowerCamelCase_ = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) lowerCamelCase_ = key.replace("mm_encoder.module" , "flava.multimodal_model" ) lowerCamelCase_ = key.replace("text_projection" , "flava.text_projection" ) lowerCamelCase_ = key.replace("image_projection" , "flava.image_projection" ) lowerCamelCase_ = value.float() for key, value in codebook_state_dict.items(): lowerCamelCase_ = value return upgrade @torch.no_grad() def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict=None ): if config_path is not None: lowerCamelCase_ = FlavaConfig.from_pretrained(UpperCAmelCase_ ) else: lowerCamelCase_ = FlavaConfig() lowerCamelCase_ = FlavaForPreTraining(UpperCAmelCase_ ).eval() lowerCamelCase_ = convert_dalle_checkpoint(UpperCAmelCase_ , UpperCAmelCase_ , save_checkpoint=UpperCAmelCase_ ) if os.path.exists(UpperCAmelCase_ ): lowerCamelCase_ = torch.load(UpperCAmelCase_ , map_location="cpu" ) else: lowerCamelCase_ = torch.hub.load_state_dict_from_url(UpperCAmelCase_ , map_location="cpu" ) lowerCamelCase_ = upgrade_state_dict(UpperCAmelCase_ , UpperCAmelCase_ ) hf_model.load_state_dict(UpperCAmelCase_ ) lowerCamelCase_ = hf_model.state_dict() lowerCamelCase_ = count_parameters(UpperCAmelCase_ ) lowerCamelCase_ = count_parameters(UpperCAmelCase_ ) + count_parameters(UpperCAmelCase_ ) assert torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 ) hf_model.save_pretrained(UpperCAmelCase_ ) if __name__ == "__main__": a_ : Optional[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 flava checkpoint""") parser.add_argument("""--codebook_path""", default=None, type=str, help="""Path to flava codebook checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") a_ : Union[str, Any] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
55
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
'''simple docstring''' import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed a : Optional[Any] = 'true' def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=82, __UpperCAmelCase=16 ) -> str: '''simple docstring''' set_seed(42 ) snake_case_ = RegressionModel() snake_case_ = deepcopy(__UpperCAmelCase ) snake_case_ = RegressionDataset(length=__UpperCAmelCase ) snake_case_ = DataLoader(__UpperCAmelCase, batch_size=__UpperCAmelCase ) model.to(accelerator.device ) snake_case_ ,snake_case_ = accelerator.prepare(__UpperCAmelCase, __UpperCAmelCase ) return model, ddp_model, dataloader def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=False ) -> int: '''simple docstring''' snake_case_ = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) snake_case_ = load_dataset('''glue''', '''mrpc''', split='''validation''' ) def tokenize_function(__UpperCAmelCase ): snake_case_ = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=__UpperCAmelCase, max_length=__UpperCAmelCase ) return outputs with accelerator.main_process_first(): snake_case_ = dataset.map( __UpperCAmelCase, batched=__UpperCAmelCase, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], ) snake_case_ = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(__UpperCAmelCase ): if use_longest: return tokenizer.pad(__UpperCAmelCase, padding='''longest''', return_tensors='''pt''' ) return tokenizer.pad(__UpperCAmelCase, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return DataLoader(__UpperCAmelCase, shuffle=__UpperCAmelCase, collate_fn=__UpperCAmelCase, batch_size=16 ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> int: '''simple docstring''' snake_case_ = Accelerator(dispatch_batches=__UpperCAmelCase, split_batches=__UpperCAmelCase ) snake_case_ = get_dataloader(__UpperCAmelCase, not dispatch_batches ) snake_case_ = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''', return_dict=__UpperCAmelCase ) snake_case_ ,snake_case_ = accelerator.prepare(__UpperCAmelCase, __UpperCAmelCase ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> Any: '''simple docstring''' snake_case_ = [] for batch in dataloader: snake_case_ ,snake_case_ = batch.values() with torch.no_grad(): snake_case_ = model(__UpperCAmelCase ) snake_case_ ,snake_case_ = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) snake_case_ ,snake_case_ = [], [] for logit, targ in logits_and_targets: logits.append(__UpperCAmelCase ) targs.append(__UpperCAmelCase ) snake_case_ ,snake_case_ = torch.cat(__UpperCAmelCase ), torch.cat(__UpperCAmelCase ) return logits, targs def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase=82, __UpperCAmelCase=False, __UpperCAmelCase=False, __UpperCAmelCase=16 ) -> Dict: '''simple docstring''' snake_case_ ,snake_case_ ,snake_case_ = get_basic_setup(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) snake_case_ ,snake_case_ = generate_predictions(__UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) assert ( len(__UpperCAmelCase ) == num_samples ), F"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(__UpperCAmelCase )}" def __magic_name__ ( __UpperCAmelCase = False, __UpperCAmelCase = False ) -> Union[str, Any]: '''simple docstring''' snake_case_ = evaluate.load('''glue''', '''mrpc''' ) snake_case_ ,snake_case_ = get_mrpc_setup(__UpperCAmelCase, __UpperCAmelCase ) # First do baseline snake_case_ ,snake_case_ ,snake_case_ = setup['''no'''] model.to(__UpperCAmelCase ) model.eval() for batch in dataloader: batch.to(__UpperCAmelCase ) with torch.inference_mode(): snake_case_ = model(**__UpperCAmelCase ) snake_case_ = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=__UpperCAmelCase, references=batch['''labels'''] ) snake_case_ = metric.compute() # Then do distributed snake_case_ ,snake_case_ ,snake_case_ = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): snake_case_ = model(**__UpperCAmelCase ) snake_case_ = outputs.logits.argmax(dim=-1 ) snake_case_ = batch['''labels'''] snake_case_ ,snake_case_ = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=__UpperCAmelCase, references=__UpperCAmelCase ) snake_case_ = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key], distributed[key] ), F"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n" def __magic_name__ ( ) -> Union[str, Any]: '''simple docstring''' snake_case_ = Accelerator(split_batches=__UpperCAmelCase, dispatch_batches=__UpperCAmelCase ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('''**Testing gather_for_metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`" ) test_mrpc(__UpperCAmelCase, __UpperCAmelCase ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test torch metrics**''' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: snake_case_ = Accelerator(split_batches=__UpperCAmelCase, dispatch_batches=__UpperCAmelCase ) if accelerator.is_local_main_process: print(F"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99" ) test_torch_metrics(__UpperCAmelCase, 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) snake_case_ = Accelerator() test_torch_metrics(__UpperCAmelCase, 512 ) accelerator.state._reset_state() def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' main() if __name__ == "__main__": main()
56
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = '''ylacombe/bark-small''' __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = '''en_speaker_1''' __lowerCamelCase = '''This is a test string''' __lowerCamelCase = '''speaker_embeddings_path.json''' __lowerCamelCase = '''speaker_embeddings''' def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Dict ): """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __lowerCamelCase = 35 __lowerCamelCase = 2 __lowerCamelCase = 8 __lowerCamelCase = { '''semantic_prompt''': np.ones(a ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from npz file __lowerCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(a , **a ) __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from the hub __lowerCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) __lowerCamelCase = processor(text=self.input_string ) __lowerCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
67
0
"""simple docstring""" def _lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , ): '''simple docstring''' __lowerCAmelCase = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError("All input parameters must be positive" ) if any(p > 1 for p in parameters[1:4] ): raise ValueError("Relative densities cannot be greater than one" ) else: __lowerCAmelCase = 1 - (matter_density + radiation_density + dark_energy) __lowerCAmelCase = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCAmelCase = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation A : Tuple = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
57
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
'''simple docstring''' import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) set_seed(770) lowercase_ = { """c_attn""": """att_proj""", """c_proj""": """out_proj""", """c_fc""": """in_proj""", """transformer.""": """""", """h.""": """layers.""", """ln_1""": """layernorm_1""", """ln_2""": """layernorm_2""", """ln_f""": """layernorm_final""", """wpe""": """position_embeds_layer""", """wte""": """input_embeds_layer""", } lowercase_ = { """text_small""": { """repo_id""": """suno/bark""", """file_name""": """text.pt""", }, """coarse_small""": { """repo_id""": """suno/bark""", """file_name""": """coarse.pt""", }, """fine_small""": { """repo_id""": """suno/bark""", """file_name""": """fine.pt""", }, """text""": { """repo_id""": """suno/bark""", """file_name""": """text_2.pt""", }, """coarse""": { """repo_id""": """suno/bark""", """file_name""": """coarse_2.pt""", }, """fine""": { """repo_id""": """suno/bark""", """file_name""": """fine_2.pt""", }, } lowercase_ = os.path.dirname(os.path.abspath(__file__)) lowercase_ = os.path.join(os.path.expanduser("""~"""), """.cache""") lowercase_ = os.path.join(os.getenv("""XDG_CACHE_HOME""", default_cache_dir), """suno""", """bark_v0""") def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Tuple=False ) ->Any: _SCREAMING_SNAKE_CASE = model_type if use_small: key += "_small" return os.path.join(__lowerCamelCase , REMOTE_MODEL_PATHS[key]["""file_name"""] ) def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : int ) ->Any: os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) hf_hub_download(repo_id=__lowerCamelCase , filename=__lowerCamelCase , local_dir=__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : Dict=False , __lowerCamelCase : Optional[int]="text" ) ->Optional[int]: if model_type == "text": _SCREAMING_SNAKE_CASE = BarkSemanticModel _SCREAMING_SNAKE_CASE = BarkSemanticConfig _SCREAMING_SNAKE_CASE = BarkSemanticGenerationConfig elif model_type == "coarse": _SCREAMING_SNAKE_CASE = BarkCoarseModel _SCREAMING_SNAKE_CASE = BarkCoarseConfig _SCREAMING_SNAKE_CASE = BarkCoarseGenerationConfig elif model_type == "fine": _SCREAMING_SNAKE_CASE = BarkFineModel _SCREAMING_SNAKE_CASE = BarkFineConfig _SCREAMING_SNAKE_CASE = BarkFineGenerationConfig else: raise NotImplementedError() _SCREAMING_SNAKE_CASE = F'{model_type}_small' if use_small else model_type _SCREAMING_SNAKE_CASE = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(__lowerCamelCase ): logger.info(F'{model_type} model not found, downloading into `{CACHE_DIR}`.' ) _download(model_info["""repo_id"""] , model_info["""file_name"""] ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location=__lowerCamelCase ) # this is a hack _SCREAMING_SNAKE_CASE = checkpoint["""model_args"""] if "input_vocab_size" not in model_args: _SCREAMING_SNAKE_CASE = model_args["""vocab_size"""] _SCREAMING_SNAKE_CASE = model_args["""vocab_size"""] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments _SCREAMING_SNAKE_CASE = model_args.pop("""n_head""" ) _SCREAMING_SNAKE_CASE = model_args.pop("""n_embd""" ) _SCREAMING_SNAKE_CASE = model_args.pop("""n_layer""" ) _SCREAMING_SNAKE_CASE = ConfigClass(**checkpoint["""model_args"""] ) _SCREAMING_SNAKE_CASE = ModelClass(config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = GenerationConfigClass() _SCREAMING_SNAKE_CASE = model_generation_config _SCREAMING_SNAKE_CASE = checkpoint["""model"""] # fixup checkpoint _SCREAMING_SNAKE_CASE = """_orig_mod.""" for k, v in list(state_dict.items() ): if k.startswith(__lowerCamelCase ): # replace part of the key with corresponding layer name in HF implementation _SCREAMING_SNAKE_CASE = k[len(__lowerCamelCase ) :] for old_layer_name in new_layer_name_dict: _SCREAMING_SNAKE_CASE = new_k.replace(__lowerCamelCase , new_layer_name_dict[old_layer_name] ) _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = set(state_dict.keys() ) - set(model.state_dict().keys() ) _SCREAMING_SNAKE_CASE = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} _SCREAMING_SNAKE_CASE = set(model.state_dict().keys() ) - set(state_dict.keys() ) _SCREAMING_SNAKE_CASE = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(__lowerCamelCase ) != 0: raise ValueError(F'extra keys found: {extra_keys}' ) if len(__lowerCamelCase ) != 0: raise ValueError(F'missing keys: {missing_keys}' ) model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = model.num_parameters(exclude_embeddings=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = checkpoint["""best_val_loss"""].item() logger.info(F'model loaded: {round(n_params/1e6 , 1 )}M params, {round(__lowerCamelCase , 3 )} loss' ) model.eval() model.to(__lowerCamelCase ) del checkpoint, state_dict return model def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any=False , __lowerCamelCase : Union[str, Any]="text" ) ->Tuple: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() _SCREAMING_SNAKE_CASE = """cpu""" # do conversion on cpu _SCREAMING_SNAKE_CASE = _get_ckpt_path(__lowerCamelCase , use_small=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = _load_model(__lowerCamelCase , __lowerCamelCase , model_type=__lowerCamelCase , use_small=__lowerCamelCase ) # load bark initial model _SCREAMING_SNAKE_CASE = _bark_load_model(__lowerCamelCase , """cpu""" , model_type=__lowerCamelCase , use_small=__lowerCamelCase ) if model_type == "text": _SCREAMING_SNAKE_CASE = bark_model["""model"""] if model.num_parameters(exclude_embeddings=__lowerCamelCase ) != bark_model.get_num_params(): raise ValueError("""initial and new models don't have the same number of parameters""" ) # check if same output as the bark model _SCREAMING_SNAKE_CASE = 5 _SCREAMING_SNAKE_CASE = 10 if model_type in ["text", "coarse"]: _SCREAMING_SNAKE_CASE = torch.randint(256 , (batch_size, sequence_length) , dtype=torch.int ) _SCREAMING_SNAKE_CASE = bark_model(__lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) # take last logits _SCREAMING_SNAKE_CASE = output_new_model_total.logits[:, [-1], :] else: _SCREAMING_SNAKE_CASE = 3 _SCREAMING_SNAKE_CASE = 8 _SCREAMING_SNAKE_CASE = torch.randint(256 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) _SCREAMING_SNAKE_CASE = model(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = bark_model(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don't have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) model.save_pretrained(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] , ) ->List[str]: _SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = BarkSemanticConfig.from_pretrained(os.path.join(__lowerCamelCase , """config.json""" ) ) _SCREAMING_SNAKE_CASE = BarkCoarseConfig.from_pretrained(os.path.join(__lowerCamelCase , """config.json""" ) ) _SCREAMING_SNAKE_CASE = BarkFineConfig.from_pretrained(os.path.join(__lowerCamelCase , """config.json""" ) ) _SCREAMING_SNAKE_CASE = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) _SCREAMING_SNAKE_CASE = BarkSemanticModel.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = BarkCoarseModel.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = BarkFineModel.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) _SCREAMING_SNAKE_CASE = BarkConfig.from_sub_model_configs( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) _SCREAMING_SNAKE_CASE = BarkModel(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = semantic _SCREAMING_SNAKE_CASE = coarseAcoustic _SCREAMING_SNAKE_CASE = fineAcoustic _SCREAMING_SNAKE_CASE = codec _SCREAMING_SNAKE_CASE = bark_generation_config Path(__lowerCamelCase ).mkdir(exist_ok=__lowerCamelCase ) bark.save_pretrained(__lowerCamelCase , repo_id=__lowerCamelCase , push_to_hub=__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("""model_type""", type=str, help="""text, coarse or fine.""") parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--is_small""", action="""store_true""", help="""convert the small version instead of the large.""") lowercase_ = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
58
'''simple docstring''' import re from filelock import FileLock try: import nltk __UpperCAmelCase =True except (ImportError, ModuleNotFoundError): __UpperCAmelCase =False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: re.sub('''<n>''' , '''''' , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
67
0
import inspect import os import unittest from pathlib import Path import torch import accelerate from accelerate.test_utils import execute_subprocess_async from accelerate.test_utils.testing import run_command class UpperCAmelCase ( unittest.TestCase ): A__ : List[str] = inspect.getfile(accelerate.test_utils ) A__ : List[str] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_cli.py"] ) A__ : Tuple = ["accelerate", "launch"] A__ : int = Path.home() / ".cache/huggingface/accelerate" A__ : Tuple = "default_config.yaml" A__ : List[Any] = config_folder / config_file A__ : List[Any] = config_folder / "_default_config.yaml" A__ : List[str] = Path("tests/test_configs" ) @classmethod def _SCREAMING_SNAKE_CASE (cls : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if cls.config_path.is_file(): cls.config_path.rename(cls.changed_path ) @classmethod def _SCREAMING_SNAKE_CASE (cls : Optional[Any] ) -> Optional[int]: '''simple docstring''' if cls.changed_path.is_file(): cls.changed_path.rename(cls.config_path ) def _SCREAMING_SNAKE_CASE (self : str ) -> Dict: '''simple docstring''' snake_case : int = self.base_cmd if torch.cuda.is_available() and (torch.cuda.device_count() > 1): cmd += ["--multi_gpu"] execute_subprocess_async(cmd + [self.test_file_path] , env=os.environ.copy() ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> Tuple: '''simple docstring''' for config in sorted(self.test_config_path.glob("**/*.yaml" ) ): with self.subTest(config_file=snake_case__ ): execute_subprocess_async( self.base_cmd + ["--config_file", str(snake_case__ ), self.test_file_path] , env=os.environ.copy() ) def _SCREAMING_SNAKE_CASE (self : Union[str, Any] ) -> Dict: '''simple docstring''' execute_subprocess_async(["accelerate", "test"] , env=os.environ.copy() ) class UpperCAmelCase ( unittest.TestCase ): A__ : List[Any] = "test-tpu" A__ : int = "us-central1-a" A__ : Any = "ls" A__ : int = ["accelerate", "tpu-config"] A__ : Dict = "cd /usr/share" A__ : List[Any] = "tests/test_samples/test_command_file.sh" A__ : Optional[int] = "Running gcloud compute tpus tpu-vm ssh" def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> int: '''simple docstring''' snake_case : List[str] = run_command( self.cmd + ["--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug"] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Any: '''simple docstring''' snake_case : Tuple = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command", self.command, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : Any ) -> int: '''simple docstring''' snake_case : Any = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--debug"] , return_stdout=snake_case__ ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Optional[int]: '''simple docstring''' snake_case : str = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--debug"] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : int ) -> Dict: '''simple docstring''' snake_case : Union[str, Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--command", self.command, "--command", "echo \"Hello World\"", "--debug", ] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo \"Hello World\" --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : Optional[int] ) -> List[str]: '''simple docstring''' snake_case : List[Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--command_file", self.command_file, "--debug"] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : Optional[Any] ) -> Tuple: '''simple docstring''' snake_case : Any = run_command( self.cmd + [ "--config_file", "tests/test_configs/0_12_0.yaml", "--command_file", self.command_file, "--tpu_zone", self.tpu_zone, "--tpu_name", self.tpu_name, "--debug", ] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo \"hello world\"; echo \"this is a second command\" --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : List[str] ) -> Optional[int]: '''simple docstring''' snake_case : List[Any] = run_command( self.cmd + ["--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--debug"] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo \"hello world\"; echo \"this is a second command\" --worker all""" , snake_case__ , ) def _SCREAMING_SNAKE_CASE (self : List[Any] ) -> Optional[int]: '''simple docstring''' snake_case : Optional[Any] = run_command( self.cmd + [ "--config_file", "tests/test_configs/latest.yaml", "--install_accelerate", "--accelerate_version", "12.0.0", "--debug", ] , return_stdout=snake_case__ , ) self.assertIn( f"""{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo \"hello world\"; echo \"this is a second command\" --worker all""" , snake_case__ , )
59
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] ="gpt_neox_japanese" def __init__( self : List[Any] , a : Tuple=3_20_00 , a : Dict=25_60 , a : Union[str, Any]=32 , a : Dict=32 , a : Dict=4 , a : Optional[Any]="gelu" , a : Any=1.00 , a : str=1_00_00 , a : List[str]=20_48 , a : str=0.02 , a : Union[str, Any]=1e-5 , a : Optional[Any]=True , a : str=3_19_96 , a : List[str]=3_19_99 , a : str=0.1 , a : Union[str, Any]=0.0 , **a : Optional[Any] , ): """simple docstring""" super().__init__(bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_multiple_size __lowerCamelCase = hidden_act __lowerCamelCase = rotary_pct __lowerCamelCase = rotary_emb_base __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = attention_dropout __lowerCamelCase = hidden_dropout
67
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging snake_case__ : Optional[int] = logging.get_logger(__name__) snake_case__ : List[Any] = { '''EleutherAI/gpt-neo-1.3B''': '''https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json''', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class snake_case_( a__ ): __UpperCamelCase = '''gpt_neo''' __UpperCamelCase = ['''past_key_values'''] __UpperCamelCase = {'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , UpperCamelCase_ : Union[str, Any]=5_0_2_5_7 , UpperCamelCase_ : List[Any]=2_0_4_8 , UpperCamelCase_ : Optional[int]=2_0_4_8 , UpperCamelCase_ : List[str]=2_4 , UpperCamelCase_ : Dict=[[["global", "local"], 1_2]] , UpperCamelCase_ : List[Any]=1_6 , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Tuple=2_5_6 , UpperCamelCase_ : Tuple="gelu_new" , UpperCamelCase_ : List[str]=0.0 , UpperCamelCase_ : int=0.0 , UpperCamelCase_ : List[Any]=0.0 , UpperCamelCase_ : Dict=0.1 , UpperCamelCase_ : Union[str, Any]=1E-5 , UpperCamelCase_ : Dict=0.02 , UpperCamelCase_ : List[str]=True , UpperCamelCase_ : str=5_0_2_5_6 , UpperCamelCase_ : Tuple=5_0_2_5_6 , **UpperCamelCase_ : Optional[int] , ): lowerCAmelCase : Optional[Any] = vocab_size lowerCAmelCase : str = max_position_embeddings lowerCAmelCase : Optional[Any] = hidden_size lowerCAmelCase : Any = num_layers lowerCAmelCase : Union[str, Any] = num_heads lowerCAmelCase : int = intermediate_size lowerCAmelCase : Optional[Any] = window_size lowerCAmelCase : str = activation_function lowerCAmelCase : str = resid_dropout lowerCAmelCase : Dict = embed_dropout lowerCAmelCase : List[str] = attention_dropout lowerCAmelCase : List[str] = classifier_dropout lowerCAmelCase : str = layer_norm_epsilon lowerCAmelCase : Optional[Any] = initializer_range lowerCAmelCase : List[Any] = use_cache lowerCAmelCase : Optional[Any] = bos_token_id lowerCAmelCase : int = eos_token_id lowerCAmelCase : List[str] = attention_types lowerCAmelCase : Optional[int] = self.expand_attention_types_params(UpperCamelCase_ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.attention_layers)` == `config.num_layers` ''' F'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, ''' F'''`config.num_layers = {self.num_layers}`. ''' '''`config.attention_layers` is prepared using `config.attention_types`. ''' '''Please verify the value of `config.attention_types` argument.''' ) super().__init__(bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ ) @staticmethod def lowerCamelCase__ ( UpperCamelCase_ : Optional[Any] ): lowerCAmelCase : Any = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _snake_case ( _snake_case : Any , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : Optional[int] ): import torch lowerCAmelCase : Any = input.size() lowerCAmelCase : List[Any] = len(_snake_case ) lowerCAmelCase : Union[str, Any] = shape[dimension] lowerCAmelCase : List[Any] = torch.arange(0 , _snake_case , _snake_case ) lowerCAmelCase : int = torch.div(sizedim - size , _snake_case , rounding_mode='''floor''' ) + 1 lowerCAmelCase : List[Any] = torch.arange(_snake_case ) + low_indices[:min_length][:, None] lowerCAmelCase : Optional[Any] = [slice(_snake_case )] * rank lowerCAmelCase : Optional[int] = indices lowerCAmelCase : Dict = input[s] lowerCAmelCase : str = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(_snake_case ) def _snake_case ( _snake_case : Optional[Any] , _snake_case : Optional[int] ): import torch lowerCAmelCase : Optional[Any] = torch.arange(1 , _snake_case ) lowerCAmelCase : List[Any] = torch.remainder(_snake_case , _snake_case ) lowerCAmelCase : Optional[int] = remainders == 0 lowerCAmelCase : Tuple = candidates[divisor_indices] lowerCAmelCase : Dict = torch.max(_snake_case ) return largest_divisor, torch.div(_snake_case , _snake_case , rounding_mode='''floor''' ) class snake_case_( a__ ): @property def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Dict = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: self.fill_with_past_key_values_(UpperCamelCase_ , direction='''inputs''' ) lowerCAmelCase : str = {0: '''batch''', 1: '''past_sequence + sequence'''} else: lowerCAmelCase : List[str] = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def lowerCamelCase__ ( self : Union[str, Any] ): return self._config.num_heads def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : PreTrainedTokenizer , UpperCamelCase_ : int = -1 , UpperCamelCase_ : int = -1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[TensorType] = None , ): lowerCAmelCase : int = super(UpperCamelCase_ , self ).generate_dummy_inputs( UpperCamelCase_ , batch_size=UpperCamelCase_ , seq_length=UpperCamelCase_ , is_pair=UpperCamelCase_ , framework=UpperCamelCase_ ) # We need to order the input in the way they appears in the forward() lowerCAmelCase : Dict = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowerCAmelCase, lowerCAmelCase : int = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowerCAmelCase : List[Any] = seqlen + 2 lowerCAmelCase : Optional[int] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCAmelCase : int = [ (torch.zeros(UpperCamelCase_ ), torch.zeros(UpperCamelCase_ )) for _ in range(self.num_layers ) ] lowerCAmelCase : str = common_inputs['''attention_mask'''] if self.use_past: lowerCAmelCase : List[Any] = ordered_inputs['''attention_mask'''].dtype lowerCAmelCase : Dict = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(UpperCamelCase_ , UpperCamelCase_ , dtype=UpperCamelCase_ )] , dim=1 ) return ordered_inputs @property def lowerCamelCase__ ( self : Tuple ): return 1_3
60
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase =int(input("Enter the first number: ").strip()) __UpperCAmelCase =int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
67
0
"""simple docstring""" from __future__ import annotations def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): if days_between_payments <= 0: raise ValueError("days_between_payments must be > 0" ) if daily_interest_rate < 0: raise ValueError("daily_interest_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * daily_interest_rate * days_between_payments def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, ): if number_of_compounding_periods <= 0: raise ValueError("number_of_compounding_periods must be > 0" ) if nominal_annual_interest_rate_percentage < 0: raise ValueError("nominal_annual_interest_rate_percentage must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def __a ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, ): if number_of_years <= 0: raise ValueError("number_of_years must be > 0" ) if nominal_annual_percentage_rate < 0: raise ValueError("nominal_annual_percentage_rate must be >= 0" ) if principal <= 0: raise ValueError("principal must be > 0" ) return compound_interest( __lowerCamelCase, nominal_annual_percentage_rate / 365, number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
61
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class UpperCAmelCase__ ( unittest.TestCase ): """simple docstring""" def _a ( self ) -> Union[str, Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =tokenizer.decode(greedy_ids[0] ) __UpperCamelCase =TextIteratorStreamer(A_ ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text self.assertEqual(A_ , A_ ) def _a ( self ) -> List[Any]: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =model.generate(A_ , max_new_tokens=10 , do_sample=A_ ) __UpperCamelCase =greedy_ids[:, input_ids.shape[1] :] __UpperCamelCase =tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_prompt=A_ ) model.generate(A_ , max_new_tokens=10 , do_sample=A_ , streamer=A_ ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer __UpperCamelCase =cs.out[:-1] self.assertEqual(A_ , A_ ) def _a ( self ) -> Any: # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them __UpperCamelCase =AutoTokenizer.from_pretrained('distilgpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('distilgpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =torch.ones((1, 5) , device=A_ ).long() * model.config.bos_token_id with CaptureStdout() as cs: __UpperCamelCase =TextStreamer(A_ , skip_special_tokens=A_ ) model.generate(A_ , max_new_tokens=1 , do_sample=A_ , streamer=A_ ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token __UpperCamelCase =cs.out[:-1] # Remove the final "\n" __UpperCamelCase =tokenizer(A_ , return_tensors='pt' ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def _a ( self ) -> Tuple: __UpperCamelCase =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) __UpperCamelCase =AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(A_ ) __UpperCamelCase =-1 __UpperCamelCase =ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(A_ ) __UpperCamelCase =TextIteratorStreamer(A_ , timeout=0.001 ) __UpperCamelCase ={'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} __UpperCamelCase =Thread(target=model.generate , kwargs=A_ ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(A_ ): __UpperCamelCase ='' for new_text in streamer: streamer_text += new_text
62
'''simple docstring''' import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ), f"""{len(UpperCamelCase__ )} != {len(UpperCamelCase__ )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __UpperCAmelCase ={ # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __UpperCAmelCase ={ # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: try: __lowerCamelCase = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" f""" {n_student}""" ) return list(range(UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[int]: if n_student > n_teacher: raise ValueError(f"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(UpperCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = "student" , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__=False , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __lowerCamelCase = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(UpperCamelCase__ , UpperCamelCase__ ): AutoTokenizer.from_pretrained(UpperCamelCase__ ).save_pretrained(UpperCamelCase__ ) # purely for convenience __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ).eval() else: assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), f"""teacher must be a model or string got type {type(UpperCamelCase__ )}""" __lowerCamelCase = teacher.config.to_diff_dict() try: __lowerCamelCase , __lowerCamelCase = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): __lowerCamelCase , __lowerCamelCase = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __lowerCamelCase , __lowerCamelCase = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(UpperCamelCase__ ) # Copy weights __lowerCamelCase = teacher.config_class(**UpperCamelCase__ ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_config(UpperCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __lowerCamelCase = student.load_state_dict(teacher.state_dict() , strict=UpperCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __lowerCamelCase , __lowerCamelCase = list(range(UpperCamelCase__ ) ), list(range(UpperCamelCase__ ) ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" f""" {save_path}""" ) student.save_pretrained(UpperCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) if d_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) try: if hasattr( UpperCamelCase__ , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , UpperCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , UpperCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , UpperCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , UpperCamelCase__ ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __lowerCamelCase = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(UpperCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
67
0
'''simple docstring''' def _lowerCamelCase ( lowercase : int = 50 ) -> int: _a = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(f"""{solution() = }""")
63
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __UpperCAmelCase =["gpt2"] __UpperCAmelCase ="gpt2" if is_tf_available(): class a__ ( tf.Module ): def __init__( self : str , a : Union[str, Any] ): """simple docstring""" super().__init__() __lowerCamelCase = tokenizer __lowerCamelCase = AutoConfig.from_pretrained(a ) __lowerCamelCase = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = self.tokenizer(a ) __lowerCamelCase = tokenized['''input_ids'''].to_tensor() __lowerCamelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase = self.model(input_ids=a , attention_mask=a )['''logits'''] return outputs @require_tf @require_keras_nlp class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" super().setUp() __lowerCamelCase = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowerCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase = tokenizer([test_inputs] , return_tensors='''tf''' ) __lowerCamelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase = python_outputs[key].numpy() __lowerCamelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase = tf.constant(a ) __lowerCamelCase = compiled_tokenizer(a ) __lowerCamelCase = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = ModelToSave(tokenizer=a ) __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase = Path(a ) / '''saved.model''' tf.saved_model.save(a , a , signatures={'''serving_default''': model.serving} ) __lowerCamelCase = tf.saved_model.load(a ) __lowerCamelCase = loaded_model.signatures['''serving_default'''](a )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase = tf_tokenizer.get_config() __lowerCamelCase = TFGPTaTokenizer.from_config(a ) __lowerCamelCase = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase = 12_31_23 for max_length in [3, 5, 10_24]: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a , max_length=a ) __lowerCamelCase = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
67
0
"""simple docstring""" import requests A_ = '''YOUR API KEY''' def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str = giphy_api_key ): """simple docstring""" _snake_case : List[Any] = """+""".join(query.split() ) _snake_case : Optional[int] = F"https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}" _snake_case : int = requests.get(snake_case__ ).json()["""data"""] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('''\n'''.join(get_gifs('''space ship''')))
64
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
67
0
import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) UpperCamelCase__ = logging.getLogger(__name__) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=3_0_5_2_2, type=int) UpperCamelCase__ = parser.parse_args() logger.info(f'''Loading data from {args.data_file}''') with open(args.data_file, 'rb') as fp: UpperCamelCase__ = pickle.load(fp) logger.info('Counting occurrences for MLM.') UpperCamelCase__ = Counter() for tk_ids in data: counter.update(tk_ids) UpperCamelCase__ = [0] * args.vocab_size for k, v in counter.items(): UpperCamelCase__ = v logger.info(f'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, 'wb') as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
65
'''simple docstring''' import logging import os from .state import PartialState class a__ ( logging.LoggerAdapter ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a : Optional[Any] ): """simple docstring""" __lowerCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[int] , a : str , *a : Optional[int] , **a : List[Any] ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __lowerCamelCase = kwargs.pop('''main_process_only''' , a ) __lowerCamelCase = kwargs.pop('''in_order''' , a ) if self.isEnabledFor(a ): if self._should_log(a ): __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) elif in_order: __lowerCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) state.wait_for_everyone() def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = None ) -> Optional[int]: if log_level is None: __lowerCamelCase = os.environ.get('''ACCELERATE_LOG_LEVEL''' , UpperCamelCase__ ) __lowerCamelCase = logging.getLogger(UpperCamelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(UpperCamelCase__ , {} )
67
0
"""simple docstring""" import argparse import os import torch from transformers import FlavaImageCodebook, FlavaImageCodebookConfig def A_ ( _lowercase, _lowercase, _lowercase, _lowercase ): '''simple docstring''' snake_case_ :Dict = s.rsplit(_lowercase, _lowercase ) return new.join(_lowercase ) def A_ ( _lowercase ): '''simple docstring''' return sum(param.float().sum() if """encoder.embeddings""" not in key else 0 for key, param in state_dict.items() ) def A_ ( _lowercase ): '''simple docstring''' snake_case_ :Tuple = {} snake_case_ :Union[str, Any] = ["""group_1""", """group_2""", """group_3""", """group_4"""] for key, value in state_dict.items(): for group_key in group_keys: if group_key in key: snake_case_ :int = key.replace(f"""{group_key}.""", f"""{group_key}.group.""" ) if "res_path" in key: snake_case_ :Tuple = key.replace("""res_path.""", """res_path.path.""" ) if key.endswith(""".w""" ): snake_case_ :List[str] = rreplace(_lowercase, """.w""", """.weight""", 1 ) if key.endswith(""".b""" ): snake_case_ :Dict = rreplace(_lowercase, """.b""", """.bias""", 1 ) snake_case_ :Union[str, Any] = value.float() return upgrade @torch.no_grad() def A_ ( _lowercase, _lowercase, _lowercase=None, _lowercase=True ): '''simple docstring''' from dall_e import Encoder snake_case_ :Tuple = Encoder() if os.path.exists(_lowercase ): snake_case_ :Any = torch.load(_lowercase ) else: snake_case_ :str = torch.hub.load_state_dict_from_url(_lowercase ) if isinstance(_lowercase, _lowercase ): snake_case_ :str = ckpt.state_dict() encoder.load_state_dict(_lowercase ) if config_path is not None: snake_case_ :Tuple = FlavaImageCodebookConfig.from_pretrained(_lowercase ) else: snake_case_ :int = FlavaImageCodebookConfig() snake_case_ :List[Any] = FlavaImageCodebook(_lowercase ).eval() snake_case_ :Union[str, Any] = encoder.state_dict() snake_case_ :List[Any] = upgrade_state_dict(_lowercase ) hf_model.load_state_dict(_lowercase ) snake_case_ :str = hf_model.state_dict() snake_case_ :Tuple = count_parameters(_lowercase ) snake_case_ :Optional[Any] = count_parameters(_lowercase ) assert torch.allclose(_lowercase, _lowercase, atol=1e-3 ) if save_checkpoint: hf_model.save_pretrained(_lowercase ) else: return hf_state_dict if __name__ == "__main__": __a = 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 flava checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") __a = parser.parse_args() convert_dalle_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
66
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = set({'''(''', '''[''', '''{'''} ) __lowerCamelCase = set({''')''', ''']''', '''}'''} ) __lowerCamelCase = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def __lowerCAmelCase ( ) -> str: __lowerCamelCase = input('''Enter sequence of brackets: ''' ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , '''is balanced''' ) else: print(UpperCamelCase__ , '''is not balanced''' ) if __name__ == "__main__": main()
67
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: Optional[Any] ) -> Tuple: '''simple docstring''' A__ = b.T A__ = np.sum(np.square(SCREAMING_SNAKE_CASE_ ) , axis=1 ) A__ = np.sum(np.square(SCREAMING_SNAKE_CASE_ ) , axis=0 ) A__ = np.matmul(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ = aa[:, None] - 2 * ab + ba[None, :] return d def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> Dict: '''simple docstring''' A__ = x.reshape(-1 , 3 ) A__ = squared_euclidean_distance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return np.argmin(SCREAMING_SNAKE_CASE_ , axis=1 ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = None , lowercase = True , lowercase = None , lowercase = PILImageResampling.BILINEAR , lowercase = True , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 256, "width": 256} A__ = get_size_dict(lowercase ) A__ = np.array(lowercase ) if clusters is not None else None A__ = do_resize A__ = size A__ = resample A__ = do_normalize A__ = do_color_quantize def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BILINEAR , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( lowercase , size=(size["height"], size["width"]) , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , ) -> np.ndarray: '''simple docstring''' A__ = rescale(image=lowercase , scale=1 / 127.5 , data_format=lowercase ) A__ = image - 1 return image def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = size if size is not None else self.size A__ = get_size_dict(lowercase ) A__ = resample if resample is not None else self.resample A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize A__ = clusters if clusters is not None else self.clusters A__ = np.array(lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): 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 or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True." ) # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase ) for image in images] if do_color_quantize: A__ = [to_channel_dimension_format(lowercase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) A__ = np.array(lowercase ) A__ = color_quantize(lowercase , lowercase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) A__ = images.shape[0] A__ = images.reshape(lowercase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. A__ = list(lowercase ) else: A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = {"input_ids": images} return BatchFeature(data=lowercase , tensor_type=lowercase )
68
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict ="M-CLIP" def __init__( self : Tuple , a : Optional[int]=10_24 , a : Tuple=7_68 , **a : List[str] ): """simple docstring""" __lowerCamelCase = transformerDimSize __lowerCamelCase = imageDimSize super().__init__(**a ) class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =MCLIPConfig def __init__( self : str , a : List[Any] , *a : Dict , **a : str ): """simple docstring""" super().__init__(a , *a , **a ) __lowerCamelCase = XLMRobertaModel(a ) __lowerCamelCase = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.transformer(input_ids=a , attention_mask=a )[0] __lowerCamelCase = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a ), embs
67
0
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __UpperCamelCase = abspath(join(dirname(dirname(dirname(__file__))), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def UpperCAmelCase ( UpperCAmelCase ) -> int: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase ) -> int: from transformers.testing_utils import pytest_terminal_summary_main snake_case_ = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(UpperCAmelCase , id=UpperCAmelCase )
69
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
67
0
'''simple docstring''' from multiprocessing import Lock, Pipe, Process # lock used to ensure that two processes do not access a pipe at the same time A__ : Optional[Any] =Lock() def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" global process_lock # we perform n swaps since after n swaps we know we are sorted # we *could* stop early if we are sorted already, but it takes as long to # find out we are sorted as it does to sort the list with this algorithm for i in range(0 , 10 ): if (i + position) % 2 == 0 and r_send is not None: # send your value to your right neighbor process_lock.acquire() r_send[1].send(lowerCAmelCase ) process_lock.release() # receive your right neighbor's value process_lock.acquire() _lowerCAmelCase = rr_cv[0].recv() process_lock.release() # take the lower value since you are on the left _lowerCAmelCase = min(lowerCAmelCase , lowerCAmelCase ) elif (i + position) % 2 != 0 and l_send is not None: # send your value to your left neighbor process_lock.acquire() l_send[1].send(lowerCAmelCase ) process_lock.release() # receive your left neighbor's value process_lock.acquire() _lowerCAmelCase = lr_cv[0].recv() process_lock.release() # take the higher value since you are on the right _lowerCAmelCase = max(lowerCAmelCase , lowerCAmelCase ) # after all swaps are performed, send the values back to main result_pipe[1].send(lowerCAmelCase ) def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = [] # initialize the list of pipes where the values will be retrieved for _ in arr: result_pipe.append(Pipe() ) # creates the processes # the first and last process only have one neighbor so they are made outside # of the loop _lowerCAmelCase = Pipe() _lowerCAmelCase = Pipe() process_array_.append( Process( target=lowerCAmelCase , args=(0, arr[0], None, temp_rs, None, temp_rr, result_pipe[0]) , ) ) _lowerCAmelCase = temp_rs _lowerCAmelCase = temp_rr for i in range(1 , len(lowerCAmelCase ) - 1 ): _lowerCAmelCase = Pipe() _lowerCAmelCase = Pipe() process_array_.append( Process( target=lowerCAmelCase , args=(i, arr[i], temp_ls, temp_rs, temp_lr, temp_rr, result_pipe[i]) , ) ) _lowerCAmelCase = temp_rs _lowerCAmelCase = temp_rr process_array_.append( Process( target=lowerCAmelCase , args=( len(lowerCAmelCase ) - 1, arr[len(lowerCAmelCase ) - 1], temp_ls, None, temp_lr, None, result_pipe[len(lowerCAmelCase ) - 1], ) , ) ) # start the processes for p in process_array_: p.start() # wait for the processes to end and write their values to the list for p in range(0 , len(lowerCAmelCase ) ): _lowerCAmelCase = result_pipe[p][0].recv() process_array_[p].join() return arr def UpperCamelCase__ ( ): """simple docstring""" _lowerCAmelCase = list(range(10 , 0 , -1 ) ) print("""Initial List""" ) print(*lowerCAmelCase ) _lowerCAmelCase = odd_even_transposition(lowerCAmelCase ) print("""Sorted List\n""" ) print(*lowerCAmelCase ) if __name__ == "__main__": main()
70
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ :Optional[Any] = { '''configuration_electra''': ['''ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ElectraConfig''', '''ElectraOnnxConfig'''], '''tokenization_electra''': ['''ElectraTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ :Optional[int] = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ :Union[str, Any] = [ '''ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ElectraForCausalLM''', '''ElectraForMaskedLM''', '''ElectraForMultipleChoice''', '''ElectraForPreTraining''', '''ElectraForQuestionAnswering''', '''ElectraForSequenceClassification''', '''ElectraForTokenClassification''', '''ElectraModel''', '''ElectraPreTrainedModel''', '''load_tf_weights_in_electra''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ :Optional[int] = [ '''TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFElectraForMaskedLM''', '''TFElectraForMultipleChoice''', '''TFElectraForPreTraining''', '''TFElectraForQuestionAnswering''', '''TFElectraForSequenceClassification''', '''TFElectraForTokenClassification''', '''TFElectraModel''', '''TFElectraPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ :Dict = [ '''FlaxElectraForCausalLM''', '''FlaxElectraForMaskedLM''', '''FlaxElectraForMultipleChoice''', '''FlaxElectraForPreTraining''', '''FlaxElectraForQuestionAnswering''', '''FlaxElectraForSequenceClassification''', '''FlaxElectraForTokenClassification''', '''FlaxElectraModel''', '''FlaxElectraPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig from .tokenization_electra import ElectraTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_electra_fast import ElectraTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_electra import ( ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, ElectraForCausalLM, ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ElectraPreTrainedModel, load_tf_weights_in_electra, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_electra import ( TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST, TFElectraForMaskedLM, TFElectraForMultipleChoice, TFElectraForPreTraining, TFElectraForQuestionAnswering, TFElectraForSequenceClassification, TFElectraForTokenClassification, TFElectraModel, TFElectraPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_electra import ( FlaxElectraForCausalLM, FlaxElectraForMaskedLM, FlaxElectraForMultipleChoice, FlaxElectraForPreTraining, FlaxElectraForQuestionAnswering, FlaxElectraForSequenceClassification, FlaxElectraForTokenClassification, FlaxElectraModel, FlaxElectraPreTrainedModel, ) else: import sys A_ :Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
71
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
0
"""simple docstring""" import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class __snake_case ( unittest.TestCase): snake_case__ : Union[str, Any] = MODEL_FOR_CAUSAL_LM_MAPPING snake_case__ : List[str] = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Tuple = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' ) # Using `do_sample=False` to force deterministic output _lowerCamelCase : str = text_generator('''This is a test''' , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ] , ) _lowerCamelCase : Union[str, Any] = text_generator(['''This is a test''', '''This is a second test'''] ) self.assertEqual( __lowerCAmelCase , [ [ { '''generated_text''': ( '''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.''' ''' oscope. FiliFili@@''' ) } ], [ { '''generated_text''': ( '''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy''' ''' oscope. oscope. FiliFili@@''' ) } ], ] , ) _lowerCamelCase : Tuple = text_generator('''This is a test''' , do_sample=__lowerCAmelCase , num_return_sequences=2 , return_tensors=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ {'''generated_token_ids''': ANY(__lowerCAmelCase )}, {'''generated_token_ids''': ANY(__lowerCAmelCase )}, ] , ) _lowerCamelCase : str = text_generator.model.config.eos_token_id _lowerCamelCase : Tuple = '''<pad>''' _lowerCamelCase : str = text_generator( ['''This is a test''', '''This is a second test'''] , do_sample=__lowerCAmelCase , num_return_sequences=2 , batch_size=2 , return_tensors=__lowerCAmelCase , ) self.assertEqual( __lowerCAmelCase , [ [ {'''generated_token_ids''': ANY(__lowerCAmelCase )}, {'''generated_token_ids''': ANY(__lowerCAmelCase )}, ], [ {'''generated_token_ids''': ANY(__lowerCAmelCase )}, {'''generated_token_ids''': ANY(__lowerCAmelCase )}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : str = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' ) # Using `do_sample=False` to force deterministic output _lowerCamelCase : List[str] = text_generator('''This is a test''' , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ] , ) _lowerCamelCase : str = text_generator(['''This is a test''', '''This is a second test'''] , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [ { '''generated_text''': ( '''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵''' ''' please,''' ) } ], [ { '''generated_text''': ( '''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes''' ''' Cannes 閲閲Cannes Cannes Cannes 攵 please,''' ) } ], ] , ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = TextGenerationPipeline(model=__lowerCAmelCase , tokenizer=__lowerCAmelCase ) return text_generator, ["This is a test", "Another test"] def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Union[str, Any] = '''Hello I believe in''' _lowerCamelCase : int = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) _lowerCamelCase : Union[str, Any] = text_generator(__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , ) _lowerCamelCase : Dict = text_generator(__lowerCAmelCase , stop_sequence=''' fe''' ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': '''Hello I believe in fe'''}] ) def SCREAMING_SNAKE_CASE ( self : List[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Any ): """simple docstring""" _lowerCamelCase : Tuple = text_generator.model _lowerCamelCase : Optional[int] = text_generator.tokenizer _lowerCamelCase : int = text_generator('''This is a test''' ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) _lowerCamelCase : Optional[Any] = text_generator('''This is a test''' , return_full_text=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) _lowerCamelCase : Optional[int] = pipeline(task='''text-generation''' , model=__lowerCAmelCase , tokenizer=__lowerCAmelCase , return_full_text=__lowerCAmelCase ) _lowerCamelCase : str = text_generator('''This is a test''' ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] ) self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] ) _lowerCamelCase : Tuple = text_generator('''This is a test''' , return_full_text=__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] ) self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) ) _lowerCamelCase : Union[str, Any] = text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}], [{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}], ] , ) if text_generator.tokenizer.pad_token is not None: _lowerCamelCase : Any = text_generator( ['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=__lowerCAmelCase ) self.assertEqual( __lowerCAmelCase , [ [{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}], [{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}], ] , ) with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Dict = text_generator('''test''' , return_full_text=__lowerCAmelCase , return_text=__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : List[str] = text_generator('''test''' , return_full_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : str = text_generator('''test''' , return_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): _lowerCamelCase : Any = text_generator('''''' ) self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] ) else: with self.assertRaises((ValueError, AssertionError) ): _lowerCamelCase : str = text_generator('''''' ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. _lowerCamelCase : Union[str, Any] = ['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM'''] if ( tokenizer.model_max_length < 1_0_0_0_0 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator('''This is a test''' * 5_0_0 , max_new_tokens=2_0 ) _lowerCamelCase : str = text_generator('''This is a test''' * 5_0_0 , handle_long_generation='''hole''' , max_new_tokens=2_0 ) # Hole strategy cannot work with self.assertRaises(__lowerCAmelCase ): text_generator( '''This is a test''' * 5_0_0 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 1_0 , ) @require_torch @require_accelerate @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" import torch # Classic `model_kwargs` _lowerCamelCase : str = pipeline( model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) _lowerCamelCase : Dict = pipe('''This is a test''' ) self.assertEqual( __lowerCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) _lowerCamelCase : Union[str, Any] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) _lowerCamelCase : str = pipe('''This is a test''' ) self.assertEqual( __lowerCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 _lowerCamelCase : str = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) _lowerCamelCase : Dict = pipe('''This is a test''' ) self.assertEqual( __lowerCAmelCase , [ { '''generated_text''': ( '''This is a test test test test test test test test test test test test test test test test''' ''' test''' ) } ] , ) @require_torch @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" import torch _lowerCamelCase : int = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa ) pipe('''This is a test''' ) @require_torch @require_accelerate @require_torch_gpu def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" import torch _lowerCamelCase : Optional[Any] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa ) pipe('''This is a test''' , do_sample=__lowerCAmelCase , top_p=0.5 ) def SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" _lowerCamelCase : List[Any] = '''Hello world''' _lowerCamelCase : int = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' ) if text_generator.model.framework == "tf": _lowerCamelCase : int = logging.get_logger('''transformers.generation.tf_utils''' ) else: _lowerCamelCase : str = logging.get_logger('''transformers.generation.utils''' ) _lowerCamelCase : Tuple = '''Both `max_new_tokens`''' # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(__lowerCAmelCase ) as cl: _lowerCamelCase : int = text_generator(__lowerCAmelCase , max_length=1_0 , max_new_tokens=1 ) self.assertIn(__lowerCAmelCase , cl.out ) # The user only sets one -> no warning with CaptureLogger(__lowerCAmelCase ) as cl: _lowerCamelCase : Dict = text_generator(__lowerCAmelCase , max_new_tokens=1 ) self.assertNotIn(__lowerCAmelCase , cl.out ) with CaptureLogger(__lowerCAmelCase ) as cl: _lowerCamelCase : List[str] = text_generator(__lowerCAmelCase , max_length=1_0 ) self.assertNotIn(__lowerCAmelCase , cl.out )
72
'''simple docstring''' 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_barthez import BarthezTokenizer else: __UpperCAmelCase =None __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __UpperCAmelCase ={ "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } __UpperCAmelCase ={ "moussaKam/mbarthez": 1_0_2_4, "moussaKam/barthez": 1_0_2_4, "moussaKam/barthez-orangesum-title": 1_0_2_4, } __UpperCAmelCase ="▁" class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] =["input_ids", "attention_mask"] lowerCamelCase : Union[str, Any] =BarthezTokenizer def __init__( self : Optional[Any] , a : Dict=None , a : str=None , a : List[Any]="<s>" , a : Optional[int]="</s>" , a : List[str]="</s>" , a : Tuple="<s>" , a : str="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , **a : Union[str, Any] , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Optional[str] = None ): """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(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
67
0
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> bool: return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("""Program to check whether a number is a Perfect number or not...""") a =int(input("""Enter number: """).strip()) print(F"""{number} is {'' if perfect(number) else 'not '}a Perfect Number.""")
73
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00_00 ) -> int: __lowerCamelCase = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , UpperCamelCase__ , UpperCamelCase__ ) ) ) __lowerCamelCase = [float(UpperCamelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCamelCase__ , limit + 1 , UpperCamelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'{solution() = }')
67
0
"""simple docstring""" from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: torch.FloatTensor class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Dict ,A_ : Optional[Any]=3 ,A_ : int=3 ,A_ : Any=("DownEncoderBlock2D",) ,A_ : List[Any]=(64,) ,A_ : Optional[int]=2 ,A_ : List[Any]=32 ,A_ : Union[str, Any]="silu" ,A_ : Optional[Any]=True ,) -> Dict: super().__init__() A = layers_per_block A = torch.nn.Convad( A_ ,block_out_channels[0] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) # down A = block_out_channels[0] for i, down_block_type in enumerate(A_ ): A = output_channel A = block_out_channels[i] A = i == len(A_ ) - 1 A = get_down_block( A_ ,num_layers=self.layers_per_block ,in_channels=A_ ,out_channels=A_ ,add_downsample=not is_final_block ,resnet_eps=1e-6 ,downsample_padding=0 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,) self.down_blocks.append(A_ ) # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # out A = nn.GroupNorm(num_channels=block_out_channels[-1] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = 2 * out_channels if double_z else out_channels A = nn.Convad(block_out_channels[-1] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Tuple ) -> Any: A = x A = self.conv_in(A_ ) if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : Optional[Any] ): def custom_forward(*A_ : int ): return module(*A_ ) return custom_forward # down if is_torch_version('>=' ,'1.11.0' ): for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,use_reentrant=A_ ) # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,use_reentrant=A_ ) else: for down_block in self.down_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ) # middle A = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) ,A_ ) else: # down for down_block in self.down_blocks: A = down_block(A_ ) # middle A = self.mid_block(A_ ) # post-process A = self.conv_norm_out(A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] ,A_ : List[str]=3 ,A_ : Union[str, Any]=3 ,A_ : int=("UpDecoderBlock2D",) ,A_ : Optional[Any]=(64,) ,A_ : str=2 ,A_ : int=32 ,A_ : Optional[Any]="silu" ,A_ : Optional[Any]="group" ,) -> str: super().__init__() A = layers_per_block A = nn.Convad( A_ ,block_out_channels[-1] ,kernel_size=3 ,stride=1 ,padding=1 ,) A = None A = nn.ModuleList([] ) A = in_channels if norm_type == 'spatial' else None # mid A = UNetMidBlockaD( in_channels=block_out_channels[-1] ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,output_scale_factor=1 ,resnet_time_scale_shift='default' if norm_type == 'group' else norm_type ,attention_head_dim=block_out_channels[-1] ,resnet_groups=A_ ,temb_channels=A_ ,) # up A = list(reversed(A_ ) ) A = reversed_block_out_channels[0] for i, up_block_type in enumerate(A_ ): A = output_channel A = reversed_block_out_channels[i] A = i == len(A_ ) - 1 A = get_up_block( A_ ,num_layers=self.layers_per_block + 1 ,in_channels=A_ ,out_channels=A_ ,prev_output_channel=A_ ,add_upsample=not is_final_block ,resnet_eps=1e-6 ,resnet_act_fn=A_ ,resnet_groups=A_ ,attention_head_dim=A_ ,temb_channels=A_ ,resnet_time_scale_shift=A_ ,) self.up_blocks.append(A_ ) A = output_channel # out if norm_type == "spatial": A = SpatialNorm(block_out_channels[0] ,A_ ) else: A = nn.GroupNorm(num_channels=block_out_channels[0] ,num_groups=A_ ,eps=1e-6 ) A = nn.SiLU() A = nn.Convad(block_out_channels[0] ,A_ ,3 ,padding=1 ) A = False def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : int ,A_ : List[str]=None ) -> List[str]: A = z A = self.conv_in(A_ ) A = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(A_ : str ): def custom_forward(*A_ : List[str] ): return module(*A_ ) return custom_forward if is_torch_version('>=' ,'1.11.0' ): # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ,use_reentrant=A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint( create_custom_forward(A_ ) ,A_ ,A_ ,use_reentrant=A_ ) else: # middle A = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) ,A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = torch.utils.checkpoint.checkpoint(create_custom_forward(A_ ) ,A_ ,A_ ) else: # middle A = self.mid_block(A_ ,A_ ) A = sample.to(A_ ) # up for up_block in self.up_blocks: A = up_block(A_ ,A_ ) # post-process if latent_embeds is None: A = self.conv_norm_out(A_ ) else: A = self.conv_norm_out(A_ ,A_ ) A = self.conv_act(A_ ) A = self.conv_out(A_ ) return sample class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ,A_ : Tuple ,A_ : Optional[Any] ,A_ : Optional[Any] ,A_ : Union[str, Any]=None ,A_ : Union[str, Any]="random" ,A_ : Optional[Any]=False ,A_ : Any=True ) -> List[str]: super().__init__() A = n_e A = vq_embed_dim A = beta A = legacy A = nn.Embedding(self.n_e ,self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e ,1.0 / self.n_e ) A = remap if self.remap is not None: self.register_buffer('used' ,torch.tensor(np.load(self.remap ) ) ) A = self.used.shape[0] A = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": A = self.re_embed A = self.re_embed + 1 print( F'Remapping {self.n_e} indices to {self.re_embed} indices. ' F'Using {self.unknown_index} for unknown indices.' ) else: A = n_e A = sane_index_shape def _SCREAMING_SNAKE_CASE ( self : int ,A_ : Tuple ) -> str: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) A = (inds[:, :, None] == used[None, None, ...]).long() A = match.argmax(-1 ) A = match.sum(2 ) < 1 if self.unknown_index == "random": A = torch.randint(0 ,self.re_embed ,size=new[unknown].shape ).to(device=new.device ) else: A = self.unknown_index return new.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[str]: A = inds.shape assert len(A_ ) > 1 A = inds.reshape(ishape[0] ,-1 ) A = self.used.to(A_ ) if self.re_embed > self.used.shape[0]: # extra token A = 0 # simply set to zero A = torch.gather(used[None, :][inds.shape[0] * [0], :] ,1 ,A_ ) return back.reshape(A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : Any ) -> Union[str, Any]: # reshape z -> (batch, height, width, channel) and flatten A = z.permute(0 ,2 ,3 ,1 ).contiguous() A = z.view(-1 ,self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z A = torch.argmin(torch.cdist(A_ ,self.embedding.weight ) ,dim=1 ) A = self.embedding(A_ ).view(z.shape ) A = None A = None # compute loss for embedding if not self.legacy: A = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: A = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients A = z + (z_q - z).detach() # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() if self.remap is not None: A = min_encoding_indices.reshape(z.shape[0] ,-1 ) # add batch axis A = self.remap_to_used(A_ ) A = min_encoding_indices.reshape(-1 ,1 ) # flatten if self.sane_index_shape: A = min_encoding_indices.reshape(z_q.shape[0] ,z_q.shape[2] ,z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ,A_ : int ,A_ : List[str] ) -> int: # shape specifying (batch, height, width, channel) if self.remap is not None: A = indices.reshape(shape[0] ,-1 ) # add batch axis A = self.unmap_to_all(A_ ) A = indices.reshape(-1 ) # flatten again # get quantized latent vectors A = self.embedding(A_ ) if shape is not None: A = z_q.view(A_ ) # reshape back to match original input shape A = z_q.permute(0 ,3 ,1 ,2 ).contiguous() return z_q class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' def __init__( self : str ,A_ : Optional[int] ,A_ : Union[str, Any]=False ) -> Optional[int]: A = parameters A , A = torch.chunk(A_ ,2 ,dim=1 ) A = torch.clamp(self.logvar ,-30.0 ,20.0 ) A = deterministic A = torch.exp(0.5 * self.logvar ) A = torch.exp(self.logvar ) if self.deterministic: A = A = torch.zeros_like( self.mean ,device=self.parameters.device ,dtype=self.parameters.dtype ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Optional[torch.Generator] = None ) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype A = randn_tensor( self.mean.shape ,generator=A_ ,device=self.parameters.device ,dtype=self.parameters.dtype ) A = self.mean + self.std * sample return x def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List[Any]=None ) -> Optional[Any]: if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean ,2 ) + self.var - 1.0 - self.logvar ,dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean ,2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar ,dim=[1, 2, 3] ,) def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : List[str] ,A_ : Dict=[1, 2, 3] ) -> int: if self.deterministic: return torch.Tensor([0.0] ) A = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean ,2 ) / self.var ,dim=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Any: return self.mean
74
'''simple docstring''' 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 a__ : def __init__( self : Union[str, Any] , a : Union[str, Any] , a : Tuple=13 , a : Optional[Any]=7 , a : List[Any]=True , a : Optional[Any]=True , a : Any=True , a : Union[str, Any]=99 , a : Any=32 , a : int=5 , a : Optional[int]=4 , a : Union[str, Any]=37 , a : Optional[Any]="gelu" , a : Union[str, Any]=0.1 , a : Any=0.1 , a : Optional[int]=5_12 , a : int=16 , a : Optional[Any]=2 , a : Union[str, Any]=0.02 , a : Any=3 , a : Dict=4 , a : Any=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = self.vocab_size - 1 def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __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 = 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 , ) __lowerCamelCase = 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 : Union[str, Any] , a : Dict , a : List[str] , a : Tuple , a : List[Any] , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , head_mask=a ) __lowerCamelCase = model(a , token_type_ids=a ) __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Union[str, Any] , a : Dict , a : Union[str, Any] , a : Tuple , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Optional[Any] , *a : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTDoubleHeadsModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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 : List[str] , a : int , a : Dict , a : Optional[Any] , a : str , *a : int ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = OpenAIGPTForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """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, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : List[str] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCamelCase : str =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCamelCase : Optional[int] =( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple , a : Optional[int] , a : int , a : str , a : Any ): """simple docstring""" 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 : Optional[int] , a : int , a : Optional[int] , a : str=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a , ) __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a , ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , n_embd=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = OpenAIGPTModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(a ) __lowerCamelCase = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=a ) # the president is __lowerCamelCase = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the __lowerCamelCase = model.generate(a , do_sample=a ) self.assertListEqual(output_ids[0].tolist() , a )
67
0
'''simple docstring''' import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a_ : List[str] = get_tests_dir("""fixtures/test_sentencepiece_no_bos.model""") @require_sentencepiece @require_tokenizers class __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): lowercase : Dict =PegasusTokenizer lowercase : List[str] =PegasusTokenizerFast lowercase : Any =True lowercase : Tuple =True def lowercase__ ( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ =PegasusTokenizer(lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase__ ( self ): """simple docstring""" return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def lowercase__ ( self, **lowerCAmelCase ): """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return ("This is a test", "This is a test") def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ='''</s>''' lowerCamelCase_ =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ), lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ), lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0], '''<pad>''' ) self.assertEqual(vocab_keys[1], '''</s>''' ) self.assertEqual(vocab_keys[-1], '''v''' ) self.assertEqual(len(lowerCAmelCase ), 1_103 ) def lowercase__ ( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size, 1_103 ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowerCamelCase_ =self.tokenizer_class.from_pretrained(self.tmpdirname ) lowerCamelCase_ =( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) lowerCamelCase_ =rust_tokenizer([raw_input_str], return_tensors=lowerCAmelCase, add_special_tokens=lowerCAmelCase ).input_ids[0] lowerCamelCase_ =py_tokenizer([raw_input_str], return_tensors=lowerCAmelCase, add_special_tokens=lowerCAmelCase ).input_ids[0] self.assertListEqual(lowerCAmelCase, lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word lowerCamelCase_ ='''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' lowerCamelCase_ =[2, 413, 615, 114, 3, 1_971, 113, 1_679, 10_710, 107, 1] lowerCamelCase_ =tokenizer([raw_input_str], return_tensors=lowerCAmelCase ).input_ids[0] self.assertListEqual(lowerCAmelCase, lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 96_103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_024 lowerCamelCase_ ='''To ensure a smooth flow of bank resolutions.''' lowerCamelCase_ =[413, 615, 114, 2_291, 1_971, 113, 1_679, 10_710, 107, 1] lowerCamelCase_ =tokenizer([raw_input_str], return_tensors=lowerCAmelCase ).input_ids[0] self.assertListEqual(lowerCAmelCase, lowerCAmelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =['''This is going to be way too long.''' * 150, '''short example'''] lowerCamelCase_ =['''not super long but more than 5 tokens''', '''tiny'''] lowerCamelCase_ =self._large_tokenizer(lowerCAmelCase, padding=lowerCAmelCase, truncation=lowerCAmelCase, return_tensors='''pt''' ) lowerCamelCase_ =self._large_tokenizer( text_target=lowerCAmelCase, max_length=5, padding=lowerCAmelCase, truncation=lowerCAmelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1_024) assert batch.attention_mask.shape == (2, 1_024) assert targets["input_ids"].shape == (2, 5) assert len(lowerCAmelCase ) == 2 # input_ids, attention_mask. @slow def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ={'''input_ids''': [[38_979, 143, 18_485, 606, 130, 26_669, 87_686, 121, 54_189, 1_129, 111, 26_669, 87_686, 121, 9_114, 14_787, 121, 13_249, 158, 592, 956, 121, 14_621, 31_576, 143, 62_613, 108, 9_688, 930, 43_430, 11_562, 62_613, 304, 108, 11_443, 897, 108, 9_314, 17_415, 63_399, 108, 11_443, 7_614, 18_316, 118, 4_284, 7_148, 12_430, 143, 1_400, 25_703, 158, 111, 4_284, 7_148, 11_772, 143, 21_297, 1_064, 158, 122, 204, 3_506, 1_754, 1_133, 14_787, 1_581, 115, 33_224, 4_482, 111, 1_355, 110, 29_173, 317, 50_833, 108, 20_147, 94_665, 111, 77_198, 107, 1], [110, 62_613, 117, 638, 112, 1_133, 121, 20_098, 1_355, 79_050, 13_872, 135, 1_596, 53_541, 1_352, 141, 13_039, 5_542, 124, 302, 518, 111, 268, 2_956, 115, 149, 4_427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1_235, 2_799, 18_289, 17_780, 204, 109, 9_474, 1_296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase, model_name='''google/bigbird-pegasus-large-arxiv''', revision='''ba85d0851d708441f91440d509690f1ab6353415''', ) @require_sentencepiece @require_tokenizers class __UpperCamelCase ( lowerCamelCase__ , unittest.TestCase ): lowercase : List[Any] =PegasusTokenizer lowercase : List[str] =PegasusTokenizerFast lowercase : List[Any] =True lowercase : Union[str, Any] =True def lowercase__ ( self ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase_ =PegasusTokenizer(lowerCAmelCase, offset=0, mask_token_sent=lowerCAmelCase, mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def lowercase__ ( self ): """simple docstring""" return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def lowercase__ ( self, **lowerCAmelCase ): """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname, **lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return ("This is a test", "This is a test") def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) lowerCamelCase_ =self.tokenizer_class.from_pretrained(self.tmpdirname ) lowerCamelCase_ =( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) lowerCamelCase_ =rust_tokenizer([raw_input_str], return_tensors=lowerCAmelCase, add_special_tokens=lowerCAmelCase ).input_ids[0] lowerCamelCase_ =py_tokenizer([raw_input_str], return_tensors=lowerCAmelCase, add_special_tokens=lowerCAmelCase ).input_ids[0] self.assertListEqual(lowerCAmelCase, lowerCAmelCase ) @require_torch def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =['''This is going to be way too long.''' * 1_000, '''short example'''] lowerCamelCase_ =['''not super long but more than 5 tokens''', '''tiny'''] lowerCamelCase_ =self._large_tokenizer(lowerCAmelCase, padding=lowerCAmelCase, truncation=lowerCAmelCase, return_tensors='''pt''' ) lowerCamelCase_ =self._large_tokenizer( text_target=lowerCAmelCase, max_length=5, padding=lowerCAmelCase, truncation=lowerCAmelCase, return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4_096) assert batch.attention_mask.shape == (2, 4_096) assert targets["input_ids"].shape == (2, 5) assert len(lowerCAmelCase ) == 2 # input_ids, attention_mask. def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) lowerCamelCase_ =self._large_tokenizer(lowerCAmelCase ).input_ids self.assertListEqual( lowerCAmelCase, [182, 117, 142, 587, 4_211, 120, 117, 263, 112, 804, 109, 856, 25_016, 3_137, 464, 109, 26_955, 3_137, 1], )
75
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =["image_processor", "tokenizer"] lowerCamelCase : Union[str, Any] ="LayoutLMv2ImageProcessor" lowerCamelCase : int =("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , a : Any=None , a : Any=None , **a : Union[str, Any] ): """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a , a ) def __call__( self : Tuple , a : Optional[int] , a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a : Union[List[List[int]], List[List[List[int]]]] = None , a : Optional[Union[List[int], List[List[int]]]] = None , a : bool = True , a : Union[bool, str, PaddingStrategy] = False , a : Union[bool, str, TruncationStrategy] = None , a : Optional[int] = None , a : int = 0 , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[bool] = None , a : bool = False , a : bool = False , a : bool = False , a : bool = False , a : bool = True , a : Optional[Union[str, TensorType]] = None , **a : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=a , return_tensors=a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a , a ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features['''words'''] __lowerCamelCase = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel values __lowerCamelCase = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(a , encoded_inputs['''overflow_to_sample_mapping'''] ) __lowerCamelCase = images return encoded_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Optional[Any] , a : str ): """simple docstring""" __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a ) != len(a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(a )} and {len(a )}""" ) return images_with_overflow def SCREAMING_SNAKE_CASE__ ( self : List[str] , *a : Optional[Any] , **a : Union[str, Any] ): """simple docstring""" return self.tokenizer.batch_decode(*a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *a : Union[str, Any] , **a : Tuple ): """simple docstring""" return self.tokenizer.decode(*a , **a ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a , ) return self.image_processor
67
0
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: SCREAMING_SNAKE_CASE : Dict = 128 elif "12-12" in model_name: SCREAMING_SNAKE_CASE : List[str] = 12 SCREAMING_SNAKE_CASE : Optional[int] = 12 elif "14-14" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 14 SCREAMING_SNAKE_CASE : Tuple = 14 elif "16-16" in model_name: SCREAMING_SNAKE_CASE : Optional[Any] = 16 SCREAMING_SNAKE_CASE : str = 16 else: raise ValueError("Model not supported") SCREAMING_SNAKE_CASE : Optional[Any] = "huggingface/label-files" if "speech-commands" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = 35 SCREAMING_SNAKE_CASE : Tuple = "speech-commands-v2-id2label.json" else: SCREAMING_SNAKE_CASE : Union[str, Any] = 527 SCREAMING_SNAKE_CASE : str = "audioset-id2label.json" SCREAMING_SNAKE_CASE : List[str] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : Union[str, Any] = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : Tuple = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( _a): if "module.v" in name: SCREAMING_SNAKE_CASE : int = name.replace("module.v" , "audio_spectrogram_transformer") if "cls_token" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("cls_token" , "embeddings.cls_token") if "dist_token" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("dist_token" , "embeddings.distillation_token") if "pos_embed" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("pos_embed" , "embeddings.position_embeddings") if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE : str = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection") # transformer blocks if "blocks" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("blocks" , "encoder.layer") if "attn.proj" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("attn.proj" , "attention.output.dense") if "attn" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("attn" , "attention.self") if "norm1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("norm1" , "layernorm_before") if "norm2" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("norm2" , "layernorm_after") if "mlp.fc1" in name: SCREAMING_SNAKE_CASE : List[str] = name.replace("mlp.fc1" , "intermediate.dense") if "mlp.fc2" in name: SCREAMING_SNAKE_CASE : Tuple = name.replace("mlp.fc2" , "output.dense") # final layernorm if "audio_spectrogram_transformer.norm" in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("audio_spectrogram_transformer.norm" , "audio_spectrogram_transformer.layernorm") # classifier head if "module.mlp_head.0" in name: SCREAMING_SNAKE_CASE : str = name.replace("module.mlp_head.0" , "classifier.layernorm") if "module.mlp_head.1" in name: SCREAMING_SNAKE_CASE : Dict = name.replace("module.mlp_head.1" , "classifier.dense") return name def lowerCamelCase__ ( _a , _a): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : List[Any] = orig_state_dict.pop(_a) if "qkv" in key: SCREAMING_SNAKE_CASE : str = key.split(".") SCREAMING_SNAKE_CASE : List[str] = int(key_split[3]) SCREAMING_SNAKE_CASE : Union[str, Any] = config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE : str = val[:dim, :] SCREAMING_SNAKE_CASE : str = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : List[str] = val[-dim:, :] else: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim] SCREAMING_SNAKE_CASE : Any = val[dim : dim * 2] SCREAMING_SNAKE_CASE : List[str] = val[-dim:] else: SCREAMING_SNAKE_CASE : Dict = val return orig_state_dict def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[Any] = [ "module.v.head.weight", "module.v.head.bias", "module.v.head_dist.weight", "module.v.head_dist.bias", ] for k in ignore_keys: state_dict.pop(_a , _a) @torch.no_grad() def lowerCamelCase__ ( _a , _a , _a=False): SCREAMING_SNAKE_CASE : int = get_audio_spectrogram_transformer_config(_a) SCREAMING_SNAKE_CASE : Optional[Any] = { "ast-finetuned-audioset-10-10-0.4593": ( "https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.450": ( "https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448": ( "https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1" ), "ast-finetuned-audioset-10-10-0.448-v2": ( "https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1" ), "ast-finetuned-audioset-12-12-0.447": ( "https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1" ), "ast-finetuned-audioset-14-14-0.443": ( "https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1" ), "ast-finetuned-audioset-16-16-0.442": ( "https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1" ), "ast-finetuned-speech-commands-v2": ( "https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1" ), } # load original state_dict SCREAMING_SNAKE_CASE : List[str] = model_name_to_url[model_name] SCREAMING_SNAKE_CASE : List[Any] = torch.hub.load_state_dict_from_url(_a , map_location="cpu") # remove some keys remove_keys(_a) # rename some keys SCREAMING_SNAKE_CASE : List[str] = convert_state_dict(_a , _a) # load 🤗 model SCREAMING_SNAKE_CASE : Dict = ASTForAudioClassification(_a) model.eval() model.load_state_dict(_a) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 SCREAMING_SNAKE_CASE : List[str] = -4.267_7393 if "speech-commands" not in model_name else -6.84_5978 SCREAMING_SNAKE_CASE : Tuple = 4.568_9974 if "speech-commands" not in model_name else 5.565_4526 SCREAMING_SNAKE_CASE : List[Any] = 1024 if "speech-commands" not in model_name else 128 SCREAMING_SNAKE_CASE : Optional[int] = ASTFeatureExtractor(mean=_a , std=_a , max_length=_a) if "speech-commands" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset("speech_commands" , "v0.02" , split="validation") SCREAMING_SNAKE_CASE : Any = dataset[0]["audio"]["array"] else: SCREAMING_SNAKE_CASE : Dict = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" , ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = torchaudio.load(_a) SCREAMING_SNAKE_CASE : Any = waveform.squeeze().numpy() SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor(_a , sampling_rate=16000 , return_tensors="pt") # forward pass SCREAMING_SNAKE_CASE : Optional[Any] = model(**_a) SCREAMING_SNAKE_CASE : int = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": SCREAMING_SNAKE_CASE : Any = torch.tensor([-0.8760, -7.0042, -8.6602]) elif model_name == "ast-finetuned-audioset-10-10-0.450": SCREAMING_SNAKE_CASE : Any = torch.tensor([-1.1986, -7.0903, -8.2718]) elif model_name == "ast-finetuned-audioset-10-10-0.448": SCREAMING_SNAKE_CASE : str = torch.tensor([-2.6128, -8.0080, -9.4344]) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": SCREAMING_SNAKE_CASE : str = torch.tensor([-1.5080, -7.4534, -8.8917]) elif model_name == "ast-finetuned-audioset-12-12-0.447": SCREAMING_SNAKE_CASE : str = torch.tensor([-0.5050, -6.5833, -8.0843]) elif model_name == "ast-finetuned-audioset-14-14-0.443": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.3826, -7.0336, -8.2413]) elif model_name == "ast-finetuned-audioset-16-16-0.442": SCREAMING_SNAKE_CASE : Any = torch.tensor([-1.2113, -6.9101, -8.3470]) elif model_name == "ast-finetuned-speech-commands-v2": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([6.1589, -8.0566, -8.7984]) else: raise ValueError("Unknown model name") if not torch.allclose(logits[0, :3] , _a , atol=1E-4): raise ValueError("Logits don't match") print("Looks ok!") if pytorch_dump_folder_path is not None: Path(_a).mkdir(exist_ok=_a) print(f"Saving model {model_name} to {pytorch_dump_folder_path}") model.save_pretrained(_a) print(f"Saving feature extractor to {pytorch_dump_folder_path}") feature_extractor.save_pretrained(_a) if push_to_hub: print("Pushing model and feature extractor to the hub...") model.push_to_hub(f"MIT/{model_name}") feature_extractor.push_to_hub(f"MIT/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) a_ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): """simple docstring""" super().__init__() __lowerCamelCase = nn.ModuleList(a ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : torch.FloatTensor , a : Union[torch.Tensor, float, int] , a : torch.Tensor , a : List[torch.tensor] , a : List[float] , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[Dict[str, Any]] = None , a : bool = False , a : bool = True , ): """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets ) ): __lowerCamelCase , __lowerCamelCase = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: __lowerCamelCase , __lowerCamelCase = down_samples, mid_sample else: __lowerCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self : Any , a : Union[str, os.PathLike] , a : bool = True , a : Callable = None , a : bool = False , a : Optional[str] = None , ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 __lowerCamelCase = model_path_to_save + f"""_{idx}""" @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[str] , a : Optional[Union[str, os.PathLike]] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __lowerCamelCase = pretrained_model_path while os.path.isdir(a ): __lowerCamelCase = ControlNetModel.from_pretrained(a , **a ) controlnets.append(a ) idx += 1 __lowerCamelCase = pretrained_model_path + f"""_{idx}""" logger.info(f"""{len(a )} controlnets loaded from {pretrained_model_path}.""" ) if len(a ) == 0: raise ValueError( f"""No ControlNets found under {os.path.dirname(a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(a )
67
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor class UpperCAmelCase_ ( unittest.TestCase): def __init__( self , a , a=7 , a=3 , a=1_8 , a=3_0 , a=4_0_0 , a=True , a=None , a=True , a=None , a=True , a=[0.48_145_466, 0.4_578_275, 0.40_821_073] , a=[0.26_862_954, 0.26_130_258, 0.27_577_711] , a=True , ) -> Dict: lowercase__ : Tuple = size if size is not None else {'height': 2_2_4, 'width': 2_2_4} lowercase__ : List[str] = crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8} lowercase__ : int = parent lowercase__ : Tuple = batch_size lowercase__ : Optional[int] = num_channels lowercase__ : Union[str, Any] = image_size lowercase__ : Any = min_resolution lowercase__ : Optional[Any] = max_resolution lowercase__ : int = do_resize lowercase__ : Union[str, Any] = size lowercase__ : Union[str, Any] = do_center_crop lowercase__ : Any = crop_size lowercase__ : Any = do_normalize lowercase__ : List[str] = image_mean lowercase__ : List[str] = image_std lowercase__ : Tuple = do_convert_rgb def _UpperCAmelCase ( self ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def _UpperCAmelCase ( self , a=False , a=False , a=False ) -> int: assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" if equal_resolution: lowercase__ : Union[str, Any] = [] for i in range(self.batch_size ): image_inputs.append( np.random.randint( 2_5_5 , size=(self.num_channels, self.max_resolution, self.max_resolution) , dtype=np.uinta ) ) else: lowercase__ : Any = [] for i in range(self.batch_size ): lowercase__ , lowercase__ : Dict = np.random.choice(np.arange(self.min_resolution , self.max_resolution ) , 2 ) image_inputs.append(np.random.randint(2_5_5 , size=(self.num_channels, width, height) , dtype=np.uinta ) ) if not numpify and not torchify: # PIL expects the channel dimension as last dimension lowercase__ : str = [Image.fromarray(np.moveaxis(a , 0 , -1 ) ) for x in image_inputs] if torchify: lowercase__ : Union[str, Any] = [torch.from_numpy(a ) for x in image_inputs] return image_inputs @require_torch @require_vision class UpperCAmelCase_ ( _a , unittest.TestCase): lowerCamelCase__ : Dict = ChineseCLIPImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : Optional[int] = ChineseCLIPImageProcessingTester(self , do_center_crop=a ) @property def _UpperCAmelCase ( self ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self ) -> str: lowercase__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'do_resize' ) ) self.assertTrue(hasattr(a , 'size' ) ) self.assertTrue(hasattr(a , 'do_center_crop' ) ) self.assertTrue(hasattr(a , 'center_crop' ) ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'image_mean' ) ) self.assertTrue(hasattr(a , 'image_std' ) ) self.assertTrue(hasattr(a , 'do_convert_rgb' ) ) def _UpperCAmelCase ( self ) -> Union[str, Any]: lowercase__ : str = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 2_2_4, 'width': 2_2_4} ) self.assertEqual(image_processor.crop_size , {'height': 1_8, 'width': 1_8} ) lowercase__ : Any = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4 ) self.assertEqual(image_processor.size , {'shortest_edge': 4_2} ) self.assertEqual(image_processor.crop_size , {'height': 8_4, 'width': 8_4} ) def _UpperCAmelCase ( self ) -> Optional[int]: pass def _UpperCAmelCase ( self ) -> List[Any]: # Initialize image_processing lowercase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ : str = self.image_processor_tester.prepare_inputs(equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input lowercase__ : Dict = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowercase__ : int = 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, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _UpperCAmelCase ( self ) -> Any: # Initialize image_processing lowercase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__ : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input lowercase__ : Union[str, 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowercase__ : List[Any] = 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, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def _UpperCAmelCase ( self ) -> Optional[Any]: # Initialize image_processing lowercase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__ : Optional[Any] = self.image_processor_tester.prepare_inputs(equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input lowercase__ : Dict = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowercase__ : int = 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, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) @require_torch @require_vision class UpperCAmelCase_ ( _a , unittest.TestCase): lowerCamelCase__ : Dict = ChineseCLIPImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self ) -> str: lowercase__ : Optional[int] = ChineseCLIPImageProcessingTester(self , num_channels=4 , do_center_crop=a ) lowercase__ : Dict = 3 @property def _UpperCAmelCase ( self ) -> List[str]: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , 'do_resize' ) ) self.assertTrue(hasattr(a , 'size' ) ) self.assertTrue(hasattr(a , 'do_center_crop' ) ) self.assertTrue(hasattr(a , 'center_crop' ) ) self.assertTrue(hasattr(a , 'do_normalize' ) ) self.assertTrue(hasattr(a , 'image_mean' ) ) self.assertTrue(hasattr(a , 'image_std' ) ) self.assertTrue(hasattr(a , 'do_convert_rgb' ) ) def _UpperCAmelCase ( self ) -> str: pass def _UpperCAmelCase ( self ) -> Dict: # Initialize image_processing lowercase__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ : int = self.image_processor_tester.prepare_inputs(equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input lowercase__ : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched lowercase__ : Dict = image_processing(a , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.expected_encoded_image_num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
77
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
0
"""simple docstring""" from typing import Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING snake_case_ = logging.get_logger(__name__) @add_end_docstrings(SCREAMING_SNAKE_CASE_ ) class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Any , *lowercase_ :str , **lowercase_ :List[Any] ) -> Union[str, Any]: super().__init__(*lowercase_ , **lowercase_ ) self.check_model_type(lowercase_ ) def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Any=None , lowercase_ :Optional[int]=None , lowercase_ :Tuple=None , **lowercase_ :Tuple ) -> Dict: UpperCAmelCase , UpperCAmelCase = {}, {} if padding is not None: UpperCAmelCase = padding if truncation is not None: UpperCAmelCase = truncation if top_k is not None: UpperCAmelCase = top_k return preprocess_params, {}, postprocess_params def __call__( self :List[Any] , lowercase_ :Union["Image.Image", str] , lowercase_ :str = None , **lowercase_ :Union[str, Any] ) -> Union[str, Any]: if isinstance(lowercase_ , (Image.Image, str) ) and isinstance(lowercase_ , lowercase_ ): UpperCAmelCase = {'image': image, 'question': question} else: UpperCAmelCase = image UpperCAmelCase = super().__call__(lowercase_ , **lowercase_ ) return results def UpperCAmelCase__ ( self :List[str] , lowercase_ :List[Any] , lowercase_ :int=False , lowercase_ :Optional[int]=False ) -> Union[str, Any]: UpperCAmelCase = load_image(inputs['image'] ) UpperCAmelCase = self.tokenizer( inputs['question'] , return_tensors=self.framework , padding=lowercase_ , truncation=lowercase_ ) UpperCAmelCase = self.image_processor(images=lowercase_ , return_tensors=self.framework ) model_inputs.update(lowercase_ ) return model_inputs def UpperCAmelCase__ ( self :List[Any] , lowercase_ :List[str] ) -> Any: UpperCAmelCase = self.model(**lowercase_ ) return model_outputs def UpperCAmelCase__ ( self :Dict , lowercase_ :Tuple , lowercase_ :List[Any]=5 ) -> Union[str, Any]: if top_k > self.model.config.num_labels: UpperCAmelCase = self.model.config.num_labels if self.framework == "pt": UpperCAmelCase = model_outputs.logits.sigmoid()[0] UpperCAmelCase , UpperCAmelCase = probs.topk(lowercase_ ) else: raise ValueError(f"""Unsupported framework: {self.framework}""" ) UpperCAmelCase = scores.tolist() UpperCAmelCase = ids.tolist() return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowercase_ , lowercase_ )]
78
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
'''simple docstring''' import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated lowerCamelCase_ = collections.namedtuple('''_Datasets''', ['''train''', '''validation''', '''test''']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ lowerCamelCase_ = '''https://storage.googleapis.com/cvdf-datasets/mnist/''' def __lowercase ( __lowercase ) -> Optional[Any]: '''simple docstring''' _A = numpy.dtype(numpy.uintaa ).newbyteorder(">" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=__lowercase )[0] @deprecated(__lowercase , "Please use tf.data to implement this functionality." ) def __lowercase ( __lowercase ) -> List[Any]: '''simple docstring''' print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__lowercase ) as bytestream: _A = _readaa(__lowercase ) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) _A = _readaa(__lowercase ) _A = _readaa(__lowercase ) _A = _readaa(__lowercase ) _A = bytestream.read(rows * cols * num_images ) _A = numpy.frombuffer(__lowercase , dtype=numpy.uinta ) _A = data.reshape(__lowercase , __lowercase , __lowercase , 1 ) return data @deprecated(__lowercase , "Please use tf.one_hot on tensors." ) def __lowercase ( __lowercase , __lowercase ) -> int: '''simple docstring''' _A = labels_dense.shape[0] _A = numpy.arange(__lowercase ) * num_classes _A = numpy.zeros((num_labels, num_classes) ) _A = 1 return labels_one_hot @deprecated(__lowercase , "Please use tf.data to implement this functionality." ) def __lowercase ( __lowercase , __lowercase=False , __lowercase=10 ) -> List[Any]: '''simple docstring''' print("Extracting" , f.name ) with gzip.GzipFile(fileobj=__lowercase ) as bytestream: _A = _readaa(__lowercase ) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) _A = _readaa(__lowercase ) _A = bytestream.read(__lowercase ) _A = numpy.frombuffer(__lowercase , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(__lowercase , __lowercase ) return labels class _UpperCAmelCase : """simple docstring""" @deprecated( __UpperCAmelCase , "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models." , ) def __init__( self : str , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Optional[Any]=dtypes.floataa , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Optional[int]=None , ): '''simple docstring''' _A , _A = random_seed.get_seed(__UpperCAmelCase ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) _A = dtypes.as_dtype(__UpperCAmelCase ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype ) if fake_data: _A = 10000 _A = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' _A = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 _A = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. _A = images.astype(numpy.floataa ) _A = numpy.multiply(__UpperCAmelCase , 1.0 / 255.0 ) _A = images _A = labels _A = 0 _A = 0 @property def lowerCAmelCase ( self : int ): '''simple docstring''' return self._images @property def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self._labels @property def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' return self._num_examples @property def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' return self._epochs_completed def lowerCAmelCase ( self : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any=False , __UpperCAmelCase : int=True ): '''simple docstring''' if fake_data: _A = [1] * 784 _A = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(__UpperCAmelCase )], [fake_label for _ in range(__UpperCAmelCase )], ) _A = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: _A = numpy.arange(self._num_examples ) numpy.random.shuffle(__UpperCAmelCase ) _A = self.images[perma] _A = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch _A = self._num_examples - start _A = self._images[start : self._num_examples] _A = self._labels[start : self._num_examples] # Shuffle the data if shuffle: _A = numpy.arange(self._num_examples ) numpy.random.shuffle(__UpperCAmelCase ) _A = self.images[perm] _A = self.labels[perm] # Start next epoch _A = 0 _A = batch_size - rest_num_examples _A = self._index_in_epoch _A = self._images[start:end] _A = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size _A = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(__lowercase , "Please write your own downloading logic." ) def __lowercase ( __lowercase , __lowercase , __lowercase ) -> Union[str, Any]: '''simple docstring''' if not gfile.Exists(__lowercase ): gfile.MakeDirs(__lowercase ) _A = os.path.join(__lowercase , __lowercase ) if not gfile.Exists(__lowercase ): urllib.request.urlretrieve(__lowercase , __lowercase ) # noqa: S310 with gfile.GFile(__lowercase ) as f: _A = f.size() print("Successfully downloaded" , __lowercase , __lowercase , "bytes." ) return filepath @deprecated( __lowercase , "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def __lowercase ( __lowercase , __lowercase=False , __lowercase=False , __lowercase=dtypes.floataa , __lowercase=True , __lowercase=5000 , __lowercase=None , __lowercase=DEFAULT_SOURCE_URL , ) -> List[str]: '''simple docstring''' if fake_data: def fake(): return _DataSet( [] , [] , fake_data=__lowercase , one_hot=__lowercase , dtype=__lowercase , seed=__lowercase ) _A = fake() _A = fake() _A = fake() return _Datasets(train=__lowercase , validation=__lowercase , test=__lowercase ) if not source_url: # empty string check _A = DEFAULT_SOURCE_URL _A = "train-images-idx3-ubyte.gz" _A = "train-labels-idx1-ubyte.gz" _A = "t10k-images-idx3-ubyte.gz" _A = "t10k-labels-idx1-ubyte.gz" _A = _maybe_download( __lowercase , __lowercase , source_url + train_images_file ) with gfile.Open(__lowercase , "rb" ) as f: _A = _extract_images(__lowercase ) _A = _maybe_download( __lowercase , __lowercase , source_url + train_labels_file ) with gfile.Open(__lowercase , "rb" ) as f: _A = _extract_labels(__lowercase , one_hot=__lowercase ) _A = _maybe_download( __lowercase , __lowercase , source_url + test_images_file ) with gfile.Open(__lowercase , "rb" ) as f: _A = _extract_images(__lowercase ) _A = _maybe_download( __lowercase , __lowercase , source_url + test_labels_file ) with gfile.Open(__lowercase , "rb" ) as f: _A = _extract_labels(__lowercase , one_hot=__lowercase ) if not 0 <= validation_size <= len(__lowercase ): _A = ( "Validation size should be between 0 and " F'''{len(__lowercase )}. Received: {validation_size}.''' ) raise ValueError(__lowercase ) _A = train_images[:validation_size] _A = train_labels[:validation_size] _A = train_images[validation_size:] _A = train_labels[validation_size:] _A = {"dtype": dtype, "reshape": reshape, "seed": seed} _A = _DataSet(__lowercase , __lowercase , **__lowercase ) _A = _DataSet(__lowercase , __lowercase , **__lowercase ) _A = _DataSet(__lowercase , __lowercase , **__lowercase ) return _Datasets(train=__lowercase , validation=__lowercase , test=__lowercase )
79
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = '''ylacombe/bark-small''' __lowerCamelCase = tempfile.mkdtemp() __lowerCamelCase = '''en_speaker_1''' __lowerCamelCase = '''This is a test string''' __lowerCamelCase = '''speaker_embeddings_path.json''' __lowerCamelCase = '''speaker_embeddings''' def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Dict ): """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) processor.save_pretrained(self.tmpdirname ) __lowerCamelCase = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) __lowerCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowerCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) __lowerCamelCase = 35 __lowerCamelCase = 2 __lowerCamelCase = 8 __lowerCamelCase = { '''semantic_prompt''': np.ones(a ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from npz file __lowerCamelCase = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(a , **a ) __lowerCamelCase = processor(text=self.input_string , voice_preset=a ) __lowerCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from the hub __lowerCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = self.get_tokenizer() __lowerCamelCase = BarkProcessor(tokenizer=a ) __lowerCamelCase = processor(text=self.input_string ) __lowerCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
67
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor a__ : Optional[int] = logging.get_logger(__name__) class lowercase_ ( a__ ): def __init__( self , *a , **a ): warnings.warn( "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DPTImageProcessor instead." , a , ) super().__init__(*a , **a )
80
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={"configuration_vit_msn": ["VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP", "ViTMSNConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST", "ViTMSNModel", "ViTMSNForImageClassification", "ViTMSNPreTrainedModel", ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def _A ( lowercase ): """simple docstring""" a =SwinvaConfig() a =swinva_name.split('''_''' ) a =name_split[1] if "to" in name_split[3]: a =int(name_split[3][-3:] ) else: a =int(name_split[3] ) if "to" in name_split[2]: a =int(name_split[2][-2:] ) else: a =int(name_split[2][6:] ) if model_size == "tiny": a =96 a =(2, 2, 6, 2) a =(3, 6, 12, 24) elif model_size == "small": a =96 a =(2, 2, 18, 2) a =(3, 6, 12, 24) elif model_size == "base": a =1_28 a =(2, 2, 18, 2) a =(4, 8, 16, 32) else: a =1_92 a =(2, 2, 18, 2) a =(6, 12, 24, 48) if "to" in swinva_name: a =(12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a =2_18_41 a ='''huggingface/label-files''' a ='''imagenet-22k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} else: a =10_00 a ='''huggingface/label-files''' a ='''imagenet-1k-id2label.json''' a =json.load(open(hf_hub_download(lowercase , lowercase , repo_type='''dataset''' ) , '''r''' ) ) a ={int(lowercase ): v for k, v in idalabel.items()} a =idalabel a ={v: k for k, v in idalabel.items()} a =img_size a =num_classes a =embed_dim a =depths a =num_heads a =window_size return config def _A ( lowercase ): """simple docstring""" if "patch_embed.proj" in name: a =name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a =name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a ='''encoder.''' + name 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 "q_bias" in name: a =name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: a =name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: a =name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: a =name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if name == "norm.weight": a ='''layernorm.weight''' if name == "norm.bias": a ='''layernorm.bias''' if "head" in name: a =name.replace('''head''' , '''classifier''' ) else: a ='''swinv2.''' + name return name def _A ( lowercase , lowercase ): """simple docstring""" for key in orig_state_dict.copy().keys(): a =orig_state_dict.pop(lowercase ) if "mask" in key: continue elif "qkv" in key: a =key.split('''.''' ) a =int(key_split[1] ) a =int(key_split[3] ) a =model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a =val[:dim, :] a =val[dim : dim * 2, :] a =val[-dim:, :] else: a =val[:dim] a =val[ dim : dim * 2 ] a =val[-dim:] else: a =val return orig_state_dict def _A ( lowercase , lowercase ): """simple docstring""" a =timm.create_model(lowercase , pretrained=lowercase ) timm_model.eval() a =get_swinva_config(lowercase ) a =SwinvaForImageClassification(lowercase ) model.eval() a =convert_state_dict(timm_model.state_dict() , lowercase ) model.load_state_dict(lowercase ) a ='''http://images.cocodataset.org/val2017/000000039769.jpg''' a =AutoImageProcessor.from_pretrained('''microsoft/{}'''.format(swinva_name.replace('''_''' , '''-''' ) ) ) a =Image.open(requests.get(lowercase , stream=lowercase ).raw ) a =image_processor(images=lowercase , return_tensors='''pt''' ) a =timm_model(inputs['''pixel_values'''] ) a =model(**lowercase ).logits assert torch.allclose(lowercase , lowercase , atol=1E-3 ) print(f'''Saving model {swinva_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) model.push_to_hub( repo_path_or_name=Path(lowercase , lowercase ) , organization='''nandwalritik''' , commit_message='''Add model''' , ) if __name__ == "__main__": lowerCamelCase_ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 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.""" ) lowerCamelCase_ : Union[str, Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
81
'''simple docstring''' import re from filelock import FileLock try: import nltk __UpperCAmelCase =True except (ImportError, ModuleNotFoundError): __UpperCAmelCase =False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __lowerCAmelCase ( UpperCamelCase__ ) -> str: re.sub('''<n>''' , '''''' , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
67
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() A__ = logging.get_logger(__name__) def _UpperCAmelCase ( snake_case , snake_case=False ): """simple docstring""" _lowerCAmelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """vit.embeddings.cls_token"""), ("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _lowerCAmelCase = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def _UpperCAmelCase ( snake_case , snake_case , snake_case=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: _lowerCAmelCase = """""" else: _lowerCAmelCase = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _lowerCAmelCase = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) _lowerCAmelCase = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict _lowerCAmelCase = in_proj_weight[ : config.hidden_size, : ] _lowerCAmelCase = in_proj_bias[: config.hidden_size] _lowerCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _lowerCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _lowerCAmelCase = in_proj_weight[ -config.hidden_size :, : ] _lowerCAmelCase = in_proj_bias[-config.hidden_size :] def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(snake_case , snake_case ) def _UpperCAmelCase ( snake_case , snake_case , snake_case ): """simple docstring""" _lowerCAmelCase = dct.pop(snake_case ) _lowerCAmelCase = val def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = """http://images.cocodataset.org/val2017/000000039769.jpg""" _lowerCAmelCase = Image.open(requests.get(snake_case , stream=snake_case ).raw ) return im @torch.no_grad() def _UpperCAmelCase ( snake_case , snake_case , snake_case=True ): """simple docstring""" _lowerCAmelCase = ViTConfig() # patch_size if model_name[-1] == "8": _lowerCAmelCase = 8 # set labels if required if not base_model: _lowerCAmelCase = 10_00 _lowerCAmelCase = """huggingface/label-files""" _lowerCAmelCase = """imagenet-1k-id2label.json""" _lowerCAmelCase = json.load(open(hf_hub_download(snake_case , snake_case , repo_type="""dataset""" ) , """r""" ) ) _lowerCAmelCase = {int(snake_case ): v for k, v in idalabel.items()} _lowerCAmelCase = idalabel _lowerCAmelCase = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: _lowerCAmelCase = 3_84 _lowerCAmelCase = 15_36 _lowerCAmelCase = 12 _lowerCAmelCase = 6 # load original model from torch hub _lowerCAmelCase = torch.hub.load("""facebookresearch/dino:main""" , snake_case ) original_model.eval() # load state_dict of original model, remove and rename some keys _lowerCAmelCase = original_model.state_dict() if base_model: remove_classification_head_(snake_case ) _lowerCAmelCase = create_rename_keys(snake_case , base_model=snake_case ) for src, dest in rename_keys: rename_key(snake_case , snake_case , snake_case ) read_in_q_k_v(snake_case , snake_case , snake_case ) # load HuggingFace model if base_model: _lowerCAmelCase = ViTModel(snake_case , add_pooling_layer=snake_case ).eval() else: _lowerCAmelCase = ViTForImageClassification(snake_case ).eval() model.load_state_dict(snake_case ) # Check outputs on an image, prepared by ViTImageProcessor _lowerCAmelCase = ViTImageProcessor() _lowerCAmelCase = image_processor(images=prepare_img() , return_tensors="""pt""" ) _lowerCAmelCase = encoding["""pixel_values"""] _lowerCAmelCase = model(snake_case ) if base_model: _lowerCAmelCase = original_model(snake_case ) assert torch.allclose(snake_case , outputs.last_hidden_state[:, 0, :] , atol=1E-1 ) else: _lowerCAmelCase = original_model(snake_case ) assert logits.shape == outputs.logits.shape assert torch.allclose(snake_case , outputs.logits , atol=1E-3 ) Path(snake_case ).mkdir(exist_ok=snake_case ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(snake_case ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(snake_case ) if __name__ == "__main__": A__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""dino_vitb16""", type=str, help="""Name of the model trained with DINO 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( """--base_model""", action="""store_true""", help="""Whether to only convert the base model (no projection head weights).""", ) parser.set_defaults(base_model=True) A__ = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
82
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] ="gpt_neox_japanese" def __init__( self : List[Any] , a : Tuple=3_20_00 , a : Dict=25_60 , a : Union[str, Any]=32 , a : Dict=32 , a : Dict=4 , a : Optional[Any]="gelu" , a : Any=1.00 , a : str=1_00_00 , a : List[str]=20_48 , a : str=0.02 , a : Union[str, Any]=1e-5 , a : Optional[Any]=True , a : str=3_19_96 , a : List[str]=3_19_99 , a : str=0.1 , a : Union[str, Any]=0.0 , **a : Optional[Any] , ): """simple docstring""" super().__init__(bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase = vocab_size __lowerCamelCase = max_position_embeddings __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_multiple_size __lowerCamelCase = hidden_act __lowerCamelCase = rotary_pct __lowerCamelCase = rotary_emb_base __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = use_cache __lowerCamelCase = attention_dropout __lowerCamelCase = hidden_dropout
67
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) snake_case_ : int = { 'uclanlp/visualbert-vqa': 'https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json', 'uclanlp/visualbert-vqa-pre': 'https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json', 'uclanlp/visualbert-vqa-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-vcr': 'https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json', 'uclanlp/visualbert-vcr-pre': 'https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json', 'uclanlp/visualbert-vcr-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json' ), 'uclanlp/visualbert-nlvr2': 'https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-pre': 'https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json', 'uclanlp/visualbert-nlvr2-coco-pre': ( 'https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json' ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class lowercase__ ( lowercase ): lowercase__ = """visual_bert""" def __init__( self : List[Any] ,lowerCamelCase__ : Tuple=30522 ,lowerCamelCase__ : str=768 ,lowerCamelCase__ : List[str]=512 ,lowerCamelCase__ : Any=12 ,lowerCamelCase__ : Any=12 ,lowerCamelCase__ : Dict=3072 ,lowerCamelCase__ : List[str]="gelu" ,lowerCamelCase__ : Optional[int]=0.1 ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Optional[Any]=512 ,lowerCamelCase__ : Optional[int]=2 ,lowerCamelCase__ : Dict=0.0_2 ,lowerCamelCase__ : Optional[int]=1E-12 ,lowerCamelCase__ : Any=False ,lowerCamelCase__ : int=True ,lowerCamelCase__ : Optional[int]=1 ,lowerCamelCase__ : List[str]=0 ,lowerCamelCase__ : List[str]=2 ,**lowerCamelCase__ : str ,): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) _UpperCamelCase : Tuple = vocab_size _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : Dict = hidden_size _UpperCamelCase : Union[str, Any] = visual_embedding_dim _UpperCamelCase : List[Any] = num_hidden_layers _UpperCamelCase : str = num_attention_heads _UpperCamelCase : Any = intermediate_size _UpperCamelCase : Optional[int] = hidden_act _UpperCamelCase : int = hidden_dropout_prob _UpperCamelCase : Any = attention_probs_dropout_prob _UpperCamelCase : Optional[Any] = initializer_range _UpperCamelCase : Tuple = type_vocab_size _UpperCamelCase : Optional[Any] = layer_norm_eps _UpperCamelCase : List[Any] = bypass_transformer _UpperCamelCase : Optional[Any] = special_visual_initialize
83
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> int: while second != 0: __lowerCamelCase = first & second first ^= second __lowerCamelCase = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() __UpperCAmelCase =int(input("Enter the first number: ").strip()) __UpperCAmelCase =int(input("Enter the second number: ").strip()) print(f'{add(first, second) = }')
67
0
"""simple docstring""" def _snake_case ( lowercase__ : int ) -> Dict: '''simple docstring''' if collection == []: return [] # get some information about the collection lowerCAmelCase_ :List[Any] = len(lowercase__ ) lowerCAmelCase_ :Optional[Any] = max(lowercase__ ) lowerCAmelCase_ :Tuple = min(lowercase__ ) # create the counting array lowerCAmelCase_ :Optional[Any] = coll_max + 1 - coll_min lowerCAmelCase_ :int = [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__ ): lowerCAmelCase_ :Optional[Any] = counting_arr[i] + counting_arr[i - 1] # create the output collection lowerCAmelCase_ :Union[str, Any] = [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__ ) ): lowerCAmelCase_ :int = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def _snake_case ( lowercase__ : Optional[Any] ) -> Optional[int]: '''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" __UpperCAmelCase = input('Enter numbers separated by a comma:\n').strip() __UpperCAmelCase = [int(item) for item in user_input.split(',')] print(counting_sort(unsorted))
84
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def UpperCamelCase_( snake_case : Dict , snake_case : str , snake_case : List[str] ): '''simple docstring''' if isinstance(snake_case , torch.Tensor ): return image elif isinstance(snake_case , PIL.Image.Image ): snake_case_ = [image] if isinstance(image[0] , PIL.Image.Image ): snake_case_ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] snake_case_ = np.concatenate(snake_case , axis=0 ) snake_case_ = np.array(snake_case ).astype(np.floataa ) / 255.0 snake_case_ = image.transpose(0 , 3 , 1 , 2 ) snake_case_ = 2.0 * image - 1.0 snake_case_ = torch.from_numpy(snake_case ) elif isinstance(image[0] , torch.Tensor ): snake_case_ = torch.cat(snake_case , dim=0 ) return image def UpperCamelCase_( snake_case : Tuple , snake_case : str , snake_case : Union[str, Any] , snake_case : Any=0.9995 ): '''simple docstring''' if not isinstance(snake_case , np.ndarray ): snake_case_ = True snake_case_ = va.device snake_case_ = va.cpu().numpy() snake_case_ = va.cpu().numpy() snake_case_ = np.sum(va * va / (np.linalg.norm(snake_case ) * np.linalg.norm(snake_case )) ) if np.abs(snake_case ) > DOT_THRESHOLD: snake_case_ = (1 - t) * va + t * va else: snake_case_ = np.arccos(snake_case ) snake_case_ = np.sin(snake_case ) snake_case_ = theta_a * t snake_case_ = np.sin(snake_case ) snake_case_ = np.sin(theta_a - theta_t ) / sin_theta_a snake_case_ = sin_theta_t / sin_theta_a snake_case_ = sa * va + sa * va if inputs_are_torch: snake_case_ = torch.from_numpy(snake_case ).to(snake_case ) return va def UpperCamelCase_( snake_case : Tuple , snake_case : Any ): '''simple docstring''' snake_case_ = F.normalize(snake_case , dim=-1 ) snake_case_ = F.normalize(snake_case , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def UpperCamelCase_( snake_case : Optional[Any] , snake_case : Optional[Any] ): '''simple docstring''' for param in model.parameters(): snake_case_ = value class _snake_case ( lowercase_ ): def __init__( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , a__=None , a__=None , a__=None , ) -> Tuple: '''simple docstring''' super().__init__() self.register_modules( vae=a__ , text_encoder=a__ , clip_model=a__ , tokenizer=a__ , unet=a__ , scheduler=a__ , feature_extractor=a__ , coca_model=a__ , coca_tokenizer=a__ , coca_transform=a__ , ) snake_case_ = ( feature_extractor.size if isinstance(feature_extractor.size , a__ ) else feature_extractor.size["shortest_edge"] ) snake_case_ = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , a__ ) set_requires_grad(self.clip_model , a__ ) def lowerCAmelCase__ ( self , a__ = "auto" ) -> int: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory snake_case_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.enable_attention_slicing(a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' set_requires_grad(self.vae , a__ ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' set_requires_grad(self.vae , a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' set_requires_grad(self.unet , a__ ) def lowerCAmelCase__ ( self ) -> List[Any]: '''simple docstring''' set_requires_grad(self.unet , a__ ) def lowerCAmelCase__ ( self , a__ , a__ , a__ ) -> Optional[int]: '''simple docstring''' snake_case_ = min(int(num_inference_steps * strength ) , a__ ) snake_case_ = max(num_inference_steps - init_timestep , 0 ) snake_case_ = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__=None ) -> int: '''simple docstring''' if not isinstance(a__ , torch.Tensor ): raise ValueError(F'`image` has to be of type `torch.Tensor` but is {type(a__ )}' ) snake_case_ = image.to(device=a__ , dtype=a__ ) if isinstance(a__ , a__ ): snake_case_ = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(a__ ) ] snake_case_ = torch.cat(a__ , dim=0 ) else: snake_case_ = self.vae.encode(a__ ).latent_dist.sample(a__ ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 0.1_8_2_1_5 * init_latents snake_case_ = init_latents.repeat_interleave(a__ , dim=0 ) snake_case_ = randn_tensor(init_latents.shape , generator=a__ , device=a__ , dtype=a__ ) # get latents snake_case_ = self.scheduler.add_noise(a__ , a__ , a__ ) snake_case_ = init_latents return latents def lowerCAmelCase__ ( self , a__ ) -> Any: '''simple docstring''' snake_case_ = self.coca_transform(a__ ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): snake_case_ = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) snake_case_ = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>" , "" ).rstrip(" .," ) def lowerCAmelCase__ ( self , a__ , a__ ) -> int: '''simple docstring''' snake_case_ = self.feature_extractor.preprocess(a__ ) snake_case_ = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() snake_case_ = self.clip_model.get_image_features(a__ ) snake_case_ = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a__ ) snake_case_ = image_embeddings_clip.repeat_interleave(a__ , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowerCAmelCase__ ( self , a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) -> Optional[int]: '''simple docstring''' snake_case_ = latents.detach().requires_grad_() snake_case_ = self.scheduler.scale_model_input(a__ , a__ ) # predict the noise residual snake_case_ = self.unet(a__ , a__ , encoder_hidden_states=a__ ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): snake_case_ = self.scheduler.alphas_cumprod[timestep] snake_case_ = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case_ = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 snake_case_ = torch.sqrt(a__ ) snake_case_ = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , a__ ): snake_case_ = self.scheduler.sigmas[index] snake_case_ = latents - sigma * noise_pred else: raise ValueError(F'scheduler type {type(self.scheduler )} not supported' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 1 / 0.1_8_2_1_5 * sample snake_case_ = self.vae.decode(a__ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ = transforms.Resize(self.feature_extractor_size )(a__ ) snake_case_ = self.normalize(a__ ).to(latents.dtype ) snake_case_ = self.clip_model.get_image_features(a__ ) snake_case_ = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=a__ ) snake_case_ = spherical_dist_loss(a__ , a__ ).mean() * clip_guidance_scale snake_case_ = -torch.autograd.grad(a__ , a__ )[0] if isinstance(self.scheduler , a__ ): snake_case_ = latents.detach() + grads * (sigma**2) snake_case_ = noise_pred_original else: snake_case_ = noise_pred_original - torch.sqrt(a__ ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , a__ , a__ , a__ = None , a__ = None , a__ = 512 , a__ = 512 , a__ = 0.6 , a__ = 50 , a__ = 7.5 , a__ = 1 , a__ = 0.0 , a__ = 100 , a__ = None , a__ = "pil" , a__ = True , a__ = 0.8 , a__ = 0.1 , a__ = 0.1 , ) -> Tuple: '''simple docstring''' if isinstance(a__ , a__ ) and len(a__ ) != batch_size: raise ValueError(F'You have passed {batch_size} batch_size, but only {len(a__ )} generators.' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if isinstance(a__ , torch.Generator ) and batch_size > 1: snake_case_ = [generator] + [None] * (batch_size - 1) snake_case_ = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] snake_case_ = [x[0] for x in coca_is_none if x[1]] snake_case_ = ", ".join(a__ ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(a__ ): raise ValueError( F'Content prompt is None and CoCa [{coca_is_none_str}] is None.' F'Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) snake_case_ = self.get_image_description(a__ ) if style_prompt is None: if len(a__ ): raise ValueError( F'Style prompt is None and CoCa [{coca_is_none_str}] is None.' F' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.' ) snake_case_ = self.get_image_description(a__ ) # get prompt text embeddings for content and style snake_case_ = self.tokenizer( a__ , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=a__ , return_tensors="pt" , ) snake_case_ = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] snake_case_ = self.tokenizer( a__ , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=a__ , return_tensors="pt" , ) snake_case_ = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] snake_case_ = slerp(a__ , a__ , a__ ) # duplicate text embeddings for each generation per prompt snake_case_ = text_embeddings.repeat_interleave(a__ , dim=0 ) # set timesteps snake_case_ = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) snake_case_ = {} if accepts_offset: snake_case_ = 1 self.scheduler.set_timesteps(a__ , **a__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) snake_case_ , snake_case_ = self.get_timesteps(a__ , a__ , self.device ) snake_case_ = timesteps[:1].repeat(a__ ) # Preprocess image snake_case_ = preprocess(a__ , a__ , a__ ) snake_case_ = self.prepare_latents( a__ , a__ , a__ , text_embeddings.dtype , self.device , a__ ) snake_case_ = preprocess(a__ , a__ , a__ ) snake_case_ = self.prepare_latents( a__ , a__ , a__ , text_embeddings.dtype , self.device , a__ ) snake_case_ = slerp(a__ , a__ , a__ ) if clip_guidance_scale > 0: snake_case_ = self.get_clip_image_embeddings(a__ , a__ ) snake_case_ = self.get_clip_image_embeddings(a__ , a__ ) snake_case_ = slerp( a__ , a__ , a__ ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. snake_case_ = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: snake_case_ = content_text_input.input_ids.shape[-1] snake_case_ = self.tokenizer([""] , padding="max_length" , max_length=a__ , return_tensors="pt" ) snake_case_ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt snake_case_ = uncond_embeddings.repeat_interleave(a__ , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes snake_case_ = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. snake_case_ = (batch_size, self.unet.config.in_channels, height // 8, width // 8) snake_case_ = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps snake_case_ = torch.randn(a__ , generator=a__ , device="cpu" , dtype=a__ ).to( self.device ) else: snake_case_ = torch.randn(a__ , generator=a__ , device=self.device , dtype=a__ ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) snake_case_ = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case_ = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] snake_case_ = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case_ = {} if accepts_eta: snake_case_ = eta # check if the scheduler accepts generator snake_case_ = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: snake_case_ = generator with self.progress_bar(total=a__ ): for i, t in enumerate(a__ ): # expand the latents if we are doing classifier free guidance snake_case_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case_ = self.scheduler.scale_model_input(a__ , a__ ) # predict the noise residual snake_case_ = self.unet(a__ , a__ , encoder_hidden_states=a__ ).sample # perform classifier free guidance if do_classifier_free_guidance: snake_case_ , snake_case_ = noise_pred.chunk(2 ) snake_case_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: snake_case_ = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) snake_case_ , snake_case_ = self.cond_fn( a__ , a__ , a__ , a__ , a__ , a__ , a__ , ) # compute the previous noisy sample x_t -> x_t-1 snake_case_ = self.scheduler.step(a__ , a__ , a__ , **a__ ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor snake_case_ = 1 / 0.1_8_2_1_5 * latents snake_case_ = self.vae.decode(a__ ).sample snake_case_ = (image / 2 + 0.5).clamp(0 , 1 ) snake_case_ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case_ = self.numpy_to_pil(a__ ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=a__ , nsfw_content_detected=a__ )
85
'''simple docstring''' import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(UpperCamelCase__ ) == len(UpperCamelCase__ ), f"""{len(UpperCamelCase__ )} != {len(UpperCamelCase__ )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) __UpperCAmelCase ={ # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 1_2: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 1_1], 4: [0, 4, 8, 1_1], 6: [0, 2, 4, 7, 9, 1_1], 9: [0, 1, 2, 4, 5, 7, 9, 1_0, 1_1], 1_2: list(range(1_2)), }, 1_6: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 1_5], 3: [0, 8, 1_5], 4: [0, 5, 1_0, 1_5], 6: [0, 3, 6, 9, 1_2, 1_5], 8: [0, 2, 4, 6, 8, 1_0, 1_2, 1_5], 9: [0, 1, 3, 5, 7, 9, 1_1, 1_3, 1_5], 1_2: [0, 1, 2, 3, 4, 5, 6, 7, 9, 1_1, 1_3, 1_5], 1_6: list(range(1_6)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } __UpperCAmelCase ={ # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 1_2: {1: [1_1], 2: [5, 1_1], 3: [3, 7, 1_1], 6: [1, 3, 5, 8, 1_0, 1_1]}, 1_6: {1: [1_5], 4: [4, 9, 1_2, 1_5], 8: [1, 3, 5, 7, 9, 1_1, 1_3, 1_5]}, } def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: try: __lowerCamelCase = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( f"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" f""" {n_student}""" ) return list(range(UpperCamelCase__ ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> List[int]: if n_student > n_teacher: raise ValueError(f"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(UpperCamelCase__ ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = "student" , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__=False , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __lowerCamelCase = '''encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.''' assert (e is not None) or (d is not None), _msg if isinstance(UpperCamelCase__ , UpperCamelCase__ ): AutoTokenizer.from_pretrained(UpperCamelCase__ ).save_pretrained(UpperCamelCase__ ) # purely for convenience __lowerCamelCase = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ ).eval() else: assert isinstance(UpperCamelCase__ , UpperCamelCase__ ), f"""teacher must be a model or string got type {type(UpperCamelCase__ )}""" __lowerCamelCase = teacher.config.to_diff_dict() try: __lowerCamelCase , __lowerCamelCase = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d init_kwargs.update({'''encoder_layers''': e, '''decoder_layers''': d} ) except AttributeError: # T5 if hasattr(teacher.config , '''num_encoder_layers''' ): __lowerCamelCase , __lowerCamelCase = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __lowerCamelCase , __lowerCamelCase = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __lowerCamelCase = teacher_e if d is None: __lowerCamelCase = teacher_d if hasattr(teacher.config , '''num_encoder_layers''' ): init_kwargs.update({'''num_encoder_layers''': e, '''num_decoder_layers''': d} ) else: init_kwargs.update({'''num_layers''': e, '''num_decoder_layers''': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(UpperCamelCase__ ) # Copy weights __lowerCamelCase = teacher.config_class(**UpperCamelCase__ ) __lowerCamelCase = AutoModelForSeqaSeqLM.from_config(UpperCamelCase__ ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __lowerCamelCase = student.load_state_dict(teacher.state_dict() , strict=UpperCamelCase__ ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __lowerCamelCase , __lowerCamelCase = list(range(UpperCamelCase__ ) ), list(range(UpperCamelCase__ ) ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" f""" {save_path}""" ) student.save_pretrained(UpperCamelCase__ ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) if d_layers_to_copy is None: __lowerCamelCase = pick_layers_to_copy(UpperCamelCase__ , UpperCamelCase__ ) try: if hasattr( UpperCamelCase__ , '''prophetnet''' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , UpperCamelCase__ ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , UpperCamelCase__ ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , UpperCamelCase__ ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , UpperCamelCase__ ) copy_layers(teacher.decoder.block , student.decoder.block , UpperCamelCase__ ) logger.info( f"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __lowerCamelCase = { '''teacher_type''': teacher.config.model_type, '''copied_encoder_layers''': e_layers_to_copy, '''copied_decoder_layers''': d_layers_to_copy, } student.save_pretrained(UpperCamelCase__ ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
67
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 transformers import ( SwiftFormerConfig, SwiftFormerForImageClassification, ViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = torch.device("""cpu""") def __lowerCAmelCase (): __lowerCAmelCase : List[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' __lowerCAmelCase : Dict = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im def __lowerCAmelCase (_UpperCamelCase ): if swiftformer_name == "swiftformer_xs": return torch.tensor([-2.1_7_0_3e0_0, 2.1_1_0_7e0_0, -2.0_8_1_1e0_0, 8.8_6_8_5e-0_1, 2.4_3_6_0e-0_1] ) elif swiftformer_name == "swiftformer_s": return torch.tensor([3.9_6_3_6e-0_1, 2.3_4_7_8e-0_1, -1.6_9_6_3e0_0, -1.7_3_8_1e0_0, -8.6_3_3_7e-0_1] ) elif swiftformer_name == "swiftformer_l1": return torch.tensor([-4.2_7_6_8e-0_1, -4.7_4_2_9e-0_1, -1.0_8_9_7e0_0, -1.0_2_4_8e0_0, 3.5_5_2_3e-0_2] ) elif swiftformer_name == "swiftformer_l3": return torch.tensor([-2.5_3_3_0e-0_1, 2.4_2_1_1e-0_1, -6.0_1_8_5e-0_1, -8.2_7_8_9e-0_1, -6.0_4_4_6e-0_2] ) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Tuple = dct.pop(_UpperCamelCase ) __lowerCAmelCase : Dict = val def __lowerCAmelCase (_UpperCamelCase ): __lowerCAmelCase : Optional[Any] = [] for k in state_dict.keys(): __lowerCAmelCase : str = k if ".pwconv" in k: __lowerCAmelCase : List[str] = k_new.replace('.pwconv' , '.point_wise_conv' ) if ".dwconv" in k: __lowerCAmelCase : Tuple = k_new.replace('.dwconv' , '.depth_wise_conv' ) if ".Proj." in k: __lowerCAmelCase : Optional[int] = k_new.replace('.Proj.' , '.proj.' ) if "patch_embed" in k_new: __lowerCAmelCase : List[Any] = k_new.replace('patch_embed' , 'swiftformer.patch_embed.patch_embedding' ) if "network" in k_new: __lowerCAmelCase : Optional[Any] = k_new.split('.' ) if ls[2].isdigit(): __lowerCAmelCase : Union[str, Any] = 'swiftformer.encoder.network.' + ls[1] + '.blocks.' + ls[2] + '.' + '.'.join(ls[3:] ) else: __lowerCAmelCase : int = k_new.replace('network' , 'swiftformer.encoder.network' ) rename_keys.append((k, k_new) ) return rename_keys @torch.no_grad() def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Tuple = SwiftFormerConfig() # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size __lowerCAmelCase : Tuple = 1000 __lowerCAmelCase : Tuple = 'huggingface/label-files' __lowerCAmelCase : Any = 'imagenet-1k-id2label.json' __lowerCAmelCase : Dict = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) __lowerCAmelCase : Optional[Any] = {int(_UpperCamelCase ): v for k, v in idalabel.items()} __lowerCAmelCase : Optional[Any] = idalabel __lowerCAmelCase : Any = {v: k for k, v in idalabel.items()} # size of the architecture if swiftformer_name == "swiftformer_xs": __lowerCAmelCase : Optional[int] = [3, 3, 6, 4] __lowerCAmelCase : Union[str, Any] = [48, 56, 112, 220] elif swiftformer_name == "swiftformer_s": __lowerCAmelCase : str = [3, 3, 9, 6] __lowerCAmelCase : Tuple = [48, 64, 168, 224] elif swiftformer_name == "swiftformer_l1": __lowerCAmelCase : int = [4, 3, 10, 5] __lowerCAmelCase : List[Any] = [48, 96, 192, 384] elif swiftformer_name == "swiftformer_l3": __lowerCAmelCase : Union[str, Any] = [4, 4, 12, 6] __lowerCAmelCase : List[str] = [64, 128, 320, 512] # load state_dict of original model, remove and rename some keys if original_ckpt: if original_ckpt.startswith('https' ): __lowerCAmelCase : List[Any] = torch.hub.load_state_dict_from_url(_UpperCamelCase , map_location='cpu' , check_hash=_UpperCamelCase ) else: __lowerCAmelCase : Optional[int] = torch.load(_UpperCamelCase , map_location='cpu' ) __lowerCAmelCase : List[Any] = checkpoint __lowerCAmelCase : Optional[int] = create_rename_keys(_UpperCamelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # load HuggingFace model __lowerCAmelCase : Optional[Any] = SwiftFormerForImageClassification(_UpperCamelCase ).eval() hf_model.load_state_dict(_UpperCamelCase ) # prepare test inputs __lowerCAmelCase : Optional[Any] = prepare_img() __lowerCAmelCase : Optional[Any] = ViTImageProcessor.from_pretrained('preprocessor_config' ) __lowerCAmelCase : Dict = processor(images=_UpperCamelCase , return_tensors='pt' ) # compare outputs from both models __lowerCAmelCase : int = get_expected_output(_UpperCamelCase ) __lowerCAmelCase : Tuple = hf_model(inputs['pixel_values'] ).logits assert hf_logits.shape == torch.Size([1, 1000] ) assert torch.allclose(hf_logits[0, 0:5] , _UpperCamelCase , atol=1e-3 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(F"Saving model {swiftformer_name} to {pytorch_dump_folder_path}" ) hf_model.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swiftformer_name""", default="""swiftformer_xs""", choices=["""swiftformer_xs""", """swiftformer_s""", """swiftformer_l1""", """swiftformer_l3"""], type=str, help="""Name of the SwiftFormer model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default="""./converted_outputs/""", type=str, help="""Path to the output PyTorch model directory.""", ) parser.add_argument("""--original_ckpt""", default=None, type=str, help="""Path to the original model checkpoint.""") lowerCamelCase__ = parser.parse_args() convert_swiftformer_checkpoint(args.swiftformer_name, args.pytorch_dump_folder_path, args.original_ckpt)
86
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __UpperCAmelCase =["gpt2"] __UpperCAmelCase ="gpt2" if is_tf_available(): class a__ ( tf.Module ): def __init__( self : str , a : Union[str, Any] ): """simple docstring""" super().__init__() __lowerCamelCase = tokenizer __lowerCamelCase = AutoConfig.from_pretrained(a ) __lowerCamelCase = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = self.tokenizer(a ) __lowerCamelCase = tokenized['''input_ids'''].to_tensor() __lowerCamelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase = self.model(input_ids=a , attention_mask=a )['''logits'''] return outputs @require_tf @require_keras_nlp class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" super().setUp() __lowerCamelCase = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowerCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase = tokenizer([test_inputs] , return_tensors='''tf''' ) __lowerCamelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase = python_outputs[key].numpy() __lowerCamelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase = tf.constant(a ) __lowerCamelCase = compiled_tokenizer(a ) __lowerCamelCase = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = ModelToSave(tokenizer=a ) __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase = Path(a ) / '''saved.model''' tf.saved_model.save(a , a , signatures={'''serving_default''': model.serving} ) __lowerCamelCase = tf.saved_model.load(a ) __lowerCamelCase = loaded_model.signatures['''serving_default'''](a )['''output_0'''] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase = tf_tokenizer.get_config() __lowerCamelCase = TFGPTaTokenizer.from_config(a ) __lowerCamelCase = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase = 12_31_23 for max_length in [3, 5, 10_24]: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a , max_length=a ) __lowerCamelCase = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
67
0
UpperCamelCase = '''Tobias Carryer''' from time import time class snake_case_ : def __init__( self : str , lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Optional[int]=int(time() ) ) -> Dict: # noqa: B008 lowercase__ : Dict = multiplier lowercase__ : int = increment lowercase__ : int = modulo lowercase__ : Optional[int] = seed def __UpperCamelCase ( self : List[Any] ) -> Dict: lowercase__ : Union[str, Any] = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. UpperCamelCase = LinearCongruentialGenerator(166_4525, 10_1390_4223, 2 << 31) while True: print(lcg.next_number())
87
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
67
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__) __lowerCAmelCase : Tuple = { 'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = """pegasus""" a__ = ["""past_key_values"""] a__ = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[int] , UpperCamelCase__ : Optional[int]=5_0265 , UpperCamelCase__ : Optional[int]=1024 , UpperCamelCase__ : Any=12 , UpperCamelCase__ : Union[str, Any]=4096 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : Union[str, Any]=12 , UpperCamelCase__ : List[str]=4096 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=0.0 , UpperCamelCase__ : List[Any]=0.0 , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : List[Any]=1024 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : str=0.0 , UpperCamelCase__ : Any=0.0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : Any=0 , UpperCamelCase__ : int=False , UpperCamelCase__ : Any=0 , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : Tuple=1 , **UpperCamelCase__ : Union[str, Any] , ) -> str: """simple docstring""" __magic_name__ = vocab_size __magic_name__ = max_position_embeddings __magic_name__ = d_model __magic_name__ = encoder_ffn_dim __magic_name__ = encoder_layers __magic_name__ = encoder_attention_heads __magic_name__ = decoder_ffn_dim __magic_name__ = decoder_layers __magic_name__ = decoder_attention_heads __magic_name__ = dropout __magic_name__ = attention_dropout __magic_name__ = activation_dropout __magic_name__ = activation_function __magic_name__ = init_std __magic_name__ = encoder_layerdrop __magic_name__ = decoder_layerdrop __magic_name__ = use_cache __magic_name__ = encoder_layers __magic_name__ = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , forced_eos_token_id=UpperCamelCase__ , **UpperCamelCase__ , ) @property def _lowercase ( self : List[Any] ) -> int: """simple docstring""" return self.encoder_attention_heads @property def _lowercase ( self : Dict ) -> int: """simple docstring""" return self.d_model
88
'''simple docstring''' import logging import os from .state import PartialState class a__ ( logging.LoggerAdapter ): @staticmethod def SCREAMING_SNAKE_CASE__ ( a : Optional[Any] ): """simple docstring""" __lowerCamelCase = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[int] , a : str , *a : Optional[int] , **a : List[Any] ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __lowerCamelCase = kwargs.pop('''main_process_only''' , a ) __lowerCamelCase = kwargs.pop('''in_order''' , a ) if self.isEnabledFor(a ): if self._should_log(a ): __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) elif in_order: __lowerCamelCase = PartialState() for i in range(state.num_processes ): if i == state.process_index: __lowerCamelCase , __lowerCamelCase = self.process(a , a ) self.logger.log(a , a , *a , **a ) state.wait_for_everyone() def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = None ) -> Optional[int]: if log_level is None: __lowerCamelCase = os.environ.get('''ACCELERATE_LOG_LEVEL''' , UpperCamelCase__ ) __lowerCamelCase = logging.getLogger(UpperCamelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(UpperCamelCase__ , {} )
67
0
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Optional[Any]: _a : List[str] = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' _a : Optional[Any] = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ).convert('RGB' ) _a : Optional[Any] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711) ), ] ) _a : List[str] = transform(lowerCAmelCase_ ).unsqueeze(0 ).to(lowerCAmelCase_ ) return image def __lowerCamelCase ( lowerCAmelCase_ ) -> int: if "visual_encoder" in key: _a : List[str] = re.sub('visual_encoder*' , 'vision_model.encoder' , lowerCAmelCase_ ) if "blocks" in key: _a : int = re.sub(r'blocks' , 'layers' , lowerCAmelCase_ ) if "attn" in key: _a : Optional[int] = re.sub(r'attn' , 'self_attn' , lowerCAmelCase_ ) if "norm1" in key: _a : List[str] = re.sub(r'norm1' , 'layer_norm1' , lowerCAmelCase_ ) if "norm2" in key: _a : str = re.sub(r'norm2' , 'layer_norm2' , lowerCAmelCase_ ) if "encoder.norm" in key: _a : int = re.sub(r'encoder.norm' , 'post_layernorm' , lowerCAmelCase_ ) if "encoder.patch_embed.proj" in key: _a : Union[str, Any] = re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , lowerCAmelCase_ ) if "encoder.pos_embed" in key: _a : Tuple = re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , lowerCAmelCase_ ) if "encoder.cls_token" in key: _a : Tuple = re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , lowerCAmelCase_ ) if "self_attn" in key: _a : Any = re.sub(r'self_attn.proj' , 'self_attn.projection' , lowerCAmelCase_ ) return key @torch.no_grad() def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=None ) -> int: if config_path is not None: _a : Tuple = BlipConfig.from_pretrained(lowerCAmelCase_ ) else: _a : int = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) _a : Dict = BlipForConditionalGeneration(lowerCAmelCase_ ).eval() _a : Any = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' _a : List[str] = blip_decoder(pretrained=lowerCAmelCase_ , image_size=384 , vit='base' ) _a : int = pt_model.eval() _a : Any = pt_model.state_dict() for key in modified_state_dict.copy(): _a : List[str] = modified_state_dict.pop(lowerCAmelCase_ ) _a : Optional[Any] = rename_key(lowerCAmelCase_ ) _a : Any = value hf_model.load_state_dict(lowerCAmelCase_ ) _a : Optional[int] = 384 _a : List[str] = load_demo_image(image_size=lowerCAmelCase_ , device='cpu' ) _a : Optional[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) _a : int = tokenizer(['a picture of'] ).input_ids _a : List[str] = hf_model.generate(lowerCAmelCase_ , lowerCAmelCase_ ) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] _a : List[str] = hf_model.generate(lowerCAmelCase_ ) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(lowerCAmelCase_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _a : Tuple = ( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) _a : Optional[Any] = blip_vqa(pretrained=lowerCAmelCase_ , image_size=lowerCAmelCase_ , vit='base' ) vqa_model.eval() _a : Optional[int] = vqa_model.state_dict() for key in modified_state_dict.copy(): _a : int = modified_state_dict.pop(lowerCAmelCase_ ) _a : Optional[int] = rename_key(lowerCAmelCase_ ) _a : Dict = value _a : Optional[int] = BlipForQuestionAnswering(lowerCAmelCase_ ) hf_vqa_model.load_state_dict(lowerCAmelCase_ ) _a : List[str] = ['How many dogs are in this image?'] _a : str = tokenizer(lowerCAmelCase_ , return_tensors='pt' ).input_ids _a : Dict = hf_vqa_model.generate(lowerCAmelCase_ , lowerCAmelCase_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa' ) _a : int = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' _a : List[str] = blip_itm(pretrained=lowerCAmelCase_ , image_size=lowerCAmelCase_ , vit='base' ) itm_model.eval() _a : Any = itm_model.state_dict() for key in modified_state_dict.copy(): _a : Optional[int] = modified_state_dict.pop(lowerCAmelCase_ ) _a : Any = rename_key(lowerCAmelCase_ ) _a : Dict = value _a : Tuple = BlipForImageTextRetrieval(lowerCAmelCase_ ) _a : Any = ['A picture of a woman with a dog sitting in a beach'] _a : List[str] = tokenizer( lowerCAmelCase_ , return_tensors='pt' , padding='max_length' , truncation=lowerCAmelCase_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(lowerCAmelCase_ ) hf_itm_model.eval() _a : str = hf_itm_model(lowerCAmelCase_ , lowerCAmelCase_ , use_itm_head=lowerCAmelCase_ ) _a : Any = hf_itm_model(lowerCAmelCase_ , lowerCAmelCase_ , use_itm_head=lowerCAmelCase_ ) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm' ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') __lowerCAmelCase = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
89
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ ) -> Optional[Any]: __lowerCamelCase = [] __lowerCamelCase = set({'''(''', '''[''', '''{'''} ) __lowerCamelCase = set({''')''', ''']''', '''}'''} ) __lowerCamelCase = {'''{''': '''}''', '''[''': ''']''', '''(''': ''')'''} for i in range(len(UpperCamelCase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(UpperCamelCase__ ) == 0 or (len(UpperCamelCase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(UpperCamelCase__ ) == 0 def __lowerCAmelCase ( ) -> str: __lowerCamelCase = input('''Enter sequence of brackets: ''' ) if is_balanced(UpperCamelCase__ ): print(UpperCamelCase__ , '''is balanced''' ) else: print(UpperCamelCase__ , '''is not balanced''' ) if __name__ == "__main__": main()
67
0
import math import os import sys def lowerCamelCase_ ( UpperCamelCase__ : str ) -> str: """simple docstring""" __lowerCamelCase = '' try: with open(UpperCamelCase__ , 'rb' ) as binary_file: __lowerCamelCase = binary_file.read() for dat in data: __lowerCamelCase = F"""{dat:08b}""" result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def lowerCamelCase_ ( UpperCamelCase__ : dict[str, str] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str ) -> None: """simple docstring""" lexicon.pop(UpperCamelCase__ ) __lowerCamelCase = last_match_id if math.loga(UpperCamelCase__ ).is_integer(): for curr_key in lexicon: __lowerCamelCase = '0' + lexicon[curr_key] __lowerCamelCase = bin(UpperCamelCase__ )[2:] def lowerCamelCase_ ( UpperCamelCase__ : str ) -> str: """simple docstring""" __lowerCamelCase = {'0': '0', '1': '1'} __lowerCamelCase , __lowerCamelCase = '', '' __lowerCamelCase = len(UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __lowerCamelCase = lexicon[curr_string] result += last_match_id add_key_to_lexicon(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) index += 1 __lowerCamelCase = '' while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": __lowerCamelCase = lexicon[curr_string] result += last_match_id return result def lowerCamelCase_ ( UpperCamelCase__ : str , UpperCamelCase__ : str ) -> str: """simple docstring""" __lowerCamelCase = os.path.getsize(UpperCamelCase__ ) __lowerCamelCase = bin(UpperCamelCase__ )[2:] __lowerCamelCase = len(UpperCamelCase__ ) return "0" * (length_length - 1) + file_length_binary + compressed def lowerCamelCase_ ( UpperCamelCase__ : str , UpperCamelCase__ : str ) -> None: """simple docstring""" __lowerCamelCase = 8 try: with open(UpperCamelCase__ , 'wb' ) as opened_file: __lowerCamelCase = [ to_write[i : i + byte_length] for i in range(0 , len(UpperCamelCase__ ) , UpperCamelCase__ ) ] 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(UpperCamelCase__ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def lowerCamelCase_ ( UpperCamelCase__ : str , UpperCamelCase__ : str ) -> None: """simple docstring""" __lowerCamelCase = read_file_binary(UpperCamelCase__ ) __lowerCamelCase = compress_data(UpperCamelCase__ ) __lowerCamelCase = add_file_length(UpperCamelCase__ , UpperCamelCase__ ) write_file_binary(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
90
'''simple docstring''' import torch from transformers import PreTrainedModel, XLMRobertaConfig, XLMRobertaModel class a__ ( UpperCAmelCase__ ): lowerCamelCase : Dict ="M-CLIP" def __init__( self : Tuple , a : Optional[int]=10_24 , a : Tuple=7_68 , **a : List[str] ): """simple docstring""" __lowerCamelCase = transformerDimSize __lowerCamelCase = imageDimSize super().__init__(**a ) class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[Any] =MCLIPConfig def __init__( self : str , a : List[Any] , *a : Dict , **a : str ): """simple docstring""" super().__init__(a , *a , **a ) __lowerCamelCase = XLMRobertaModel(a ) __lowerCamelCase = torch.nn.Linear( in_features=config.transformerDimensions , out_features=config.numDims ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , a : int , a : List[Any] ): """simple docstring""" __lowerCamelCase = self.transformer(input_ids=a , attention_mask=a )[0] __lowerCamelCase = (embs * attention_mask.unsqueeze(2 )).sum(dim=1 ) / attention_mask.sum(dim=1 )[:, None] return self.LinearTransformation(a ), embs
67
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def _A () -> Generator[int, None, None]: """simple docstring""" SCREAMING_SNAKE_CASE_ : dict[int, int] = {} SCREAMING_SNAKE_CASE_ : List[Any] = 2 while True: SCREAMING_SNAKE_CASE_ : int = factor_map.pop(__a , __a ) if factor: SCREAMING_SNAKE_CASE_ : Union[str, Any] = factor + prime while x in factor_map: x += factor SCREAMING_SNAKE_CASE_ : List[str] = factor else: SCREAMING_SNAKE_CASE_ : List[str] = prime yield prime prime += 1 def _A (__a = 1e10 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = sieve() SCREAMING_SNAKE_CASE_ : Optional[int] = 1 while True: SCREAMING_SNAKE_CASE_ : Union[str, Any] = next(__a ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(__a ) n += 2 if __name__ == "__main__": print(solution())
91
'''simple docstring''' from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
67
0
import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py UpperCamelCase__ = """src/diffusers""" # Matches is_xxx_available() UpperCamelCase__ = re.compile(R"""is\_([a-z_]*)_available\(\)""") # Matches from xxx import bla UpperCamelCase__ = re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""") UpperCamelCase__ = """ {0} = None """ UpperCamelCase__ = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, {1}) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, {1}) """ UpperCamelCase__ = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ def _a ( SCREAMING_SNAKE_CASE_ : Tuple ): __lowerCAmelCase = _re_backend.findall(SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) == 0: return None return "_and_".join(SCREAMING_SNAKE_CASE_ ) def _a ( ): with open(os.path.join(SCREAMING_SNAKE_CASE_ , "__init__.py" ) , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.readlines() # Get to the point we do the actual imports for type checking __lowerCAmelCase = 0 __lowerCAmelCase = {} # Go through the end of the file while line_index < len(SCREAMING_SNAKE_CASE_ ): # If the line contains is_backend_available, we grab all objects associated with the `else` block __lowerCAmelCase = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith("else:" ): line_index += 1 line_index += 1 __lowerCAmelCase = [] # Until we unindent, add backend objects to the list while line_index < len(SCREAMING_SNAKE_CASE_ ) and len(lines[line_index] ) > 1: __lowerCAmelCase = lines[line_index] __lowerCAmelCase = _re_single_line_import.search(SCREAMING_SNAKE_CASE_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(SCREAMING_SNAKE_CASE_ ) > 0: __lowerCAmelCase = objects else: line_index += 1 return backend_specific_objects def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] ): if name.isupper(): return DUMMY_CONSTANT.format(SCREAMING_SNAKE_CASE_ ) elif name.islower(): return DUMMY_FUNCTION.format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: return DUMMY_CLASS.format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ): if backend_specific_objects is None: __lowerCAmelCase = read_init() # For special correspondence backend to module name as used in the function requires_modulename __lowerCAmelCase = {} for backend, objects in backend_specific_objects.items(): __lowerCAmelCase = "[" + ", ".join(F"""\"{b}\"""" for b in backend.split("_and_" ) ) + "]" __lowerCAmelCase = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for o in objects] ) __lowerCAmelCase = dummy_file return dummy_files def _a ( SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ): __lowerCAmelCase = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py __lowerCAmelCase = {"torch": "pt"} # Locate actual dummy modules and read their content. __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , "utils" ) __lowerCAmelCase = { backend: os.path.join(SCREAMING_SNAKE_CASE_ , F"""dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py""" ) for backend in dummy_files.keys() } __lowerCAmelCase = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(SCREAMING_SNAKE_CASE_ ): with open(SCREAMING_SNAKE_CASE_ , "r" , encoding="utf-8" , newline="\n" ) as f: __lowerCAmelCase = f.read() else: __lowerCAmelCase = "" for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F"""Updating diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py as the main """ "__init__ has new objects." ) with open(dummy_file_paths[backend] , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(dummy_files[backend] ) else: raise ValueError( "The main __init__ has objects that are not present in " F"""diffusers.utils.dummy_{short_names.get(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}_objects.py. Run `make fix-copies` """ "to fix this." ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") UpperCamelCase__ = parser.parse_args() check_dummies(args.fix_and_overwrite)
92
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def __lowerCAmelCase ( UpperCamelCase__ ) -> list[list[float]]: __lowerCamelCase = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(UpperCamelCase__ ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix __lowerCamelCase = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements __lowerCamelCase = [[0.0, 0.0], [0.0, 0.0]] __lowerCamelCase , __lowerCamelCase = matrix[1][1], matrix[0][0] __lowerCamelCase , __lowerCamelCase = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(UpperCamelCase__ ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(UpperCamelCase__ ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule __lowerCamelCase = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix __lowerCamelCase = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] __lowerCamelCase = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) __lowerCamelCase = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) __lowerCamelCase = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) __lowerCamelCase = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) __lowerCamelCase = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): __lowerCamelCase = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix __lowerCamelCase = array(UpperCamelCase__ ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(UpperCamelCase__ ) # Calculate the inverse of the matrix return [[float(d(UpperCamelCase__ ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
67
0
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap _lowercase : Union[str, Any] = "Usage of script: script_name <size_of_canvas:int>" _lowercase : Union[str, Any] = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def snake_case_ ( __SCREAMING_SNAKE_CASE : int ): """simple docstring""" lowercase_ : Union[str, Any] = [[False for i in range(__SCREAMING_SNAKE_CASE )] for j in range(__SCREAMING_SNAKE_CASE )] return canvas def snake_case_ ( __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" for i, row in enumerate(__SCREAMING_SNAKE_CASE ): for j, _ in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = bool(random.getrandbits(1 ) ) def snake_case_ ( __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" lowercase_ : str = np.array(__SCREAMING_SNAKE_CASE ) lowercase_ : Any = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__SCREAMING_SNAKE_CASE ): for c, pt in enumerate(__SCREAMING_SNAKE_CASE ): lowercase_ : List[Any] = __judge_point( __SCREAMING_SNAKE_CASE , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) lowercase_ : Dict = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. lowercase_ : list[list[bool]] = current_canvas.tolist() return return_canvas def snake_case_ ( __SCREAMING_SNAKE_CASE : bool , __SCREAMING_SNAKE_CASE : list[list[bool]] ): """simple docstring""" lowercase_ : List[str] = 0 lowercase_ : Tuple = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. lowercase_ : Union[str, Any] = pt if pt: if alive < 2: lowercase_ : Optional[int] = False elif alive == 2 or alive == 3: lowercase_ : int = True elif alive > 3: lowercase_ : Any = False else: if alive == 3: lowercase_ : str = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) _lowercase : Tuple = int(sys.argv[1]) # main working structure of this module. _lowercase : int = create_canvas(canvas_size) seed(c) _lowercase , _lowercase : List[str] = plt.subplots() fig.show() _lowercase : str = ListedColormap(["w", "k"]) try: while True: _lowercase : str = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
93
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
0
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin snake_case : List[str] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class _snake_case ( _snake_case , unittest.TestCase ): SCREAMING_SNAKE_CASE__ = XLNetTokenizer SCREAMING_SNAKE_CASE__ = XLNetTokenizerFast SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True def SCREAMING_SNAKE_CASE__ ( self ): super().setUp() # We have a SentencePiece fixture for testing a :Dict = XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self ): a :int = '''<s>''' a :Optional[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE__ ( self ): a :int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<eod>''' ) self.assertEqual(len(_lowerCamelCase ) , 1006 ) def SCREAMING_SNAKE_CASE__ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def SCREAMING_SNAKE_CASE__ ( self ): a :int = XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) a :Dict = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [285, 46, 10, 170, 382] ) a :Optional[int] = 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 :Union[str, Any] = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) a :int = 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>''', '''.''', ] , ) def SCREAMING_SNAKE_CASE__ ( self ): a :Optional[Any] = XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) a :Dict = 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''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def SCREAMING_SNAKE_CASE__ ( self ): a :List[Any] = XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) a :Optional[int] = 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''', '''se''', '''.''', ] , ) @slow def SCREAMING_SNAKE_CASE__ ( self ): a :int = XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) a :Optional[Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=_lowerCamelCase ) a :Any = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_lowerCamelCase ) a :Dict = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) a :Any = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def SCREAMING_SNAKE_CASE__ ( self ): # fmt: off a :Dict = {'''input_ids''': [[17, 2_1442, 270, 17, 10, 1_4645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 2_2018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 1_4431, 13, 5500, 11, 1176, 580, 13, 1_6819, 4797, 23, 17, 10, 1_7135, 658, 19, 457, 7932, 13, 184, 19, 3154, 1_7135, 6468, 19, 1404, 1_2269, 19, 4229, 5356, 1_6264, 46, 19, 17, 2_0545, 1_0395, 9, 9, 9, 11, 28, 6421, 9531, 2_0729, 17, 10, 353, 1_7022, 11, 21, 6421, 9531, 1_6949, 17, 10, 1_1509, 753, 11, 33, 95, 2421, 7385, 956, 1_4431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 2_4738, 19, 1_3203, 658, 218, 787, 21, 430, 1_8482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 2_2178, 27, 1064, 22, 956, 13, 1_1101, 1429, 5854, 2_4313, 1_8953, 40, 422, 2_4366, 68, 1758, 37, 1_0483, 1_4257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 1_3894, 3380, 23, 95, 18, 1_7634, 2288, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
94
'''simple docstring''' 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_barthez import BarthezTokenizer else: __UpperCAmelCase =None __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} __UpperCAmelCase ={ "vocab_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "moussaKam/mbarthez": "https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json", "moussaKam/barthez": "https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json", "moussaKam/barthez-orangesum-title": ( "https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json" ), }, } __UpperCAmelCase ={ "moussaKam/mbarthez": 1_0_2_4, "moussaKam/barthez": 1_0_2_4, "moussaKam/barthez-orangesum-title": 1_0_2_4, } __UpperCAmelCase ="▁" class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =VOCAB_FILES_NAMES lowerCamelCase : Optional[Any] =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : int =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : Optional[Any] =["input_ids", "attention_mask"] lowerCamelCase : Union[str, Any] =BarthezTokenizer def __init__( self : Optional[Any] , a : Dict=None , a : str=None , a : List[Any]="<s>" , a : Optional[int]="</s>" , a : List[str]="</s>" , a : Tuple="<s>" , a : str="<unk>" , a : Any="<pad>" , a : Union[str, Any]="<mask>" , **a : Union[str, Any] , ): """simple docstring""" __lowerCamelCase = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) __lowerCamelCase = vocab_file __lowerCamelCase = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] __lowerCamelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ): """simple docstring""" __lowerCamelCase = [self.sep_token_id] __lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : str , a : Optional[str] = None ): """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(a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __lowerCamelCase = os.path.join( a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
67
0
# flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Dict[Optional[str], Type[Formatter]] = {} UpperCAmelCase : Dict[Optional[str], str] = {} UpperCAmelCase : Dict[Optional[str], Exception] = {} def _A ( SCREAMING_SNAKE_CASE : type , SCREAMING_SNAKE_CASE : Optional[str] , SCREAMING_SNAKE_CASE : Optional[List[str]] = None , ): """simple docstring""" a__ : Optional[int] =aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( f'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})''' ) a__ : Tuple =formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( f'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})''' ) a__ : int =format_type def _A ( SCREAMING_SNAKE_CASE : Exception , SCREAMING_SNAKE_CASE : Optional[str] , SCREAMING_SNAKE_CASE : Optional[List[str]] = None ): """simple docstring""" a__ : Tuple =aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): a__ : str =unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=["""python"""]) _register_formatter(ArrowFormatter, """arrow""", aliases=["""pa""", """pyarrow"""]) _register_formatter(NumpyFormatter, """numpy""", aliases=["""np"""]) _register_formatter(PandasFormatter, """pandas""", aliases=["""pd"""]) _register_formatter(CustomFormatter, """custom""") if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, """torch""", aliases=["""pt""", """pytorch"""]) else: UpperCAmelCase : int = ValueError("""PyTorch needs to be installed to be able to return PyTorch tensors.""") _register_unavailable_formatter(_torch_error, """torch""", aliases=["""pt""", """pytorch"""]) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, """tensorflow""", aliases=["""tf"""]) else: UpperCAmelCase : Dict = ValueError("""Tensorflow needs to be installed to be able to return Tensorflow tensors.""") _register_unavailable_formatter(_tf_error, """tensorflow""", aliases=["""tf"""]) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, """jax""", aliases=[]) else: UpperCAmelCase : List[Any] = ValueError("""JAX needs to be installed to be able to return JAX arrays.""") _register_unavailable_formatter(_jax_error, """jax""", aliases=[]) def _A ( SCREAMING_SNAKE_CASE : Optional[str] ): """simple docstring""" if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def _A ( SCREAMING_SNAKE_CASE : Optional[str] , **SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" a__ : Optional[Any] =get_format_type_from_alias(SCREAMING_SNAKE_CASE ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**SCREAMING_SNAKE_CASE ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( f'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got \'{format_type}\'''' )
95
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ = 1_00_00_00 ) -> int: __lowerCamelCase = set(range(3 , UpperCamelCase__ , 2 ) ) primes.add(2 ) for p in range(3 , UpperCamelCase__ , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , UpperCamelCase__ , UpperCamelCase__ ) ) ) __lowerCamelCase = [float(UpperCamelCase__ ) for n in range(limit + 1 )] for p in primes: for n in range(UpperCamelCase__ , limit + 1 , UpperCamelCase__ ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(f'{solution() = }')
67
0
"""simple docstring""" import numpy as np import qiskit def _snake_case ( lowercase__ = 8 , lowercase__ = None ): _lowerCamelCase : str = np.random.default_rng(seed=lowercase__ ) # Roughly 25% of the qubits will contribute to the key. # So we take more than we need. _lowerCamelCase : List[str] = 6 * key_len # Measurement basis for Alice's qubits. _lowerCamelCase : int = rng.integers(2 , size=lowercase__ ) # The set of states Alice will prepare. _lowerCamelCase : str = rng.integers(2 , size=lowercase__ ) # Measurement basis for Bob's qubits. _lowerCamelCase : str = rng.integers(2 , size=lowercase__ ) # Quantum Circuit to simulate BB84 _lowerCamelCase : Dict = qiskit.QuantumCircuit(lowercase__ , name='BB84' ) # Alice prepares her qubits according to rules above. for index, _ in enumerate(lowercase__ ): if alice_state[index] == 1: bbaa_circ.x(lowercase__ ) if alice_basis[index] == 1: bbaa_circ.h(lowercase__ ) bbaa_circ.barrier() # Bob measures the received qubits according to rules above. for index, _ in enumerate(lowercase__ ): if bob_basis[index] == 1: bbaa_circ.h(lowercase__ ) bbaa_circ.barrier() bbaa_circ.measure_all() # Simulate the quantum circuit. _lowerCamelCase : List[str] = qiskit.Aer.get_backend('aer_simulator' ) # We only need to run one shot because the key is unique. # Multiple shots will produce the same key. _lowerCamelCase : List[Any] = qiskit.execute(lowercase__ , lowercase__ , shots=1 , seed_simulator=lowercase__ ) # Returns the result of measurement. _lowerCamelCase : Optional[Any] = job.result().get_counts(lowercase__ ).most_frequent() # Extracting the generated key from the simulation results. # Only keep measurement results where Alice and Bob chose the same basis. _lowerCamelCase : Optional[int] = ''.join( [ result_bit for alice_basis_bit, bob_basis_bit, result_bit in zip( lowercase__ , lowercase__ , lowercase__ ) if alice_basis_bit == bob_basis_bit ] ) # Get final key. Pad with 0 if too short, otherwise truncate. _lowerCamelCase : Union[str, Any] = gen_key[:key_len] if len(lowercase__ ) >= key_len else gen_key.ljust(lowercase__ , '0' ) return key if __name__ == "__main__": print(F"The generated key is : {bbaa(8, seed=0)}") from doctest import testmod testmod()
96
'''simple docstring''' 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 a__ : def __init__( self : Union[str, Any] , a : Union[str, Any] , a : Tuple=13 , a : Optional[Any]=7 , a : List[Any]=True , a : Optional[Any]=True , a : Any=True , a : Union[str, Any]=99 , a : Any=32 , a : int=5 , a : Optional[int]=4 , a : Union[str, Any]=37 , a : Optional[Any]="gelu" , a : Union[str, Any]=0.1 , a : Any=0.1 , a : Optional[int]=5_12 , a : int=16 , a : Optional[Any]=2 , a : Union[str, Any]=0.02 , a : Any=3 , a : Dict=4 , a : Any=None , ): """simple docstring""" __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = self.vocab_size - 1 def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __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 = 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 , ) __lowerCamelCase = 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 : Union[str, Any] , a : Dict , a : List[str] , a : Tuple , a : List[Any] , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModel(config=a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , head_mask=a ) __lowerCamelCase = model(a , token_type_ids=a ) __lowerCamelCase = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : Union[str, Any] , a : Dict , a : Union[str, Any] , a : Tuple , *a : Union[str, Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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[int] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : Optional[Any] , *a : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTDoubleHeadsModel(a ) model.to(a ) model.eval() __lowerCamelCase = model(a , token_type_ids=a , labels=a ) 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 : List[str] , a : int , a : Dict , a : Optional[Any] , a : str , *a : int ): """simple docstring""" __lowerCamelCase = self.num_labels __lowerCamelCase = OpenAIGPTForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """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, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class a__ ( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : List[str] =( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCamelCase : str =( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCamelCase : Optional[int] =( { "feature-extraction": OpenAIGPTModel, "text-classification": OpenAIGPTForSequenceClassification, "text-generation": OpenAIGPTLMHeadModel, "zero-shot": OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : Tuple , a : Optional[int] , a : int , a : str , a : Any ): """simple docstring""" 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 : Optional[int] , a : int , a : Optional[int] , a : str=False ): """simple docstring""" __lowerCamelCase = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=a , ) __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = inputs_dict['''labels'''] __lowerCamelCase = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=a , ) __lowerCamelCase = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" __lowerCamelCase = OpenAIGPTModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=a , n_embd=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*a ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = OpenAIGPTModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class a__ ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(a ) __lowerCamelCase = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=a ) # the president is __lowerCamelCase = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the __lowerCamelCase = model.generate(a , do_sample=a ) self.assertListEqual(output_ids[0].tolist() , a )
67
0
'''simple docstring''' from __future__ import annotations from collections.abc import Generator def a ( ) -> Generator[int, None, None]: '''simple docstring''' UpperCamelCase__ :dict[int, int] = {} UpperCamelCase__ :Tuple = 2 while True: UpperCamelCase__ :str = factor_map.pop(__a , __a ) if factor: UpperCamelCase__ :List[str] = factor + prime while x in factor_map: x += factor UpperCamelCase__ :Optional[Any] = factor else: UpperCamelCase__ :List[str] = prime yield prime prime += 1 def a ( __a = 1e10 ) -> int: '''simple docstring''' UpperCamelCase__ :Union[str, Any] = sieve() UpperCamelCase__ :str = 1 while True: UpperCamelCase__ :Optional[Any] = next(__a ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(__a ) n += 2 if __name__ == "__main__": print(solution())
97
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__ ( UpperCAmelCase__ ): lowerCamelCase : Optional[int] =["image_processor", "tokenizer"] lowerCamelCase : Union[str, Any] ="LayoutLMv2ImageProcessor" lowerCamelCase : int =("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Optional[int] , a : Any=None , a : Any=None , **a : Union[str, Any] ): """simple docstring""" if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , a , ) __lowerCamelCase = kwargs.pop('''feature_extractor''' ) __lowerCamelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(a , a ) def __call__( self : Tuple , a : Optional[int] , a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , a : Union[List[List[int]], List[List[List[int]]]] = None , a : Optional[Union[List[int], List[List[int]]]] = None , a : bool = True , a : Union[bool, str, PaddingStrategy] = False , a : Union[bool, str, TruncationStrategy] = None , a : Optional[int] = None , a : int = 0 , a : Optional[int] = None , a : Optional[bool] = None , a : Optional[bool] = None , a : bool = False , a : bool = False , a : bool = False , a : bool = False , a : bool = True , a : Optional[Union[str, TensorType]] = None , **a : Tuple , ): """simple docstring""" if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor __lowerCamelCase = self.image_processor(images=a , return_tensors=a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(a , a ): __lowerCamelCase = [text] # add batch dimension (as the image processor always adds a batch dimension) __lowerCamelCase = features['''words'''] __lowerCamelCase = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel values __lowerCamelCase = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: __lowerCamelCase = self.get_overflowing_images(a , encoded_inputs['''overflow_to_sample_mapping'''] ) __lowerCamelCase = images return encoded_inputs def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : Optional[Any] , a : str ): """simple docstring""" __lowerCamelCase = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(a ) != len(a ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' f""" {len(a )} and {len(a )}""" ) return images_with_overflow def SCREAMING_SNAKE_CASE__ ( self : List[str] , *a : Optional[Any] , **a : Union[str, Any] ): """simple docstring""" return self.tokenizer.batch_decode(*a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , *a : Union[str, Any] , **a : Tuple ): """simple docstring""" return self.tokenizer.decode(*a , **a ) @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return ["input_ids", "bbox", "attention_mask", "image"] @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , a , ) return self.image_processor_class @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , a , ) return self.image_processor
67
0
"""simple docstring""" import random from typing import Any def a_ ( lowerCamelCase ): for _ in range(len(lowerCamelCase ) ): UpperCAmelCase__ = random.randint(0 , len(lowerCamelCase ) - 1 ) UpperCAmelCase__ = random.randint(0 , len(lowerCamelCase ) - 1 ) UpperCAmelCase__ , UpperCAmelCase__ = data[b], data[a] return data if __name__ == "__main__": lowerCAmelCase__ : Dict = [0, 1, 2, 3, 4, 5, 6, 7] lowerCAmelCase__ : str = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
98
'''simple docstring''' import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging __UpperCAmelCase =logging.get_logger(__name__) class a__ ( UpperCAmelCase__ ): def __init__( self : Optional[Any] , a : Union[List[ControlNetModel], Tuple[ControlNetModel]] ): """simple docstring""" super().__init__() __lowerCamelCase = nn.ModuleList(a ) def SCREAMING_SNAKE_CASE__ ( self : Any , a : torch.FloatTensor , a : Union[torch.Tensor, float, int] , a : torch.Tensor , a : List[torch.tensor] , a : List[float] , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[torch.Tensor] = None , a : Optional[Dict[str, Any]] = None , a : bool = False , a : bool = True , ): """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a , a , self.nets ) ): __lowerCamelCase , __lowerCamelCase = controlnet( a , a , a , a , a , a , a , a , a , a , a , ) # merge samples if i == 0: __lowerCamelCase , __lowerCamelCase = down_samples, mid_sample else: __lowerCamelCase = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a , a ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def SCREAMING_SNAKE_CASE__ ( self : Any , a : Union[str, os.PathLike] , a : bool = True , a : Callable = None , a : bool = False , a : Optional[str] = None , ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = save_directory for controlnet in self.nets: controlnet.save_pretrained( a , is_main_process=a , save_function=a , safe_serialization=a , variant=a , ) idx += 1 __lowerCamelCase = model_path_to_save + f"""_{idx}""" @classmethod def SCREAMING_SNAKE_CASE__ ( cls : List[str] , a : Optional[Union[str, os.PathLike]] , **a : Optional[Any] ): """simple docstring""" __lowerCamelCase = 0 __lowerCamelCase = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... __lowerCamelCase = pretrained_model_path while os.path.isdir(a ): __lowerCamelCase = ControlNetModel.from_pretrained(a , **a ) controlnets.append(a ) idx += 1 __lowerCamelCase = pretrained_model_path + f"""_{idx}""" logger.info(f"""{len(a )} controlnets loaded from {pretrained_model_path}.""" ) if len(a ) == 0: raise ValueError( f"""No ControlNets found under {os.path.dirname(a )}. Expected at least {pretrained_model_path + '_0'}.""" ) return cls(a )
67
0
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def A_ ( A__ ) -> List[str]: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def A_ ( A__ ) -> Tuple: a__ : Dict = create_tensor(A__ ) a__ : Tuple = gather(A__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def A_ ( A__ ) -> Any: a__ : Tuple = [state.process_index] a__ : Union[str, Any] = gather_object(A__ ) assert len(A__ ) == state.num_processes, F'{gathered_obj}, {len(A__ )} != {state.num_processes}' assert gathered_obj == list(range(state.num_processes ) ), F'{gathered_obj} != {list(range(state.num_processes ) )}' def A_ ( A__ ) -> Dict: a__ : List[Any] = create_tensor(A__ ) a__ : Optional[int] = broadcast(A__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def A_ ( A__ ) -> List[str]: # We need to pad the tensor with one more element if we are the main process # to ensure that we can pad if state.is_main_process: a__ : str = torch.arange(state.num_processes + 1 ).to(state.device ) else: a__ : Optional[int] = torch.arange(state.num_processes ).to(state.device ) a__ : Optional[Any] = pad_across_processes(A__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def A_ ( A__ ) -> List[Any]: # For now runs on only two processes if state.num_processes != 2: return a__ : Optional[Any] = create_tensor(A__ ) a__ : str = reduce(A__ , 'sum' ) a__ : Any = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(A__ , A__ ), F'{reduced_tensor} != {truth_tensor}' def A_ ( A__ ) -> Dict: # For now runs on only two processes if state.num_processes != 2: return a__ : int = create_tensor(A__ ) a__ : Union[str, Any] = reduce(A__ , 'mean' ) a__ : Any = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(A__ , A__ ), F'{reduced_tensor} != {truth_tensor}' def A_ ( A__ ) -> List[Any]: # For xla_spawn (TPUs) main() def A_ ( ) -> int: a__ : List[str] = PartialState() state.print(F'State: {state}' ) state.print('testing gather' ) test_gather(A__ ) state.print('testing gather_object' ) test_gather_object(A__ ) state.print('testing broadcast' ) test_broadcast(A__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(A__ ) state.print('testing reduce_sum' ) test_reduce_sum(A__ ) state.print('testing reduce_mean' ) test_reduce_mean(A__ ) if __name__ == "__main__": main()
99
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING __UpperCAmelCase =logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase__ ) class a__ ( UpperCAmelCase__ ): def __init__( self : List[str] , *a : Union[str, Any] , **a : Optional[Any] ): """simple docstring""" super().__init__(*a , **a ) requires_backends(self , '''vision''' ) self.check_model_type(a ) def __call__( self : Any , a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **a : Optional[int] ): """simple docstring""" return super().__call__(a , **a ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , **a : Any ): """simple docstring""" return {}, {}, {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] , a : List[str] ): """simple docstring""" __lowerCamelCase = load_image(a ) __lowerCamelCase = image.size __lowerCamelCase = self.image_processor(images=a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE__ ( self : int , a : Optional[Any] ): """simple docstring""" __lowerCamelCase = self.model(**a ) return model_outputs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , a : Any ): """simple docstring""" __lowerCamelCase = model_outputs.predicted_depth __lowerCamelCase = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode='''bicubic''' , align_corners=a ) __lowerCamelCase = prediction.squeeze().cpu().numpy() __lowerCamelCase = (output * 2_55 / np.max(a )).astype('''uint8''' ) __lowerCamelCase = Image.fromarray(a ) __lowerCamelCase = {} __lowerCamelCase = predicted_depth __lowerCamelCase = depth return output_dict
67
0
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class SCREAMING_SNAKE_CASE_ ( __a ): """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_2 , lowerCAmelCase__=5 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__="None" , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , ): __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = relative_attention __SCREAMING_SNAKE_CASE = position_biased_input __SCREAMING_SNAKE_CASE = pos_att_type __SCREAMING_SNAKE_CASE = scope def snake_case_ ( self): __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_ ( self): return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.get_config() __SCREAMING_SNAKE_CASE = 3_0_0 return config def snake_case_ ( self , lowerCAmelCase__): self.parent.assertListEqual(list(result.loss.size()) , []) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaModel(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__)[0] __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , token_type_ids=lowerCAmelCase__)[0] __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__)[0] self.parent.assertListEqual(list(sequence_output.size()) , [self.batch_size, self.seq_length, self.hidden_size]) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaForMaskedLM(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_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 snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForSequenceClassification(lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__) self.parent.assertListEqual(list(result.logits.size()) , [self.batch_size, self.num_labels]) self.check_loss_output(lowerCAmelCase__) def snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DebertaForTokenClassification(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_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 snake_case_ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = DebertaForQuestionAnswering(config=lowerCAmelCase__) model.to(lowerCAmelCase__) model.eval() __SCREAMING_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 snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) ,( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( __a , __a , unittest.TestCase ): """simple docstring""" __lowercase : Dict = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) __lowercase : Any = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) __lowercase : int = True __lowercase : Optional[int] = False __lowercase : str = False __lowercase : Tuple = False __lowercase : Optional[int] = False def snake_case_ ( self): __SCREAMING_SNAKE_CASE = DebertaModelTester(self) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=3_7) def snake_case_ ( self): self.config_tester.run_common_tests() def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*lowerCAmelCase__) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*lowerCAmelCase__) @slow def snake_case_ ( self): for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained(lowerCAmelCase__) self.assertIsNotNone(lowerCAmelCase__) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason="""Model not available yet""") def snake_case_ ( self): pass @slow def snake_case_ ( self): __SCREAMING_SNAKE_CASE = DebertaModel.from_pretrained("""microsoft/deberta-base""") __SCREAMING_SNAKE_CASE = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__)[0] # compare the actual values for a slice. __SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.59_86, -0.80_55, -0.84_62], [1.44_84, -0.93_48, -0.80_59], [0.31_23, 0.00_32, -1.41_31]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowerCAmelCase__ , atol=1E-4) , f"{output[:, 1:4, 1:4]}")
100
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0