code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Any = { '''facebook/nllb-moe-54B''': '''https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json''', } class snake_case__ ( __lowerCAmelCase ): A__ = '''nllb-moe''' A__ = ['''past_key_values'''] A__ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : int , __a : Union[str, Any]=128112 , __a : Union[str, Any]=1024 , __a : Optional[Any]=12 , __a : List[Any]=4096 , __a : str=16 , __a : Dict=12 , __a : Optional[int]=4096 , __a : Union[str, Any]=16 , __a : int=0.0_5 , __a : Dict=0.0_5 , __a : Union[str, Any]=True , __a : List[str]=True , __a : List[Any]="relu" , __a : List[str]=1024 , __a : Tuple=0.1 , __a : int=0.1 , __a : Tuple=0.0 , __a : List[Any]=0.0_2 , __a : str=2 , __a : Union[str, Any]=True , __a : Optional[Any]=False , __a : Any="float32" , __a : Any=False , __a : str=128 , __a : Optional[Any]=64 , __a : Optional[int]=4 , __a : List[Any]=4 , __a : Union[str, Any]=0.0_0_1 , __a : Dict=0.0_0_1 , __a : Any="all" , __a : Optional[int]=False , __a : Tuple=False , __a : List[Any]=1.0 , __a : Any=0.2 , __a : Optional[Any]=1 , __a : Tuple=0 , __a : str=2 , __a : Dict=False , **__a : Optional[Any] , ) -> List[Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : Any = max_position_embeddings __snake_case : List[str] = d_model __snake_case : Optional[Any] = encoder_ffn_dim __snake_case : Any = encoder_layers __snake_case : List[str] = encoder_attention_heads __snake_case : int = decoder_ffn_dim __snake_case : Union[str, Any] = decoder_layers __snake_case : Union[str, Any] = decoder_attention_heads __snake_case : Tuple = dropout __snake_case : Any = attention_dropout __snake_case : List[str] = activation_dropout __snake_case : str = activation_function __snake_case : int = init_std __snake_case : int = encoder_layerdrop __snake_case : int = decoder_layerdrop __snake_case : Dict = use_cache __snake_case : Dict = encoder_layers __snake_case : Dict = scale_embedding # scale factor will be sqrt(d_model) if True __snake_case : Union[str, Any] = router_z_loss_coef __snake_case : int = router_aux_loss_coef __snake_case : Optional[int] = decoder_sparse_step __snake_case : Optional[Any] = encoder_sparse_step __snake_case : Optional[int] = num_experts __snake_case : List[str] = expert_capacity __snake_case : str = router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}''' ) __snake_case : Tuple = router_dtype __snake_case : Union[str, Any] = router_ignore_padding_tokens __snake_case : Union[str, Any] = batch_prioritized_routing __snake_case : Tuple = second_expert_policy __snake_case : str = normalize_router_prob_before_dropping __snake_case : str = moe_eval_capacity_token_fraction __snake_case : List[str] = moe_token_dropout __snake_case : List[Any] = output_router_logits super().__init__( pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , is_encoder_decoder=lowerCAmelCase_ , decoder_start_token_id=lowerCAmelCase_ , **lowerCAmelCase_ , )
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> Tuple: if initial_intensity < 0: raise ValueError('The value of intensity cannot be negative' ) # handling of negative values of initial intensity if angle < 0 or angle > 3_60: raise ValueError('In Malus Law, the angle is in the range 0-360 degrees' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(lowerCAmelCase__ ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name='''malus_law''')
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
0
'''simple docstring''' from PIL import Image def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Union[str, Any] ) -> Image: __snake_case : Any = (2_59 * (level + 2_55)) / (2_55 * (2_59 - level)) def contrast(_UpperCAmelCase : Optional[int] ) -> int: return int(1_28 + factor * (c - 1_28) ) return img.point(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": # Load image with Image.open('''image_data/lena.jpg''') as img: # Change contrast to 170 A__ : Optional[Any] = change_contrast(img, 1_7_0) cont_img.save('''image_data/lena_high_contrast.png''', format='''png''')
366
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' import argparse import collections import json import os import re import string import sys import numpy as np A__ : str = re.compile(R'''\b(a|an|the)\b''', re.UNICODE) A__ : str = None def a_ ( ) -> Tuple: __snake_case : int = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.' ) parser.add_argument('data_file' ,metavar='data.json' ,help='Input data JSON file.' ) parser.add_argument('pred_file' ,metavar='pred.json' ,help='Model predictions.' ) parser.add_argument( '--out-file' ,'-o' ,metavar='eval.json' ,help='Write accuracy metrics to file (default is stdout).' ) parser.add_argument( '--na-prob-file' ,'-n' ,metavar='na_prob.json' ,help='Model estimates of probability of no answer.' ) parser.add_argument( '--na-prob-thresh' ,'-t' ,type=lowerCamelCase_ ,default=1.0 ,help='Predict "" if no-answer probability exceeds this (default = 1.0).' ,) parser.add_argument( '--out-image-dir' ,'-p' ,metavar='out_images' ,default=lowerCamelCase_ ,help='Save precision-recall curves to directory.' ) parser.add_argument('--verbose' ,'-v' ,action='store_true' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def a_ ( _UpperCAmelCase : List[str] ) -> List[Any]: __snake_case : str = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __snake_case : Optional[Any] = bool(qa['answers']['text'] ) return qid_to_has_ans def a_ ( _UpperCAmelCase : Dict ) -> int: def remove_articles(_UpperCAmelCase : str ): return ARTICLES_REGEX.sub(' ' ,lowerCamelCase_ ) def white_space_fix(_UpperCAmelCase : Tuple ): return " ".join(text.split() ) def remove_punc(_UpperCAmelCase : Any ): __snake_case : Optional[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_UpperCAmelCase : Optional[int] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_ ) ) ) ) def a_ ( _UpperCAmelCase : List[Any] ) -> int: if not s: return [] return normalize_answer(lowerCamelCase_ ).split() def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : List[Any] ) -> str: return int(normalize_answer(lowerCamelCase_ ) == normalize_answer(lowerCamelCase_ ) ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : str ) -> Optional[Any]: __snake_case : List[Any] = get_tokens(lowerCamelCase_ ) __snake_case : Union[str, Any] = get_tokens(lowerCamelCase_ ) __snake_case : Dict = collections.Counter(lowerCamelCase_ ) & collections.Counter(lowerCamelCase_ ) __snake_case : Any = sum(common.values() ) if len(lowerCamelCase_ ) == 0 or len(lowerCamelCase_ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __snake_case : Dict = 1.0 * num_same / len(lowerCamelCase_ ) __snake_case : int = 1.0 * num_same / len(lowerCamelCase_ ) __snake_case : Optional[Any] = (2 * precision * recall) / (precision + recall) return fa def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ) -> List[Any]: __snake_case : Optional[int] = {} __snake_case : Any = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __snake_case : str = qa['id'] __snake_case : Tuple = [t for t in qa['answers']['text'] if normalize_answer(lowerCamelCase_ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __snake_case : str = [''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __snake_case : str = preds[qid] # Take max over all gold answers __snake_case : Dict = max(compute_exact(lowerCamelCase_ ,lowerCamelCase_ ) for a in gold_answers ) __snake_case : Optional[int] = max(compute_fa(lowerCamelCase_ ,lowerCamelCase_ ) for a in gold_answers ) return exact_scores, fa_scores def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ) -> int: __snake_case : Any = {} for qid, s in scores.items(): __snake_case : Union[str, Any] = na_probs[qid] > na_prob_thresh if pred_na: __snake_case : Union[str, Any] = float(not qid_to_has_ans[qid] ) else: __snake_case : Any = s return new_scores def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int=None ) -> Optional[Any]: if not qid_list: __snake_case : List[str] = len(lowerCamelCase_ ) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores.values() ) / total), ('f1', 1_00.0 * sum(fa_scores.values() ) / total), ('total', total), ] ) else: __snake_case : Tuple = len(lowerCamelCase_ ) return collections.OrderedDict( [ ('exact', 1_00.0 * sum(exact_scores[k] for k in qid_list ) / total), ('f1', 1_00.0 * sum(fa_scores[k] for k in qid_list ) / total), ('total', total), ] ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ) -> Optional[int]: for k in new_eval: __snake_case : Optional[int] = new_eval[k] def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : str ) -> Any: plt.step(lowerCamelCase_ ,lowerCamelCase_ ,color='b' ,alpha=0.2 ,where='post' ) plt.fill_between(lowerCamelCase_ ,lowerCamelCase_ ,step='post' ,alpha=0.2 ,color='b' ) plt.xlabel('Recall' ) plt.ylabel('Precision' ) plt.xlim([0.0, 1.0_5] ) plt.ylim([0.0, 1.0_5] ) plt.title(lowerCamelCase_ ) plt.savefig(lowerCamelCase_ ) plt.clf() def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : Union[str, Any]=None ) -> Dict: __snake_case : Dict = sorted(lowerCamelCase_ ,key=lambda _UpperCAmelCase : na_probs[k] ) __snake_case : Tuple = 0.0 __snake_case : int = 1.0 __snake_case : List[str] = 0.0 __snake_case : List[Any] = [1.0] __snake_case : Optional[Any] = [0.0] __snake_case : Union[str, Any] = 0.0 for i, qid in enumerate(lowerCamelCase_ ): if qid_to_has_ans[qid]: true_pos += scores[qid] __snake_case : int = true_pos / float(i + 1 ) __snake_case : Dict = true_pos / float(lowerCamelCase_ ) if i == len(lowerCamelCase_ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(lowerCamelCase_ ) recalls.append(lowerCamelCase_ ) if out_image: plot_pr_curve(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) return {"ap": 1_00.0 * avg_prec} def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any] ) -> int: if out_image_dir and not os.path.exists(lowerCamelCase_ ): os.makedirs(lowerCamelCase_ ) __snake_case : Union[str, Any] = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __snake_case : Tuple = make_precision_recall_eval( lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,out_image=os.path.join(lowerCamelCase_ ,'pr_exact.png' ) ,title='Precision-Recall curve for Exact Match score' ,) __snake_case : int = make_precision_recall_eval( lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,out_image=os.path.join(lowerCamelCase_ ,'pr_f1.png' ) ,title='Precision-Recall curve for F1 score' ,) __snake_case : Any = {k: float(lowerCamelCase_ ) for k, v in qid_to_has_ans.items()} __snake_case : List[str] = make_precision_recall_eval( lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,out_image=os.path.join(lowerCamelCase_ ,'pr_oracle.png' ) ,title='Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)' ,) merge_eval(lowerCamelCase_ ,lowerCamelCase_ ,'pr_exact' ) merge_eval(lowerCamelCase_ ,lowerCamelCase_ ,'pr_f1' ) merge_eval(lowerCamelCase_ ,lowerCamelCase_ ,'pr_oracle' ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Union[str, Any] ) -> Dict: if not qid_list: return __snake_case : Optional[int] = [na_probs[k] for k in qid_list] __snake_case : Dict = np.ones_like(lowerCamelCase_ ) / float(len(lowerCamelCase_ ) ) plt.hist(lowerCamelCase_ ,weights=lowerCamelCase_ ,bins=20 ,range=(0.0, 1.0) ) plt.xlabel('Model probability of no-answer' ) plt.ylabel('Proportion of dataset' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(lowerCamelCase_ ,f'''na_prob_hist_{name}.png''' ) ) plt.clf() def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ) -> Any: __snake_case : List[str] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __snake_case : Dict = num_no_ans __snake_case : List[str] = cur_score __snake_case : Any = 0.0 __snake_case : str = sorted(lowerCamelCase_ ,key=lambda _UpperCAmelCase : na_probs[k] ) for i, qid in enumerate(lowerCamelCase_ ): if qid not in scores: continue if qid_to_has_ans[qid]: __snake_case : int = scores[qid] else: if preds[qid]: __snake_case : str = -1 else: __snake_case : Optional[int] = 0 cur_score += diff if cur_score > best_score: __snake_case : Tuple = cur_score __snake_case : Tuple = na_probs[qid] return 1_00.0 * best_score / len(lowerCamelCase_ ), best_thresh def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int ,_UpperCAmelCase : str ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Union[str, Any] = find_best_thresh(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) __snake_case : Optional[Any] = find_best_thresh(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) __snake_case : Optional[int] = best_exact __snake_case : List[str] = exact_thresh __snake_case : str = best_fa __snake_case : Optional[int] = fa_thresh def a_ ( ) -> List[Any]: with open(OPTS.data_file ) as f: __snake_case : Union[str, Any] = json.load(lowerCamelCase_ ) __snake_case : Optional[int] = dataset_json['data'] with open(OPTS.pred_file ) as f: __snake_case : Tuple = json.load(lowerCamelCase_ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __snake_case : int = json.load(lowerCamelCase_ ) else: __snake_case : int = {k: 0.0 for k in preds} __snake_case : Dict = make_qid_to_has_ans(lowerCamelCase_ ) # maps qid to True/False __snake_case : Dict = [k for k, v in qid_to_has_ans.items() if v] __snake_case : int = [k for k, v in qid_to_has_ans.items() if not v] __snake_case : Dict = get_raw_scores(lowerCamelCase_ ,lowerCamelCase_ ) __snake_case : Tuple = apply_no_ans_threshold(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,OPTS.na_prob_thresh ) __snake_case : List[Any] = apply_no_ans_threshold(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,OPTS.na_prob_thresh ) __snake_case : List[str] = make_eval_dict(lowerCamelCase_ ,lowerCamelCase_ ) if has_ans_qids: __snake_case : Optional[Any] = make_eval_dict(lowerCamelCase_ ,lowerCamelCase_ ,qid_list=lowerCamelCase_ ) merge_eval(lowerCamelCase_ ,lowerCamelCase_ ,'HasAns' ) if no_ans_qids: __snake_case : Optional[int] = make_eval_dict(lowerCamelCase_ ,lowerCamelCase_ ,qid_list=lowerCamelCase_ ) merge_eval(lowerCamelCase_ ,lowerCamelCase_ ,'NoAns' ) if OPTS.na_prob_file: find_all_best_thresh(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,OPTS.out_image_dir ) histogram_na_prob(lowerCamelCase_ ,lowerCamelCase_ ,OPTS.out_image_dir ,'hasAns' ) histogram_na_prob(lowerCamelCase_ ,lowerCamelCase_ ,OPTS.out_image_dir ,'noAns' ) if OPTS.out_file: with open(OPTS.out_file ,'w' ) as f: json.dump(lowerCamelCase_ ,lowerCamelCase_ ) else: print(json.dumps(lowerCamelCase_ ,indent=2 ) ) if __name__ == "__main__": A__ : Optional[int] = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('''Agg''') import matplotlib.pyplot as plt main()
367
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
0
'''simple docstring''' from __future__ import annotations import requests def a_ ( _UpperCAmelCase : str ) -> List[str]: __snake_case : Union[str, Any] = f'''https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty''' return requests.get(__UpperCamelCase ).json() def a_ ( _UpperCAmelCase : int = 10 ) -> Dict: __snake_case : int = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' __snake_case : Tuple = requests.get(__UpperCamelCase ).json()[:max_stories] return [get_hackernews_story(__UpperCamelCase ) for story_id in story_ids] def a_ ( _UpperCAmelCase : int = 10 ) -> List[str]: __snake_case : Any = hackernews_top_stories(__UpperCamelCase ) return "\n".join('* [{title}]({url})'.format(**__UpperCamelCase ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
368
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
0
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class snake_case__ ( _lowerCAmelCase ): A__ = 42 @flax_register_to_config class snake_case__ ( nn.Module , _lowerCAmelCase , _lowerCAmelCase ): A__ = 32 A__ = 4 A__ = 4 A__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) A__ = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") A__ = False A__ = (320, 640, 1_280, 1_280) A__ = 2 A__ = 8 A__ = None A__ = 1_280 A__ = 0.0 A__ = False A__ = jnp.floataa A__ = True A__ = 0 A__ = False def A_ ( self : List[str] , __a : jax.random.KeyArray ) -> Optional[Any]: '''simple docstring''' # init input tensors __snake_case : Tuple = (1, self.in_channels, self.sample_size, self.sample_size) __snake_case : Dict = jnp.zeros(_lowercase , dtype=jnp.floataa ) __snake_case : Any = jnp.ones((1,) , dtype=jnp.intaa ) __snake_case : List[Any] = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __snake_case , __snake_case : Tuple = jax.random.split(_lowercase ) __snake_case : str = {'params': params_rng, 'dropout': dropout_rng} return self.init(_lowercase , _lowercase , _lowercase , _lowercase )["params"] def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.block_out_channels __snake_case : Any = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( 'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.' ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __snake_case : Optional[Any] = self.num_attention_heads or self.attention_head_dim # input __snake_case : int = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __snake_case : Any = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __snake_case : List[Any] = FlaxTimestepEmbedding(_lowercase , dtype=self.dtype ) __snake_case : Optional[int] = self.only_cross_attention if isinstance(_lowercase , _lowercase ): __snake_case : Dict = (only_cross_attention,) * len(self.down_block_types ) if isinstance(_lowercase , _lowercase ): __snake_case : str = (num_attention_heads,) * len(self.down_block_types ) # down __snake_case : Optional[int] = [] __snake_case : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): __snake_case : Dict = output_channel __snake_case : Union[str, Any] = block_out_channels[i] __snake_case : Any = i == len(_lowercase ) - 1 if down_block_type == "CrossAttnDownBlock2D": __snake_case : int = FlaxCrossAttnDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __snake_case : Union[str, Any] = FlaxDownBlockaD( in_channels=_lowercase , out_channels=_lowercase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(_lowercase ) __snake_case : List[Any] = down_blocks # mid __snake_case : List[Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up __snake_case : List[Any] = [] __snake_case : Tuple = list(reversed(_lowercase ) ) __snake_case : List[str] = list(reversed(_lowercase ) ) __snake_case : Optional[Any] = list(reversed(_lowercase ) ) __snake_case : Optional[int] = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): __snake_case : Dict = output_channel __snake_case : str = reversed_block_out_channels[i] __snake_case : str = reversed_block_out_channels[min(i + 1 , len(_lowercase ) - 1 )] __snake_case : Optional[int] = i == len(_lowercase ) - 1 if up_block_type == "CrossAttnUpBlock2D": __snake_case : Union[str, Any] = FlaxCrossAttnUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __snake_case : Union[str, Any] = FlaxUpBlockaD( in_channels=_lowercase , out_channels=_lowercase , prev_output_channel=_lowercase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(_lowercase ) __snake_case : Dict = output_channel __snake_case : List[str] = up_blocks # out __snake_case : Union[str, Any] = nn.GroupNorm(num_groups=32 , epsilon=1e-5 ) __snake_case : List[str] = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self : Optional[int] , __a : List[Any] , __a : Any , __a : Optional[Any] , __a : Optional[Any]=None , __a : List[str]=None , __a : bool = True , __a : bool = False , ) -> int: '''simple docstring''' # 1. time if not isinstance(_lowercase , jnp.ndarray ): __snake_case : Union[str, Any] = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(_lowercase , jnp.ndarray ) and len(timesteps.shape ) == 0: __snake_case : Optional[Any] = timesteps.astype(dtype=jnp.floataa ) __snake_case : Optional[int] = jnp.expand_dims(_lowercase , 0 ) __snake_case : List[str] = self.time_proj(_lowercase ) __snake_case : Optional[Any] = self.time_embedding(_lowercase ) # 2. pre-process __snake_case : Any = jnp.transpose(_lowercase , (0, 2, 3, 1) ) __snake_case : int = self.conv_in(_lowercase ) # 3. down __snake_case : Union[str, Any] = (sample,) for down_block in self.down_blocks: if isinstance(_lowercase , _lowercase ): __snake_case , __snake_case : Union[str, Any] = down_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) else: __snake_case , __snake_case : Dict = down_block(_lowercase , _lowercase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: __snake_case : List[str] = () for down_block_res_sample, down_block_additional_residual in zip( _lowercase , _lowercase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) __snake_case : str = new_down_block_res_samples # 4. mid __snake_case : List[Any] = self.mid_block(_lowercase , _lowercase , _lowercase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: __snake_case : Optional[int] = down_block_res_samples[-(self.layers_per_block + 1) :] __snake_case : Dict = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(_lowercase , _lowercase ): __snake_case : Any = up_block( _lowercase , temb=_lowercase , encoder_hidden_states=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train , ) else: __snake_case : int = up_block(_lowercase , temb=_lowercase , res_hidden_states_tuple=_lowercase , deterministic=not train ) # 6. post-process __snake_case : Union[str, Any] = self.conv_norm_out(_lowercase ) __snake_case : Tuple = nn.silu(_lowercase ) __snake_case : Optional[int] = self.conv_out(_lowercase ) __snake_case : Optional[int] = jnp.transpose(_lowercase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=_lowercase )
369
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
0
'''simple docstring''' import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class snake_case__ ( unittest.TestCase ): def __init__( self : Any , __a : List[Any] , __a : List[str]=2 , __a : List[Any]=56 , __a : int=True , __a : Any=True , __a : Dict=True , __a : List[Any]=True , __a : Optional[Any]=99 , __a : Tuple=32 , __a : str=2 , __a : Any=2 , __a : str=7 , __a : Union[str, Any]="gelu_new" , __a : List[Any]=0.1 , __a : str=0.1 , __a : Tuple=512 , __a : List[str]=16 , __a : Any=2 , __a : int=0.0_2 , __a : Optional[int]=4 , __a : Optional[Any]="block_sparse" , __a : Optional[int]=True , __a : Optional[int]=False , __a : Optional[int]=2 , __a : Optional[int]=3 , ): '''simple docstring''' __snake_case : Any = parent __snake_case : Union[str, Any] = batch_size __snake_case : List[str] = seq_length __snake_case : Optional[int] = is_training __snake_case : int = use_attention_mask __snake_case : Union[str, Any] = use_token_type_ids __snake_case : Optional[int] = use_labels __snake_case : Union[str, Any] = vocab_size __snake_case : List[Any] = hidden_size __snake_case : int = num_hidden_layers __snake_case : int = num_attention_heads __snake_case : Union[str, Any] = intermediate_size __snake_case : Tuple = hidden_act __snake_case : Union[str, Any] = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : Any = max_position_embeddings __snake_case : Tuple = type_vocab_size __snake_case : Tuple = type_sequence_label_size __snake_case : Optional[int] = initializer_range __snake_case : Tuple = num_choices __snake_case : Union[str, Any] = rescale_embeddings __snake_case : Optional[Any] = attention_type __snake_case : List[Any] = use_bias __snake_case : List[Any] = block_size __snake_case : Dict = num_random_blocks def A_ ( self : str ): '''simple docstring''' __snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Optional[int] = None if self.use_attention_mask: __snake_case : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : str = None if self.use_token_type_ids: __snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : List[Any] = BigBirdConfig( 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=__lowerCAmelCase , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def A_ ( self : Optional[Any] ): '''simple docstring''' __snake_case : Dict = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case : Dict = config_and_inputs __snake_case : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask, } return config, inputs_dict @require_flax class snake_case__ ( _a , unittest.TestCase ): A__ = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) A__ = False A__ = False def A_ ( self : List[Any] ): '''simple docstring''' __snake_case : Any = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A_ ( self : Optional[Any] ): '''simple docstring''' super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A_ ( self : Optional[Any] ): '''simple docstring''' super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A_ ( self : List[str] ): '''simple docstring''' super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A_ ( self : Optional[Any] ): '''simple docstring''' super().test_hidden_states_output() @slow def A_ ( self : Any ): '''simple docstring''' for model_class_name in self.all_model_classes: __snake_case : Optional[Any] = model_class_name.from_pretrained('google/bigbird-roberta-base' ) self.assertIsNotNone(__lowerCAmelCase ) def A_ ( self : Optional[Any] ): '''simple docstring''' if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def A_ ( self : Optional[Any] ): '''simple docstring''' __snake_case , __snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __snake_case : Optional[int] = self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) __snake_case : Tuple = model_class(__lowerCAmelCase ) @jax.jit def model_jitted(__a : List[Any] , __a : Optional[int]=None , **__a : List[Any] ): return model(input_ids=__lowerCAmelCase , attention_mask=__lowerCAmelCase , **__lowerCAmelCase ) with self.subTest('JIT Enabled' ): __snake_case : Optional[int] = model_jitted(**__lowerCAmelCase ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): __snake_case : Optional[Any] = model_jitted(**__lowerCAmelCase ).to_tuple() self.assertEqual(len(__lowerCAmelCase ) , len(__lowerCAmelCase ) ) for jitted_output, output in zip(__lowerCAmelCase , __lowerCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) def A_ ( self : str , __a : Any , __a : Dict , __a : Optional[int] , __a : List[Any]=1e-5 , __a : List[Any]="outputs" , __a : Tuple=None ): '''simple docstring''' # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version, # an effort was done to return `attention_probs` (yet to be verified). if name.startswith('outputs.attentions' ): return else: super().check_pt_flax_outputs(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
370
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class snake_case__ ( unittest.TestCase ): def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' __snake_case : Dict = [[1, 2, 4], [1, 2, 3, 4]] __snake_case : str = DisjunctiveConstraint(_A ) self.assertTrue(isinstance(dc.token_ids , _A ) ) with self.assertRaises(_A ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(_A ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : List[Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(_A ): DisjunctiveConstraint(_A ) # fails here def A_ ( self : Tuple ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = [[1, 2, 3], [1, 2, 4]] __snake_case : int = DisjunctiveConstraint(_A ) __snake_case : List[Any] = dc.update(1 ) __snake_case : int = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __snake_case : Tuple = dc.update(2 ) __snake_case : int = stepped is True and completed is False and reset is False self.assertTrue(_A ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __snake_case : Optional[Any] = dc.update(3 ) __snake_case : List[Any] = stepped is True and completed is True and reset is False self.assertTrue(_A ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def A_ ( self : List[str] ) -> List[Any]: '''simple docstring''' __snake_case : str = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __snake_case : List[Any] = DisjunctiveConstraint(_A ) __snake_case : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __snake_case : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __snake_case : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __snake_case : List[str] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __snake_case : Dict = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __snake_case : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __snake_case : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Dict = { "configuration_mctct": ["MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MCTCTConfig"], "feature_extraction_mctct": ["MCTCTFeatureExtractor"], "processing_mctct": ["MCTCTProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ "MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST", "MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
'''simple docstring''' from collections.abc import Sequence def a_ ( _UpperCAmelCase : Sequence[float] ,_UpperCAmelCase : float ) -> Any: return sum(c * (x**i) for i, c in enumerate(lowerCAmelCase__ ) ) def a_ ( _UpperCAmelCase : Sequence[float] ,_UpperCAmelCase : float ) -> Any: __snake_case : str = 0.0 for coeff in reversed(lowerCAmelCase__ ): __snake_case : Dict = result * x + coeff return result if __name__ == "__main__": A__ : List[Any] = (0.0, 0.0, 5.0, 9.3, 7.0) A__ : List[Any] = 10.0 print(evaluate_poly(poly, x)) print(horner(poly, x))
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Dict , __a : VQModel , __a : UNetaDModel , __a : DDIMScheduler ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=__a , unet=__a , scheduler=__a ) @torch.no_grad() def __call__( self : Tuple , __a : int = 1 , __a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __a : float = 0.0 , __a : int = 50 , __a : Optional[str] = "pil" , __a : bool = True , **__a : Union[str, Any] , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' __snake_case : List[str] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=__a , ) __snake_case : int = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __snake_case : Tuple = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(__a ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature __snake_case : Tuple = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : Any = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(self.scheduler.timesteps ): __snake_case : Union[str, Any] = self.scheduler.scale_model_input(__a , __a ) # predict the noise residual __snake_case : Any = self.unet(__a , __a ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Optional[Any] = self.scheduler.step(__a , __a , __a , **__a ).prev_sample # decode the image latents with the VAE __snake_case : List[Any] = self.vqvae.decode(__a ).sample __snake_case : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) __snake_case : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : str = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
352
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
0
'''simple docstring''' from __future__ import annotations from collections.abc import Callable def a_ ( _UpperCAmelCase : Callable[[int | float], int | float] ,_UpperCAmelCase : int | float ,_UpperCAmelCase : int | float ,_UpperCAmelCase : int = 1_00 ,) -> Union[str, Any]: __snake_case : Union[str, Any] = x_start __snake_case : List[Any] = fnc(_UpperCAmelCase ) __snake_case : List[str] = 0.0 for _ in range(_UpperCAmelCase ): # Approximates small segments of curve as linear and solve # for trapezoidal area __snake_case : Optional[int] = (x_end - x_start) / steps + xa __snake_case : List[Any] = fnc(_UpperCAmelCase ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step __snake_case : str = xa __snake_case : Optional[Any] = fxa return area if __name__ == "__main__": def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Union[str, Any]: return x**3 + x**2 print('''f(x) = x^3 + x^2''') print('''The area between the curve, x = -5, x = 5 and the x axis is:''') A__ : Union[str, Any] = 1_0 while i <= 1_0_0_0_0_0: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 1_0
353
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
0
'''simple docstring''' A__ : Dict = 9.8_06_65 def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple = g ) -> Optional[int]: if fluid_density <= 0: raise ValueError('Impossible fluid density' ) if volume < 0: raise ValueError('Impossible Object volume' ) if gravity <= 0: raise ValueError('Impossible Gravity' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
354
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
0
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. A__ : str = abspath(join(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 a_ ( _UpperCAmelCase : List[Any] ) -> List[str]: config.addinivalue_line( 'markers' ,'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested' ) config.addinivalue_line( 'markers' ,'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested' ) config.addinivalue_line('markers' ,'is_pipeline_test: mark test to run only when pipelines are tested' ) config.addinivalue_line('markers' ,'is_staging_test: mark test to run only in the staging environment' ) config.addinivalue_line('markers' ,'accelerate_tests: mark test that require accelerate' ) config.addinivalue_line('markers' ,'tool_tests: mark the tool tests that are run on their specific schedule' ) def a_ ( _UpperCAmelCase : Any ) -> Optional[int]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowerCamelCase_ ) def a_ ( _UpperCAmelCase : List[str] ) -> List[Any]: from transformers.testing_utils import pytest_terminal_summary_main __snake_case : str = terminalreporter.config.getoption('--make-reports' ) if make_reports: pytest_terminal_summary_main(lowerCamelCase_ ,id=lowerCamelCase_ ) def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any] ) -> Optional[int]: if exitstatus == 5: __snake_case : Optional[Any] = 0 # Doctest custom flag to ignore output. A__ : List[Any] = doctest.register_optionflag('''IGNORE_RESULT''') A__ : Tuple = doctest.OutputChecker class snake_case__ ( lowerCamelCase__ ): def A_ ( self : List[Any] , __a : List[Any] , __a : List[Any] , __a : Dict ) -> Optional[Any]: '''simple docstring''' if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) A__ : int = CustomOutputChecker A__ : Union[str, Any] = HfDoctestModule A__ : Dict = HfDocTestParser
355
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int ) -> List[str]: __snake_case : Optional[Any] = 0 __snake_case : Any = len(UpperCAmelCase_ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __snake_case : Optional[Any] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCAmelCase_ ): return None __snake_case : int = sorted_collection[point] if current_item == item: return point else: if point < left: __snake_case : Union[str, Any] = left __snake_case : List[str] = point elif point > right: __snake_case : int = right __snake_case : int = point else: if item < current_item: __snake_case : str = point - 1 else: __snake_case : Any = point + 1 return None def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : int ,_UpperCAmelCase : Dict ) -> Any: if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __snake_case : int = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(UpperCAmelCase_ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) elif point > right: return interpolation_search_by_recursion(UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( UpperCAmelCase_ ,UpperCAmelCase_ ,UpperCAmelCase_ ,point - 1 ) else: return interpolation_search_by_recursion( UpperCAmelCase_ ,UpperCAmelCase_ ,point + 1 ,UpperCAmelCase_ ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: if collection != sorted(UpperCAmelCase_ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys A__ : Any = 0 if debug == 1: A__ : List[Any] = [1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('''Sequence must be ascending sorted to apply interpolation search''') A__ : Tuple = 6_7 A__ : Optional[Any] = interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print('''Not found''')
356
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int A__ : Union[str, Any] = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class snake_case__ ( datasets.BuilderConfig ): A__ = None def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ,) -> List[str]: import pyspark def generate_fn(): __snake_case : int = df.select('*' ,pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: __snake_case : List[Any] = df_with_partition_id.select('*' ).where(f'''part_id = {partition_id}''' ).drop('part_id' ) __snake_case : Optional[int] = partition_df.collect() __snake_case : Any = 0 for row in rows: yield f'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class snake_case__ ( _BaseExamplesIterable ): def __init__( self : List[Any] , __a : "pyspark.sql.DataFrame" , __a : int=None , ) -> Dict: '''simple docstring''' __snake_case : List[str] = df __snake_case : Optional[int] = partition_order or range(self.df.rdd.getNumPartitions() ) __snake_case : List[str] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : str ) -> Tuple: '''simple docstring''' yield from self.generate_examples_fn() def A_ ( self : Tuple , __a : np.random.Generator ) -> Optional[Any]: '''simple docstring''' __snake_case : Optional[Any] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(__snake_case ) return SparkExamplesIterable(self.df , partition_order=__snake_case ) def A_ ( self : int , __a : int , __a : int ) -> Optional[Any]: '''simple docstring''' __snake_case : str = self.split_shard_indices_by_worker(__snake_case , __snake_case ) return SparkExamplesIterable(self.df , partition_order=__snake_case ) @property def A_ ( self : int ) -> int: '''simple docstring''' return len(self.partition_order ) class snake_case__ ( datasets.DatasetBuilder ): A__ = SparkConfig def __init__( self : Tuple , __a : "pyspark.sql.DataFrame" , __a : str = None , __a : str = None , **__a : Tuple , ) -> Optional[Any]: '''simple docstring''' import pyspark __snake_case : Tuple = pyspark.sql.SparkSession.builder.getOrCreate() __snake_case : Union[str, Any] = df __snake_case : Optional[int] = working_dir super().__init__( cache_dir=__snake_case , config_name=str(self.df.semanticHash() ) , **__snake_case , ) def A_ ( self : Dict ) -> Any: '''simple docstring''' # Returns the path of the created file. def create_cache_and_write_probe(__a : Tuple ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=__snake_case ) __snake_case : Dict = os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(__snake_case , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: __snake_case : List[Any] = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(__snake_case ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def A_ ( self : Optional[Any] ) -> int: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def A_ ( self : Tuple , __a : datasets.download.download_manager.DownloadManager ) -> Any: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def A_ ( self : Optional[int] , __a : List[str] ) -> Any: '''simple docstring''' import pyspark def get_arrow_batch_size(__a : List[str] ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) __snake_case : List[Any] = self.df.count() __snake_case : Any = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. __snake_case : str = ( self.df.limit(__snake_case ) .repartition(1 ) .mapInArrow(__snake_case , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) __snake_case : Tuple = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. __snake_case : Optional[int] = min(__snake_case , int(approx_total_size / max_shard_size ) ) __snake_case : Dict = self.df.repartition(__snake_case ) def A_ ( self : List[str] , __a : str , __a : str , __a : int , ) -> Any: '''simple docstring''' import pyspark __snake_case : Optional[Any] = ParquetWriter if file_format == 'parquet' else ArrowWriter __snake_case : Any = os.path.join(self._working_dir , os.path.basename(__snake_case ) ) if self._working_dir else fpath __snake_case : Union[str, Any] = file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. __snake_case : Optional[Any] = self.config.features __snake_case : Optional[Any] = self._writer_batch_size __snake_case : List[str] = self._fs.storage_options def write_arrow(__a : str ): # Within the same SparkContext, no two task attempts will share the same attempt ID. __snake_case : Any = pyspark.TaskContext().taskAttemptId() __snake_case : int = next(__snake_case , __snake_case ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) __snake_case : Tuple = 0 __snake_case : Optional[Any] = writer_class( features=__snake_case , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=__snake_case , storage_options=__snake_case , embed_local_files=__snake_case , ) __snake_case : int = pa.Table.from_batches([first_batch] ) writer.write_table(__snake_case ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: __snake_case : int = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 __snake_case : Dict = writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , writer_batch_size=__snake_case , storage_options=__snake_case , embed_local_files=__snake_case , ) __snake_case : Dict = pa.Table.from_batches([batch] ) writer.write_table(__snake_case ) if writer._num_bytes > 0: __snake_case : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(__snake_case ) ): __snake_case : List[str] = os.path.join(os.path.dirname(__snake_case ) , os.path.basename(__snake_case ) ) shutil.move(__snake_case , __snake_case ) __snake_case : Dict = ( self.df.mapInArrow(__snake_case , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def A_ ( self : Dict , __a : "datasets.SplitGenerator" , __a : str = "arrow" , __a : Optional[Union[str, int]] = None , __a : Optional[int] = None , **__a : Tuple , ) -> List[Any]: '''simple docstring''' self._validate_cache_dir() __snake_case : Optional[int] = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(__snake_case ) __snake_case : Union[str, Any] = not is_remote_filesystem(self._fs ) __snake_case : List[Any] = os.path.join if is_local else posixpath.join __snake_case : Any = '-TTTTT-SSSSS-of-NNNNN' __snake_case : List[str] = f'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' __snake_case : int = path_join(self._output_dir , __snake_case ) __snake_case : List[str] = 0 __snake_case : int = 0 __snake_case : Any = 0 __snake_case : Tuple = [] __snake_case : Any = [] for task_id, content in self._prepare_split_single(__snake_case , __snake_case , __snake_case ): ( __snake_case ) : Any = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(__snake_case ) __snake_case : Union[str, Any] = total_num_examples __snake_case : Dict = total_num_bytes # should rename everything at the end logger.debug(f'''Renaming {total_shards} shards.''' ) if total_shards > 1: __snake_case : str = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. __snake_case : List[str] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( __a : int , __a : int , __a : int , ): rename( __snake_case , fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , f'''{global_shard_id:05d}''' ).replace('NNNNN' , f'''{total_shards:05d}''' ) , ) __snake_case : Tuple = [] __snake_case : str = 0 for i in range(len(__snake_case ) ): __snake_case : Optional[int] = task_id_and_num_shards[i] for shard_id in range(__snake_case ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(__snake_case , len(__snake_case ) ).map(lambda __a : _rename_shard(*__snake_case ) ).collect() else: # don't use any pattern __snake_case : Any = 0 __snake_case : Any = task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , f'''{shard_id:05d}''' ).replace('TTTTT' , f'''{task_id:05d}''' ) , fpath.replace(__snake_case , '' ) , ) def A_ ( self : str , __a : "datasets.SplitGenerator" , ) -> Tuple: '''simple docstring''' return SparkExamplesIterable(self.df )
357
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : Tuple ) -> Optional[int]: 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 not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False __snake_case : Union[str, Any] = range(3 ,int(math.sqrt(lowerCAmelCase__ ) + 1 ) ,2 ) return not any(not number % i for i in odd_numbers ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=1 ,**_UpperCAmelCase : Tuple ) -> str: __snake_case : List[Any] = factor * value __snake_case : str = value while not is_prime(lowerCAmelCase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 ,**lowerCAmelCase__ ) return value
358
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
0
'''simple docstring''' import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging A__ : List[str] = logging.get_logger(__name__) class snake_case__ ( __a ): A__ = ["""input_ids""", """attention_mask"""] def __init__( self : str , __a : Any="</s>" , __a : List[Any]="<unk>" , __a : int="<pad>" , __a : Optional[Any]=125 , __a : Any=None , **__a : Dict , ) -> Optional[Any]: '''simple docstring''' # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __snake_case : List[Any] = [f'''<extra_id_{i}>''' for i in range(a__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __snake_case : Dict = len(set(filter(lambda __a : bool('extra_id' in str(a__ ) ) , a__ ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the' ' extra_ids tokens' ) __snake_case : Optional[int] = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else pad_token __snake_case : Union[str, Any] = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else eos_token __snake_case : Optional[int] = AddedToken(a__ , lstrip=a__ , rstrip=a__ ) if isinstance(a__ , a__ ) else unk_token super().__init__( eos_token=a__ , unk_token=a__ , pad_token=a__ , extra_ids=a__ , additional_special_tokens=a__ , **a__ , ) __snake_case : int = extra_ids __snake_case : Any = 2**8 # utf is 8 bits # define special tokens dict __snake_case : int = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } __snake_case : Union[str, Any] = len(self.special_tokens_encoder ) __snake_case : Dict = len(a__ ) for i, token in enumerate(a__ ): __snake_case : List[str] = self.vocab_size + i - n __snake_case : str = {v: k for k, v in self.special_tokens_encoder.items()} @property def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def A_ ( self : Tuple , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ) -> List[Any]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=a__ , token_ids_a=a__ , already_has_special_tokens=a__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(a__ )) + [1] return ([0] * len(a__ )) + [1] + ([0] * len(a__ )) + [1] def A_ ( self : Dict , __a : List[int] ) -> Tuple: '''simple docstring''' if len(a__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def A_ ( self : Any , __a : List[int] , __a : Optional[List[int]] = None ) -> Optional[Any]: '''simple docstring''' __snake_case : int = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[str]: '''simple docstring''' __snake_case : Union[str, Any] = self._add_eos_if_not_present(a__ ) if token_ids_a is None: return token_ids_a else: __snake_case : List[Any] = self._add_eos_if_not_present(a__ ) return token_ids_a + token_ids_a def A_ ( self : str , __a : str ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = [chr(a__ ) for i in text.encode('utf-8' )] return tokens def A_ ( self : int , __a : str ) -> str: '''simple docstring''' if token in self.special_tokens_encoder: __snake_case : int = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: __snake_case : List[Any] = self.added_tokens_encoder[token] elif len(a__ ) != 1: __snake_case : Union[str, Any] = self.unk_token_id else: __snake_case : Dict = ord(a__ ) + self._num_special_tokens return token_id def A_ ( self : List[str] , __a : List[str] ) -> int: '''simple docstring''' if index in self.special_tokens_decoder: __snake_case : str = self.special_tokens_decoder[index] else: __snake_case : Dict = chr(index - self._num_special_tokens ) return token def A_ ( self : List[str] , __a : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Optional[Any] = b'' for token in tokens: if token in self.special_tokens_decoder: __snake_case : List[Any] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.added_tokens_decoder: __snake_case : List[str] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.special_tokens_encoder: __snake_case : Union[str, Any] = token.encode('utf-8' ) elif token in self.added_tokens_encoder: __snake_case : Optional[int] = token.encode('utf-8' ) else: __snake_case : Union[str, Any] = bytes([ord(a__ )] ) bstring += tok_string __snake_case : List[Any] = bstring.decode('utf-8' , errors='ignore' ) return string def A_ ( self : int , __a : str , __a : Optional[str] = None ) -> List[Any]: '''simple docstring''' return ()
359
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
0
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py A__ : List[str] = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. A__ : Union[str, Any] = direct_transformers_import(PATH_TO_TRANSFORMERS) A__ : Any = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` A__ : List[Any] = re.compile(R'''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') A__ : str = { "DecisionTransformerConfig", "EncoderDecoderConfig", "MusicgenConfig", "RagConfig", "SpeechEncoderDecoderConfig", "TimmBackboneConfig", "VisionEncoderDecoderConfig", "VisionTextDualEncoderConfig", "LlamaConfig", } def a_ ( _UpperCAmelCase : List[str] ) -> Union[str, Any]: __snake_case : int = None # source code of `config_class` __snake_case : Optional[Any] = inspect.getsource(_UpperCAmelCase ) __snake_case : str = _re_checkpoint.findall(_UpperCAmelCase ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith('/' ): __snake_case : Dict = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link __snake_case : int = f'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: __snake_case : List[str] = ckpt_name break return checkpoint def a_ ( ) -> Union[str, Any]: __snake_case : Optional[Any] = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue __snake_case : Tuple = get_checkpoint_from_config_class(_UpperCAmelCase ) __snake_case : Optional[Any] = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: __snake_case : str = '''\n'''.join(sorted(_UpperCAmelCase ) ) raise ValueError(f'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
360
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
0
import math def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> int: __snake_case : Tuple = len(__snake_case ) __snake_case : Union[str, Any] = int(math.floor(math.sqrt(__snake_case ) ) ) __snake_case : List[str] = 0 while arr[min(__snake_case ,__snake_case ) - 1] < x: __snake_case : List[Any] = step step += int(math.floor(math.sqrt(__snake_case ) ) ) if prev >= n: return -1 while arr[prev] < x: __snake_case : List[str] = prev + 1 if prev == min(__snake_case ,__snake_case ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": A__ : Tuple = input('''Enter numbers separated by a comma:\n''').strip() A__ : List[Any] = [int(item) for item in user_input.split(''',''')] A__ : List[str] = int(input('''Enter the number to be searched:\n''')) A__ : Dict = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(F"""Number {x} is at index {res}""")
361
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
0
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal A__ : List[Any] = datasets.utils.logging.get_logger(__name__) A__ : Optional[int] = ['''names''', '''prefix'''] A__ : Optional[int] = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] A__ : Any = ['''encoding_errors''', '''on_bad_lines'''] A__ : Optional[Any] = ['''date_format'''] @dataclass class snake_case__ ( datasets.BuilderConfig ): A__ = ''',''' A__ = None A__ = '''infer''' A__ = None A__ = None A__ = None A__ = None A__ = None A__ = True A__ = None A__ = None A__ = None A__ = None A__ = False A__ = None A__ = None A__ = None A__ = True A__ = True A__ = False A__ = True A__ = None A__ = '''.''' A__ = None A__ = '''"''' A__ = 0 A__ = None A__ = None A__ = None A__ = None A__ = True A__ = True A__ = 0 A__ = True A__ = False A__ = None A__ = 10_000 A__ = None A__ = '''strict''' A__ = '''error''' A__ = None def A_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' if self.delimiter is not None: __snake_case : List[str] = self.delimiter if self.column_names is not None: __snake_case : Optional[int] = self.column_names @property def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = { 'sep': self.sep, 'header': self.header, 'names': self.names, 'index_col': self.index_col, 'usecols': self.usecols, 'prefix': self.prefix, 'mangle_dupe_cols': self.mangle_dupe_cols, 'engine': self.engine, 'converters': self.converters, 'true_values': self.true_values, 'false_values': self.false_values, 'skipinitialspace': self.skipinitialspace, 'skiprows': self.skiprows, 'nrows': self.nrows, 'na_values': self.na_values, 'keep_default_na': self.keep_default_na, 'na_filter': self.na_filter, 'verbose': self.verbose, 'skip_blank_lines': self.skip_blank_lines, 'thousands': self.thousands, 'decimal': self.decimal, 'lineterminator': self.lineterminator, 'quotechar': self.quotechar, 'quoting': self.quoting, 'escapechar': self.escapechar, 'comment': self.comment, 'encoding': self.encoding, 'dialect': self.dialect, 'error_bad_lines': self.error_bad_lines, 'warn_bad_lines': self.warn_bad_lines, 'skipfooter': self.skipfooter, 'doublequote': self.doublequote, 'memory_map': self.memory_map, 'float_precision': self.float_precision, 'chunksize': self.chunksize, 'encoding_errors': self.encoding_errors, 'on_bad_lines': self.on_bad_lines, 'date_format': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , UpperCamelCase__ ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class snake_case__ ( datasets.ArrowBasedBuilder ): A__ = CsvConfig def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def A_ ( self : Dict , __a : str ) -> List[str]: '''simple docstring''' if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) __snake_case : Any = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCamelCase__ , (str, list, tuple) ): __snake_case : List[str] = data_files if isinstance(UpperCamelCase__ , UpperCamelCase__ ): __snake_case : str = [files] __snake_case : Optional[Any] = [dl_manager.iter_files(UpperCamelCase__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] __snake_case : Union[str, Any] = [] for split_name, files in data_files.items(): if isinstance(UpperCamelCase__ , UpperCamelCase__ ): __snake_case : Optional[int] = [files] __snake_case : List[str] = [dl_manager.iter_files(UpperCamelCase__ ) for file in files] splits.append(datasets.SplitGenerator(name=UpperCamelCase__ , gen_kwargs={'files': files} ) ) return splits def A_ ( self : Union[str, Any] , __a : List[Any] ) -> pa.Table: '''simple docstring''' if self.config.features is not None: __snake_case : Optional[Any] = self.config.features.arrow_schema if all(not require_storage_cast(UpperCamelCase__ ) for feature in self.config.features.values() ): # cheaper cast __snake_case : List[Any] = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=UpperCamelCase__ ) else: # more expensive cast; allows str <-> int/float or str to Audio for example __snake_case : int = table_cast(UpperCamelCase__ , UpperCamelCase__ ) return pa_table def A_ ( self : Dict , __a : int ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str __snake_case : Tuple = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(UpperCamelCase__ ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCamelCase__ ) ): __snake_case : Optional[int] = pd.read_csv(UpperCamelCase__ , iterator=UpperCamelCase__ , dtype=UpperCamelCase__ , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(UpperCamelCase__ ): __snake_case : int = pa.Table.from_pandas(UpperCamelCase__ ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(UpperCamelCase__ ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(UpperCamelCase__ )}: {e}''' ) raise
362
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
0
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters A__ : int = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : Tuple=None ) -> str: # Recurse if needed if "." in tensor_name: __snake_case : Tuple = tensor_name.split('.' ) for split in splits[:-1]: __snake_case : List[Any] = getattr(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) if new_module is None: raise ValueError(f'''{module} has no attribute {split}.''' ) __snake_case : Tuple = new_module __snake_case : Optional[Any] = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.''' ) __snake_case : Union[str, Any] = tensor_name in module._buffers __snake_case : Dict = getattr(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) if old_value.device == torch.device('meta' ) and device not in ["meta", torch.device('meta' )] and value is None: raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' ) __snake_case : Union[str, Any] = False __snake_case : Union[str, Any] = False if is_buffer or not is_bitsandbytes_available(): __snake_case : Optional[Any] = False __snake_case : Any = False else: __snake_case : Optional[int] = hasattr(bnb.nn ,'Params4bit' ) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit ) __snake_case : List[Any] = isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams ) if is_abit or is_abit: __snake_case : Optional[Any] = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: __snake_case : Any = old_value.to(SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_ ,torch.Tensor ): __snake_case : str = value.to('cpu' ) if value.dtype == torch.inta: __snake_case : List[str] = version.parse(importlib.metadata.version('bitsandbytes' ) ) > version.parse( '0.37.2' ) if not is_abit_serializable: raise ValueError( 'Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ' 'Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.' ) else: __snake_case : Optional[int] = torch.tensor(SCREAMING_SNAKE_CASE_ ,device='cpu' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls ,SCREAMING_SNAKE_CASE_ ) and fpaa_statistics is None: __snake_case : Optional[int] = new_value.T __snake_case : Optional[int] = old_value.__dict__ if is_abit: __snake_case : Dict = bnb.nn.IntaParams(SCREAMING_SNAKE_CASE_ ,requires_grad=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) elif is_abit: __snake_case : str = bnb.nn.Paramsabit(SCREAMING_SNAKE_CASE_ ,requires_grad=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) __snake_case : Dict = new_value if fpaa_statistics is not None: setattr(module.weight ,'SCB' ,fpaa_statistics.to(SCREAMING_SNAKE_CASE_ ) ) else: if value is None: __snake_case : int = old_value.to(SCREAMING_SNAKE_CASE_ ) elif isinstance(SCREAMING_SNAKE_CASE_ ,torch.Tensor ): __snake_case : int = value.to(SCREAMING_SNAKE_CASE_ ) else: __snake_case : Tuple = torch.tensor(SCREAMING_SNAKE_CASE_ ,device=SCREAMING_SNAKE_CASE_ ) if is_buffer: __snake_case : Optional[Any] = new_value else: __snake_case : Optional[Any] = nn.Parameter(SCREAMING_SNAKE_CASE_ ,requires_grad=old_value.requires_grad ) __snake_case : Dict = new_value def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Optional[Any]=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Optional[Any]=None ,_UpperCAmelCase : int=False ) -> Any: for name, module in model.named_children(): if current_key_name is None: __snake_case : Any = [] current_key_name.append(SCREAMING_SNAKE_CASE_ ) if (isinstance(SCREAMING_SNAKE_CASE_ ,nn.Linear ) or isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '.'.join(SCREAMING_SNAKE_CASE_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): __snake_case , __snake_case : List[Any] = module.weight.shape else: __snake_case : Optional[int] = module.in_features __snake_case : str = module.out_features if quantization_config.quantization_method() == "llm_int8": __snake_case : int = bnb.nn.LinearabitLt( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,) __snake_case : List[str] = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: __snake_case : Dict = bnb.nn.Linearabit( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,module.bias is not None ,quantization_config.bnb_abit_compute_dtype ,compress_statistics=quantization_config.bnb_abit_use_double_quant ,quant_type=quantization_config.bnb_abit_quant_type ,) __snake_case : List[str] = True # Store the module class in case we need to transpose the weight later __snake_case : str = type(SCREAMING_SNAKE_CASE_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(SCREAMING_SNAKE_CASE_ ) if len(list(module.children() ) ) > 0: __snake_case , __snake_case : Optional[int] = _replace_with_bnb_linear( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,has_been_replaced=SCREAMING_SNAKE_CASE_ ,) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Optional[Any]=None ) -> Optional[int]: __snake_case : List[str] = ['lm_head'] if modules_to_not_convert is None else modules_to_not_convert __snake_case , __snake_case : Optional[int] = _replace_with_bnb_linear( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def a_ ( *_UpperCAmelCase : str ,**_UpperCAmelCase : Any ) -> Any: warnings.warn( '`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead' ,SCREAMING_SNAKE_CASE_ ,) return replace_with_bnb_linear(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) def a_ ( *_UpperCAmelCase : Any ,**_UpperCAmelCase : Optional[int] ) -> Optional[int]: warnings.warn( '`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead' ,SCREAMING_SNAKE_CASE_ ,) return set_module_quantized_tensor_to_device(*SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ) def a_ ( _UpperCAmelCase : Any ) -> Tuple: __snake_case : Any = deepcopy(SCREAMING_SNAKE_CASE_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() __snake_case : List[Any] = find_tied_parameters(SCREAMING_SNAKE_CASE_ ) # For compatibility with Accelerate < 0.18 if isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): __snake_case : int = sum(list(tied_params.values() ) ,[] ) + list(tied_params.keys() ) else: __snake_case : int = sum(SCREAMING_SNAKE_CASE_ ,[] ) __snake_case : Any = len(SCREAMING_SNAKE_CASE_ ) > 0 # Check if it is a base model __snake_case : str = not hasattr(SCREAMING_SNAKE_CASE_ ,model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head __snake_case : Tuple = list(model.named_children() ) __snake_case : List[Any] = [list_modules[-1][0]] # add last module together with tied weights __snake_case : Union[str, Any] = set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) __snake_case : Tuple = list(set(SCREAMING_SNAKE_CASE_ ) ) + list(SCREAMING_SNAKE_CASE_ ) # remove ".weight" from the keys __snake_case : Dict = ['.weight', '.bias'] __snake_case : Tuple = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: __snake_case : Dict = name.replace(SCREAMING_SNAKE_CASE_ ,'' ) filtered_module_names.append(SCREAMING_SNAKE_CASE_ ) return filtered_module_names
363
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
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, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import LevitImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self : Optional[int] , __a : Optional[int] , __a : List[str]=7 , __a : Optional[Any]=3 , __a : Union[str, Any]=18 , __a : Dict=30 , __a : Optional[Any]=400 , __a : Tuple=True , __a : Dict=None , __a : Tuple=True , __a : Dict=None , __a : Dict=True , __a : Union[str, Any]=[0.5, 0.5, 0.5] , __a : Tuple=[0.5, 0.5, 0.5] , ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = size if size is not None else {'shortest_edge': 18} __snake_case : Dict = crop_size if crop_size is not None else {'height': 18, 'width': 18} __snake_case : int = parent __snake_case : Union[str, Any] = batch_size __snake_case : Optional[Any] = num_channels __snake_case : List[Any] = image_size __snake_case : Optional[int] = min_resolution __snake_case : Optional[int] = max_resolution __snake_case : List[Any] = do_resize __snake_case : Any = size __snake_case : Optional[Any] = do_center_crop __snake_case : List[Any] = crop_size __snake_case : int = do_normalize __snake_case : Optional[int] = image_mean __snake_case : Optional[Any] = image_std def A_ ( self : str ) -> Dict: '''simple docstring''' return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class snake_case__ ( a__ , unittest.TestCase ): A__ = LevitImageProcessor if is_vision_available() else None def A_ ( self : Any ) -> str: '''simple docstring''' __snake_case : str = LevitImageProcessingTester(self ) @property def A_ ( self : Optional[int] ) -> Any: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A_ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' __snake_case : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'do_center_crop' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , 'size' ) ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) __snake_case : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' pass def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' # Initialize image_processing __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , Image.Image ) # Test not batched input __snake_case : str = 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 __snake_case : Optional[int] = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A_ ( self : Dict ) -> Tuple: '''simple docstring''' # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , np.ndarray ) # Test not batched input __snake_case : str = 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 __snake_case : Any = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE_ , torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_ , torch.Tensor ) # Test not batched input __snake_case : int = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched __snake_case : Tuple = image_processing(SCREAMING_SNAKE_CASE_ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=_SCREAMING_SNAKE_CASE ) class snake_case__ ( _SCREAMING_SNAKE_CASE ): A__ = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) A__ = Features({'''audio''': Audio()} ) A__ = Features({'''transcription''': Value('''string''' )} ) A__ = '''audio''' A__ = '''transcription''' def A_ ( self : str , __a : Dict ) -> str: '''simple docstring''' if self.audio_column not in features: raise ValueError(f'''Column {self.audio_column} is not present in features.''' ) if not isinstance(features[self.audio_column] , __a ): raise ValueError(f'''Column {self.audio_column} is not an Audio type.''' ) __snake_case : Optional[Any] = copy.deepcopy(self ) __snake_case : int = self.input_schema.copy() __snake_case : Optional[int] = features[self.audio_column] __snake_case : Tuple = input_schema return task_template @property def A_ ( self : Dict ) -> Dict[str, str]: '''simple docstring''' return {self.audio_column: "audio", self.transcription_column: "transcription"}
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
0
'''simple docstring''' from datetime import datetime import requests def a_ ( _UpperCAmelCase : Any ) -> List[Any]: __snake_case : int = '''https://downloadgram.net/wp-json/wppress/video-downloader/video?url=''' __snake_case : int = requests.get(base_url + url ).json()[0]['''urls'''][0]['''src'''] return requests.get(_UpperCAmelCase ).content if __name__ == "__main__": A__ : Dict = input('''Enter Video/IGTV url: ''').strip() A__ : Tuple = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4""" with open(file_name, '''wb''') as fp: fp.write(download_video(url)) print(F"""Done. Video saved to disk as {file_name}.""")
366
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : Tuple ) -> Dict: if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(snake_case_ ,n - 1 ,snake_case_ ) * a) % mod else: __snake_case : Union[str, Any] = binary_exponentiation(snake_case_ ,n / 2 ,snake_case_ ) return (b * b) % mod # a prime number A__ : Any = 7_0_1 A__ : Union[str, Any] = 1_0_0_0_0_0_0_0_0_0 A__ : List[Any] = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
367
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
0
'''simple docstring''' import unittest from transformers import AutoTokenizer, NystromformerConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case__ : def __init__( self : Dict , __a : Optional[int] , __a : int=13 , __a : Optional[Any]=7 , __a : Optional[Any]=True , __a : Tuple=True , __a : Union[str, Any]=True , __a : int=True , __a : List[str]=99 , __a : Any=32 , __a : Dict=5 , __a : str=4 , __a : Optional[int]=37 , __a : Union[str, Any]="gelu" , __a : int=0.1 , __a : Any=0.1 , __a : str=512 , __a : List[Any]=16 , __a : Any=2 , __a : Dict=0.0_2 , __a : Tuple=3 , __a : str=4 , __a : Union[str, Any]=None , ) -> str: '''simple docstring''' __snake_case : List[Any] = parent __snake_case : List[str] = batch_size __snake_case : int = seq_length __snake_case : Optional[Any] = is_training __snake_case : List[str] = use_input_mask __snake_case : Any = use_token_type_ids __snake_case : Dict = use_labels __snake_case : Optional[Any] = vocab_size __snake_case : str = hidden_size __snake_case : Optional[int] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : int = intermediate_size __snake_case : Tuple = hidden_act __snake_case : int = hidden_dropout_prob __snake_case : Union[str, Any] = attention_probs_dropout_prob __snake_case : List[Any] = max_position_embeddings __snake_case : Any = type_vocab_size __snake_case : Any = type_sequence_label_size __snake_case : int = initializer_range __snake_case : Optional[int] = num_labels __snake_case : Any = num_choices __snake_case : Union[str, Any] = scope def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Dict = None if self.use_input_mask: __snake_case : str = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : Optional[Any] = None if self.use_token_type_ids: __snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : Union[str, Any] = None __snake_case : int = None __snake_case : str = None if self.use_labels: __snake_case : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) __snake_case : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A_ ( self : Any ) -> List[Any]: '''simple docstring''' return NystromformerConfig( 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 A_ ( self : Any , __a : Union[str, Any] , __a : Dict , __a : int , __a : Union[str, Any] , __a : Dict , __a : Tuple , __a : List[Any] ) -> str: '''simple docstring''' __snake_case : Dict = NystromformerModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : str = model(_UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) __snake_case : List[str] = model(_UpperCAmelCase , token_type_ids=_UpperCAmelCase ) __snake_case : Dict = model(_UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : Tuple , __a : Any , __a : Any , __a : List[Any] , __a : Any , __a : Dict , __a : List[str] , __a : Any ) -> str: '''simple docstring''' __snake_case : List[str] = NystromformerForMaskedLM(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : str = 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 A_ ( self : Optional[Any] , __a : List[str] , __a : List[Any] , __a : Dict , __a : List[str] , __a : str , __a : int , __a : Union[str, Any] ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = NystromformerForQuestionAnswering(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : Tuple = 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 A_ ( self : Any , __a : List[Any] , __a : Optional[Any] , __a : Tuple , __a : List[Any] , __a : int , __a : Dict , __a : Any ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.num_labels __snake_case : Optional[Any] = NystromformerForSequenceClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : Optional[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 A_ ( self : str , __a : Optional[Any] , __a : List[Any] , __a : str , __a : int , __a : Optional[int] , __a : Any , __a : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = self.num_labels __snake_case : Any = NystromformerForTokenClassification(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : Tuple = 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 A_ ( self : Union[str, Any] , __a : int , __a : Dict , __a : Union[str, Any] , __a : str , __a : Dict , __a : Tuple , __a : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : int = self.num_choices __snake_case : Optional[Any] = NystromformerForMultipleChoice(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() __snake_case : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : List[str] = model( _UpperCAmelCase , attention_mask=_UpperCAmelCase , token_type_ids=_UpperCAmelCase , labels=_UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Optional[Any] = self.prepare_config_and_inputs() ( __snake_case ) : List[str] = config_and_inputs __snake_case : str = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): A__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) A__ = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) A__ = False A__ = False def A_ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' __snake_case : Dict = NystromformerModelTester(self ) __snake_case : Dict = ConfigTester(self , config_class=_UpperCAmelCase , hidden_size=37 ) def A_ ( self : Tuple ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __snake_case : List[str] = type self.model_tester.create_and_check_model(*_UpperCAmelCase ) def A_ ( self : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase ) def A_ ( self : Tuple ) -> str: '''simple docstring''' __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_UpperCAmelCase ) def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_UpperCAmelCase ) def A_ ( self : int ) -> str: '''simple docstring''' __snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_UpperCAmelCase ) def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_UpperCAmelCase ) @slow def A_ ( self : Dict ) -> Any: '''simple docstring''' for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[Any] = NystromformerModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) @require_torch class snake_case__ ( unittest.TestCase ): @slow def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' __snake_case : List[str] = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) __snake_case : Optional[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __snake_case : Optional[Any] = model(_UpperCAmelCase )[0] __snake_case : Optional[Any] = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , _UpperCAmelCase ) __snake_case : Any = torch.tensor( [[[-0.4_5_3_2, -0.0_9_3_6, 0.5_1_3_7], [-0.2_6_7_6, 0.0_6_2_8, 0.6_1_8_6], [-0.3_6_2_9, -0.1_7_2_6, 0.4_7_1_6]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _UpperCAmelCase , atol=1e-4 ) ) @slow def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' __snake_case : Optional[Any] = 'the [MASK] of Belgium is Brussels' __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) __snake_case : Optional[Any] = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) __snake_case : List[str] = tokenizer(_UpperCAmelCase , return_tensors='pt' ) with torch.no_grad(): __snake_case : Union[str, Any] = model(encoding.input_ids ).logits __snake_case : Tuple = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(_UpperCAmelCase ) , 'capital' )
368
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
0
'''simple docstring''' from typing import Any class snake_case__ : def __init__( self : Any , __a : Any ) -> Dict: '''simple docstring''' __snake_case : Tuple = data __snake_case : Any = None def __repr__( self : str ) -> str: '''simple docstring''' return f'''Node({self.data})''' class snake_case__ : def __init__( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = None def __iter__( self : Optional[Any] ) -> Any: '''simple docstring''' __snake_case : List[str] = self.head while node: yield node.data __snake_case : List[str] = node.next def __len__( self : List[str] ) -> int: '''simple docstring''' return sum(1 for _ in self ) def __repr__( self : List[Any] ) -> str: '''simple docstring''' return "->".join([str(UpperCamelCase__ ) for item in self] ) def __getitem__( self : Any , __a : int ) -> Any: '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : List[Any] , __a : int , __a : Any ) -> None: '''simple docstring''' if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) __snake_case : List[str] = self.head for _ in range(UpperCamelCase__ ): __snake_case : Optional[int] = current.next __snake_case : List[Any] = data def A_ ( self : Union[str, Any] , __a : Any ) -> None: '''simple docstring''' self.insert_nth(len(self ) , UpperCamelCase__ ) def A_ ( self : str , __a : Any ) -> None: '''simple docstring''' self.insert_nth(0 , UpperCamelCase__ ) def A_ ( self : Dict , __a : int , __a : Any ) -> None: '''simple docstring''' if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) __snake_case : Union[str, Any] = Node(UpperCamelCase__ ) if self.head is None: __snake_case : Optional[Any] = new_node elif index == 0: __snake_case : int = self.head # link new_node to head __snake_case : Optional[Any] = new_node else: __snake_case : Union[str, Any] = self.head for _ in range(index - 1 ): __snake_case : Dict = temp.next __snake_case : int = temp.next __snake_case : Any = new_node def A_ ( self : Tuple ) -> None: # print every node data '''simple docstring''' print(self ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' return self.delete_nth(0 ) def A_ ( self : Dict ) -> Any: # delete from tail '''simple docstring''' return self.delete_nth(len(self ) - 1 ) def A_ ( self : Optional[Any] , __a : int = 0 ) -> Any: '''simple docstring''' if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) __snake_case : List[Any] = self.head # default first node if index == 0: __snake_case : Union[str, Any] = self.head.next else: __snake_case : Optional[int] = self.head for _ in range(index - 1 ): __snake_case : Any = temp.next __snake_case : Union[str, Any] = temp.next __snake_case : int = temp.next.next return delete_node.data def A_ ( self : str ) -> bool: '''simple docstring''' return self.head is None def A_ ( self : Any ) -> None: '''simple docstring''' __snake_case : List[str] = None __snake_case : int = self.head while current: # Store the current node's next node. __snake_case : Tuple = current.next # Make the current node's next point backwards __snake_case : Optional[int] = prev # Make the previous node be the current node __snake_case : List[str] = current # Make the current node the next node (to progress iteration) __snake_case : List[Any] = next_node # Return prev in order to put the head at the end __snake_case : Dict = prev def a_ ( ) -> None: __snake_case : Optional[Any] = LinkedList() assert linked_list.is_empty() is True assert str(__SCREAMING_SNAKE_CASE ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(__SCREAMING_SNAKE_CASE ) == i linked_list.insert_nth(__SCREAMING_SNAKE_CASE ,i + 1 ) assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(1 ,11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(0 ,12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(__SCREAMING_SNAKE_CASE ) == 9 assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(1 ,10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 ,9 ) ) is True for i in range(0 ,9 ): __snake_case : str = -i assert all(linked_list[i] == -i for i in range(0 ,9 ) ) is True linked_list.reverse() assert str(__SCREAMING_SNAKE_CASE ) == "->".join(str(__SCREAMING_SNAKE_CASE ) for i in range(-8 ,1 ) ) def a_ ( ) -> None: __snake_case : Union[str, Any] = [ -9, 1_00, Node(77_34_51_12 ), "dlrow olleH", 7, 55_55, 0, -1_9_2.5_5_5_5_5, "Hello, world!", 7_7.9, Node(10 ), None, None, 1_2.2_0, ] __snake_case : int = LinkedList() for i in test_input: linked_list.insert_tail(__SCREAMING_SNAKE_CASE ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(__SCREAMING_SNAKE_CASE ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head __snake_case : Union[str, Any] = linked_list.delete_head() assert result == -9 assert ( str(__SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail __snake_case : List[str] = linked_list.delete_tail() assert result == 1_2.2 assert ( str(__SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list __snake_case : List[str] = linked_list.delete_nth(10 ) assert result is None assert ( str(__SCREAMING_SNAKE_CASE ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(__SCREAMING_SNAKE_CASE ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(__SCREAMING_SNAKE_CASE ) assert ( str(__SCREAMING_SNAKE_CASE ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(__SCREAMING_SNAKE_CASE ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def a_ ( ) -> str: from doctest import testmod testmod() __snake_case : Optional[int] = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(__SCREAMING_SNAKE_CASE ) print('\nReading/changing Node data using indexing:' ) print(f'''Element at Position 1: {linked_list[1]}''' ) __snake_case : Tuple = input('Enter New Value: ' ).strip() print('New list:' ) print(__SCREAMING_SNAKE_CASE ) print(f'''length of linked_list is : {len(__SCREAMING_SNAKE_CASE )}''' ) if __name__ == "__main__": main()
369
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): A__ = StableDiffusionInpaintPipeline A__ = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS A__ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS A__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess A__ = frozenset([] ) def A_ ( self : Optional[Any] ): '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__snake_case , ) __snake_case : Optional[int] = PNDMScheduler(skip_prk_steps=__snake_case ) torch.manual_seed(0 ) __snake_case : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='gelu' , projection_dim=512 , ) __snake_case : Optional[int] = CLIPTextModel(__snake_case ) __snake_case : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __snake_case : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def A_ ( self : Optional[int] , __a : Union[str, Any] , __a : int=0 ): '''simple docstring''' # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched __snake_case : str = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) __snake_case : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __snake_case : List[str] = Image.fromarray(np.uinta(__snake_case ) ).convert('RGB' ).resize((64, 64) ) __snake_case : Union[str, Any] = Image.fromarray(np.uinta(image + 4 ) ).convert('RGB' ).resize((64, 64) ) if str(__snake_case ).startswith('mps' ): __snake_case : Union[str, Any] = torch.manual_seed(__snake_case ) else: __snake_case : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) __snake_case : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': init_image, 'mask_image': mask_image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', } return inputs def A_ ( self : int ): '''simple docstring''' __snake_case : str = 'cpu' # ensure determinism for the device-dependent torch.Generator __snake_case : Union[str, Any] = self.get_dummy_components() __snake_case : Dict = StableDiffusionInpaintPipeline(**__snake_case ) __snake_case : Union[str, Any] = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) __snake_case : Union[str, Any] = self.get_dummy_inputs(__snake_case ) __snake_case : int = sd_pipe(**__snake_case ).images __snake_case : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __snake_case : Dict = np.array([0.4_7_2_7, 0.5_7_3_5, 0.3_9_4_1, 0.5_4_4_6, 0.5_9_2_6, 0.4_3_9_4, 0.5_0_6_2, 0.4_6_5_4, 0.4_4_7_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : List[Any] ): '''simple docstring''' super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : Dict ): '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : Union[str, Any] ): '''simple docstring''' __snake_case : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __snake_case : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __snake_case : Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench.npy' ) __snake_case : Tuple = 'stabilityai/stable-diffusion-2-inpainting' __snake_case : Tuple = StableDiffusionInpaintPipeline.from_pretrained(__snake_case , safety_checker=__snake_case ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() __snake_case : List[str] = 'Face of a yellow cat, high resolution, sitting on a park bench' __snake_case : str = torch.manual_seed(0 ) __snake_case : List[str] = pipe( prompt=__snake_case , image=__snake_case , mask_image=__snake_case , generator=__snake_case , output_type='np' , ) __snake_case : Dict = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def A_ ( self : List[Any] ): '''simple docstring''' __snake_case : List[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __snake_case : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __snake_case : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint' '/yellow_cat_sitting_on_a_park_bench_fp16.npy' ) __snake_case : List[Any] = 'stabilityai/stable-diffusion-2-inpainting' __snake_case : Optional[int] = StableDiffusionInpaintPipeline.from_pretrained( __snake_case , torch_dtype=torch.floataa , safety_checker=__snake_case , ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() __snake_case : Optional[Any] = 'Face of a yellow cat, high resolution, sitting on a park bench' __snake_case : Dict = torch.manual_seed(0 ) __snake_case : List[Any] = pipe( prompt=__snake_case , image=__snake_case , mask_image=__snake_case , generator=__snake_case , output_type='np' , ) __snake_case : Any = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def A_ ( self : List[str] ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __snake_case : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) __snake_case : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) __snake_case : Any = 'stabilityai/stable-diffusion-2-inpainting' __snake_case : List[Any] = PNDMScheduler.from_pretrained(__snake_case , subfolder='scheduler' ) __snake_case : Any = StableDiffusionInpaintPipeline.from_pretrained( __snake_case , safety_checker=__snake_case , scheduler=__snake_case , torch_dtype=torch.floataa , ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __snake_case : int = 'Face of a yellow cat, high resolution, sitting on a park bench' __snake_case : Any = torch.manual_seed(0 ) __snake_case : List[str] = pipe( prompt=__snake_case , image=__snake_case , mask_image=__snake_case , generator=__snake_case , num_inference_steps=2 , output_type='np' , ) __snake_case : Union[str, Any] = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.6_5 * 10**9
370
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
0
'''simple docstring''' from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case__ ( _SCREAMING_SNAKE_CASE ): A__ = "new-model" if is_tf_available(): class snake_case__ ( _SCREAMING_SNAKE_CASE ): A__ = NewModelConfig @require_tf class snake_case__ ( unittest.TestCase ): @slow def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = 'bert-base-cased' __snake_case : Optional[int] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : int = TFAutoModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : Dict ) -> Tuple: '''simple docstring''' __snake_case : int = 'bert-base-cased' __snake_case : Optional[int] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : List[str] = TFAutoModelForPreTraining.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : List[str] = TFAutoModelForCausalLM.from_pretrained(A_ ) __snake_case , __snake_case : Tuple = TFAutoModelForCausalLM.from_pretrained(A_ , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : Optional[int] ) -> int: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Union[str, Any] = TFAutoModelWithLMHead.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Tuple = TFAutoModelForMaskedLM.from_pretrained(A_ ) __snake_case , __snake_case : Union[str, Any] = TFAutoModelForMaskedLM.from_pretrained(A_ , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Dict = TFAutoModelForSeqaSeqLM.from_pretrained(A_ ) __snake_case , __snake_case : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(A_ , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __snake_case : Optional[Any] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Optional[Any] = TFAutoModelForSequenceClassification.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow def A_ ( self : Dict ) -> List[str]: '''simple docstring''' # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __snake_case : List[str] = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Optional[int] = TFAutoModelForQuestionAnswering.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) @slow @require_tensorflow_probability def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: __snake_case : Dict = AutoConfig.from_pretrained(A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) __snake_case : Optional[Any] = TFAutoModelForTableQuestionAnswering.from_pretrained(A_ ) __snake_case , __snake_case : Tuple = TFAutoModelForTableQuestionAnswering.from_pretrained( A_ , output_loading_info=A_ ) self.assertIsNotNone(A_ ) self.assertIsInstance(A_ , A_ ) def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' __snake_case : str = TFAutoModelWithLMHead.from_pretrained(A_ ) self.assertIsInstance(A_ , A_ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=A_ ) , 14410 ) def A_ ( self : int ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TFAutoModelWithLMHead.from_pretrained(A_ ) self.assertIsInstance(A_ , A_ ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=A_ ) , 14410 ) def A_ ( self : str ) -> int: '''simple docstring''' __snake_case : int = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny' ) self.assertIsInstance(A_ , A_ ) __snake_case : List[Any] = copy.deepcopy(model.config ) __snake_case : Optional[int] = ['FunnelBaseModel'] __snake_case : Tuple = TFAutoModel.from_config(A_ ) self.assertIsInstance(A_ , A_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(A_ ) __snake_case : Optional[Any] = TFAutoModel.from_pretrained(A_ ) self.assertIsInstance(A_ , A_ ) def A_ ( self : Dict ) -> List[str]: '''simple docstring''' try: AutoConfig.register('new-model' , A_ ) __snake_case : int = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(A_ ): auto_class.register(A_ , A_ ) auto_class.register(A_ , A_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A_ ): auto_class.register(A_ , A_ ) # Now that the config is registered, it can be used as any other config with the auto-API __snake_case : List[Any] = BertModelTester(self ).get_config() __snake_case : List[str] = NewModelConfig(**tiny_config.to_dict() ) __snake_case : Union[str, Any] = auto_class.from_config(A_ ) self.assertIsInstance(A_ , A_ ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(A_ ) __snake_case : int = auto_class.from_pretrained(A_ ) self.assertIsInstance(A_ , A_ ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def A_ ( self : List[Any] ) -> Any: '''simple docstring''' with self.assertRaisesRegex( A_ , 'bert-base is not a local folder and is not a valid model identifier' ): __snake_case : List[str] = TFAutoModel.from_pretrained('bert-base' ) def A_ ( self : Any ) -> Dict: '''simple docstring''' with self.assertRaisesRegex( A_ , r'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): __snake_case : Any = TFAutoModel.from_pretrained(A_ , revision='aaaaaa' ) def A_ ( self : int ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A_ , 'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' , ): __snake_case : Tuple = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' with self.assertRaisesRegex(A_ , 'Use `from_pt=True` to load this model' ): __snake_case : Optional[int] = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) with RequestCounter() as counter: __snake_case : int = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint __snake_case : Union[str, Any] = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) with RequestCounter() as counter: __snake_case : Dict = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
0
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
'''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_camembert import CamembertTokenizer else: A__ : Union[str, Any] = None A__ : Optional[int] = logging.get_logger(__name__) A__ : Dict = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} A__ : Tuple = { '''vocab_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_file''': { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/tokenizer.json''', }, } A__ : List[Any] = { '''camembert-base''': 5_1_2, } A__ : Optional[Any] = '''▁''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ['''input_ids''', '''attention_mask'''] A__ = CamembertTokenizer def __init__( self : Any , __a : Dict=None , __a : Optional[Any]=None , __a : int="<s>" , __a : List[Any]="</s>" , __a : Union[str, Any]="</s>" , __a : Optional[Any]="<s>" , __a : Tuple="<unk>" , __a : int="<pad>" , __a : List[Any]="<mask>" , __a : int=["<s>NOTUSED", "</s>NOTUSED"] , **__a : List[str] , ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 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 , sep_token=__a , cls_token=__a , unk_token=__a , pad_token=__a , mask_token=__a , additional_special_tokens=__a , **__a , ) __snake_case : Optional[Any] = vocab_file __snake_case : str = False if not self.vocab_file else True def A_ ( self : str , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __snake_case : List[str] = [self.cls_token_id] __snake_case : Dict = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : Tuple , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : Union[str, Any] = [self.sep_token_id] __snake_case : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def A_ ( self : Dict , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(__a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __snake_case : str = 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,)
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
'''simple docstring''' import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() A__ : Optional[int] = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[str]=False ) -> Dict: __snake_case : Dict = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('head' ): __snake_case : Any = 'segformer.encoder.' + key if key.startswith('backbone' ): __snake_case : List[Any] = key.replace('backbone' ,'segformer.encoder' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 __snake_case : Union[str, Any] = key[key.find('patch_embed' ) + len('patch_embed' )] __snake_case : Optional[int] = key.replace(f'''patch_embed{idx}''' ,f'''patch_embeddings.{int(_UpperCAmelCase )-1}''' ) if "norm" in key: __snake_case : List[str] = key.replace('norm' ,'layer_norm' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 __snake_case : Tuple = key[key.find('segformer.encoder.layer_norm' ) + len('segformer.encoder.layer_norm' )] __snake_case : Union[str, Any] = key.replace(f'''layer_norm{idx}''' ,f'''layer_norm.{int(_UpperCAmelCase )-1}''' ) if "layer_norm1" in key: __snake_case : str = key.replace('layer_norm1' ,'layer_norm_1' ) if "layer_norm2" in key: __snake_case : int = key.replace('layer_norm2' ,'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 __snake_case : Dict = key[key.find('block' ) + len('block' )] __snake_case : List[str] = key.replace(f'''block{idx}''' ,f'''block.{int(_UpperCAmelCase )-1}''' ) if "attn.q" in key: __snake_case : Dict = key.replace('attn.q' ,'attention.self.query' ) if "attn.proj" in key: __snake_case : List[str] = key.replace('attn.proj' ,'attention.output.dense' ) if "attn" in key: __snake_case : int = key.replace('attn' ,'attention.self' ) if "fc1" in key: __snake_case : Optional[Any] = key.replace('fc1' ,'dense1' ) if "fc2" in key: __snake_case : int = key.replace('fc2' ,'dense2' ) if "linear_pred" in key: __snake_case : Optional[Any] = key.replace('linear_pred' ,'classifier' ) if "linear_fuse" in key: __snake_case : Any = key.replace('linear_fuse.conv' ,'linear_fuse' ) __snake_case : List[str] = key.replace('linear_fuse.bn' ,'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 __snake_case : int = key[key.find('linear_c' ) + len('linear_c' )] __snake_case : List[str] = key.replace(f'''linear_c{idx}''' ,f'''linear_c.{int(_UpperCAmelCase )-1}''' ) if key.startswith('head' ): __snake_case : Any = key.replace('head' ,'classifier' ) __snake_case : List[str] = value return new_state_dict def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : List[str] ) -> List[Any]: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) __snake_case : List[Any] = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''' ) __snake_case : int = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict __snake_case : int = kv_weight[ : config.hidden_sizes[i], : ] __snake_case : List[str] = kv_bias[: config.hidden_sizes[i]] __snake_case : Union[str, Any] = kv_weight[ config.hidden_sizes[i] :, : ] __snake_case : Optional[Any] = kv_bias[ config.hidden_sizes[i] : ] def a_ ( ) -> str: __snake_case : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __snake_case : Optional[int] = Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ) return image @torch.no_grad() def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any] ) -> List[str]: __snake_case : List[Any] = SegformerConfig() __snake_case : Optional[Any] = False # set attributes based on model_name __snake_case : int = 'huggingface/label-files' if "segformer" in model_name: __snake_case : Tuple = model_name[len('segformer.' ) : len('segformer.' ) + 2] if "ade" in model_name: __snake_case : Optional[Any] = 1_50 __snake_case : Optional[int] = 'ade20k-id2label.json' __snake_case : Optional[Any] = (1, 1_50, 1_28, 1_28) elif "city" in model_name: __snake_case : Any = 19 __snake_case : List[Any] = 'cityscapes-id2label.json' __snake_case : Tuple = (1, 19, 1_28, 1_28) else: raise ValueError(f'''Model {model_name} not supported''' ) elif "mit" in model_name: __snake_case : Union[str, Any] = True __snake_case : int = model_name[4:6] __snake_case : Union[str, Any] = 10_00 __snake_case : str = 'imagenet-1k-id2label.json' __snake_case : Any = (1, 10_00) else: raise ValueError(f'''Model {model_name} not supported''' ) # set config attributes __snake_case : List[Any] = json.load(open(hf_hub_download(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ,'r' ) ) __snake_case : Optional[int] = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Dict = idalabel __snake_case : List[Any] = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": __snake_case : List[Any] = [64, 1_28, 3_20, 5_12] __snake_case : str = 2_56 elif size == "b2": __snake_case : int = [64, 1_28, 3_20, 5_12] __snake_case : str = 7_68 __snake_case : Optional[int] = [3, 4, 6, 3] elif size == "b3": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : int = 7_68 __snake_case : Tuple = [3, 4, 18, 3] elif size == "b4": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : Union[str, Any] = 7_68 __snake_case : Union[str, Any] = [3, 8, 27, 3] elif size == "b5": __snake_case : Any = [64, 1_28, 3_20, 5_12] __snake_case : int = 7_68 __snake_case : List[str] = [3, 6, 40, 3] else: raise ValueError(f'''Size {size} not supported''' ) # load image processor (only resize + normalize) __snake_case : Optional[Any] = SegformerImageProcessor( image_scale=(5_12, 5_12) ,keep_ratio=_UpperCAmelCase ,align=_UpperCAmelCase ,do_random_crop=_UpperCAmelCase ) # prepare image __snake_case : Dict = prepare_img() __snake_case : List[str] = image_processor(images=_UpperCAmelCase ,return_tensors='pt' ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict if encoder_only: __snake_case : List[Any] = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) else: __snake_case : Optional[Any] = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) )['state_dict'] # rename keys __snake_case : Optional[int] = rename_keys(_UpperCAmelCase ,encoder_only=_UpperCAmelCase ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(_UpperCAmelCase ,_UpperCAmelCase ) # create HuggingFace model and load state dict if encoder_only: __snake_case : Dict = False __snake_case : Union[str, Any] = SegformerForImageClassification(_UpperCAmelCase ) else: __snake_case : Dict = SegformerForSemanticSegmentation(_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) model.eval() # forward pass __snake_case : List[str] = model(_UpperCAmelCase ) __snake_case : Tuple = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": __snake_case : Tuple = torch.tensor( [ [[-4.6_3_1_0, -5.5_2_3_2, -6.2_3_5_6], [-5.1_9_2_1, -6.1_4_4_4, -6.5_9_9_6], [-5.4_4_2_4, -6.2_7_9_0, -6.7_5_7_4]], [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]], [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": __snake_case : str = torch.tensor( [ [[-7.5_8_2_0, -8.7_2_3_1, -8.3_2_1_5], [-8.0_6_0_0, -10.35_29, -10.03_04], [-7.5_2_0_8, -9.4_1_0_3, -9.6_2_3_9]], [[-12.69_18, -13.89_94, -13.71_37], [-13.31_96, -15.75_23, -15.47_89], [-12.93_43, -14.87_57, -14.96_89]], [[-11.19_11, -11.94_21, -11.32_43], [-11.33_42, -13.68_39, -13.35_81], [-10.39_09, -12.18_32, -12.48_58]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": __snake_case : Optional[Any] = torch.tensor( [ [[-11.81_73, -14.38_50, -16.31_28], [-14.56_48, -16.58_04, -18.65_68], [-14.72_23, -15.73_87, -18.42_18]], [[-15.72_90, -17.91_71, -19.44_23], [-18.31_05, -19.94_48, -21.46_61], [-17.92_96, -18.64_97, -20.79_10]], [[-15.07_83, -17.03_36, -18.27_89], [-16.87_71, -18.68_70, -20.16_12], [-16.24_54, -17.14_26, -19.50_55]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-9.0_8_7_8, -10.20_81, -10.18_91], [-9.3_1_4_4, -10.79_41, -10.98_43], [-9.2_2_9_4, -10.38_55, -10.57_04]], [[-12.23_16, -13.90_68, -13.61_02], [-12.91_61, -14.37_02, -14.32_35], [-12.52_33, -13.71_74, -13.79_32]], [[-14.62_75, -15.24_90, -14.97_27], [-14.34_00, -15.96_87, -16.28_27], [-14.14_84, -15.40_33, -15.89_37]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": __snake_case : Dict = torch.tensor( [ [[-12.31_44, -13.24_47, -14.08_02], [-13.36_14, -14.58_16, -15.61_17], [-13.33_40, -14.44_33, -16.22_19]], [[-19.27_81, -20.41_28, -20.75_06], [-20.61_53, -21.65_66, -22.09_98], [-19.98_00, -21.04_30, -22.14_94]], [[-18.87_39, -19.78_04, -21.18_34], [-20.12_33, -21.67_65, -23.29_44], [-20.03_15, -21.26_41, -23.69_44]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-9.5_5_2_4, -12.08_35, -11.73_48], [-10.52_29, -13.64_46, -14.56_62], [-9.5_8_4_2, -12.88_51, -13.94_14]], [[-15.34_32, -17.53_23, -17.08_18], [-16.33_30, -18.92_55, -19.21_01], [-15.13_40, -17.78_48, -18.39_71]], [[-12.60_72, -14.94_86, -14.66_31], [-13.76_29, -17.09_07, -17.77_45], [-12.78_99, -16.16_95, -17.16_71]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": __snake_case : List[str] = torch.tensor( [ [[-11.92_95, -13.40_57, -14.81_06], [-13.34_31, -14.81_79, -15.37_81], [-14.28_36, -15.59_42, -16.15_88]], [[-11.49_06, -12.80_67, -13.65_64], [-13.11_89, -14.05_00, -14.15_43], [-13.87_48, -14.51_36, -14.87_89]], [[0.5_3_7_4, 0.1_0_6_7, -0.4_7_4_2], [0.1_1_4_1, -0.2_2_5_5, -0.7_0_9_9], [-0.3_0_0_0, -0.5_9_2_4, -1.3_1_0_5]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": __snake_case : int = torch.tensor( [ [[-7.8_2_1_7, -9.8_7_6_7, -10.17_17], [-9.4_4_3_8, -10.90_58, -11.40_47], [-9.7_9_3_9, -12.34_95, -12.10_79]], [[-7.1_5_1_4, -9.5_3_3_6, -10.08_60], [-9.7_7_7_6, -11.68_22, -11.84_39], [-10.14_11, -12.76_55, -12.89_72]], [[0.3_0_2_1, 0.0_8_0_5, -0.2_3_1_0], [-0.0_3_2_8, -0.1_6_0_5, -0.2_7_1_4], [-0.1_4_0_8, -0.5_4_7_7, -0.6_9_7_6]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": __snake_case : int = torch.tensor( [ [ [-1.1372E01, -1.2787E01, -1.3477E01], [-1.2536E01, -1.4194E01, -1.4409E01], [-1.3217E01, -1.4888E01, -1.5327E01], ], [ [-1.4791E01, -1.7122E01, -1.8277E01], [-1.7163E01, -1.9192E01, -1.9533E01], [-1.7897E01, -1.9991E01, -2.0315E01], ], [ [7.6723E-01, 4.1921E-01, -7.7878E-02], [4.7772E-01, 9.5557E-03, -2.8082E-01], [3.6032E-01, -2.4826E-01, -5.1168E-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": __snake_case : Optional[int] = torch.tensor( [ [[-9.4_9_5_9, -11.30_87, -11.74_79], [-11.00_25, -12.65_40, -12.33_19], [-11.40_64, -13.04_87, -12.99_05]], [[-9.8_9_0_5, -11.30_84, -12.08_54], [-11.17_26, -12.76_98, -12.95_83], [-11.59_85, -13.32_78, -14.17_74]], [[0.2_2_1_3, 0.0_1_9_2, -0.2_4_6_6], [-0.1_7_3_1, -0.4_2_1_3, -0.4_8_7_4], [-0.3_1_2_6, -0.6_5_4_1, -1.1_3_8_9]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": __snake_case : Tuple = torch.tensor( [ [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]], [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]], [[-3.6_4_5_6, -3.0_2_0_9, -1.4_2_0_3], [-3.0_7_9_7, -3.1_9_5_9, -2.0_0_0_0], [-1.8_7_5_7, -1.9_2_1_7, -1.6_9_9_7]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": __snake_case : Optional[Any] = torch.tensor( [ [[-16.09_76, -16.48_56, -17.39_62], [-16.62_34, -19.03_42, -19.76_85], [-16.09_00, -18.06_61, -19.11_80]], [[-18.47_50, -18.84_88, -19.50_74], [-19.40_30, -22.15_70, -22.59_77], [-19.11_91, -20.84_86, -22.37_83]], [[-4.5_1_7_8, -5.5_0_3_7, -6.5_1_0_9], [-5.0_8_8_4, -7.2_1_7_4, -8.0_3_3_4], [-4.4_1_5_6, -5.8_1_1_7, -7.2_9_7_0]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": __snake_case : Union[str, Any] = torch.tensor( [ [[-14.20_81, -14.47_32, -14.19_77], [-14.58_67, -16.44_23, -16.63_56], [-13.44_41, -14.96_85, -16.86_96]], [[-14.45_76, -14.70_73, -15.04_51], [-15.08_16, -17.62_37, -17.98_73], [-14.42_13, -16.01_99, -18.59_92]], [[-4.7_3_4_9, -4.9_5_8_8, -5.0_9_6_6], [-4.3_2_1_0, -6.9_3_2_5, -7.2_5_9_1], [-3.4_3_1_2, -4.7_4_8_4, -7.1_9_1_7]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": __snake_case : Optional[int] = torch.tensor( [ [[-11.77_37, -11.95_26, -11.32_73], [-13.66_92, -14.45_74, -13.88_78], [-13.89_37, -14.69_24, -15.93_45]], [[-14.67_06, -14.53_30, -14.13_06], [-16.15_02, -16.81_80, -16.42_69], [-16.83_38, -17.89_39, -20.17_46]], [[1.0_4_9_1, 0.8_2_8_9, 1.0_3_1_0], [1.1_0_4_4, 0.5_2_1_9, 0.8_0_5_5], [1.0_8_9_9, 0.6_9_2_6, 0.5_5_9_0]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": __snake_case : int = torch.tensor( [ [[-12.56_41, -13.47_77, -13.06_84], [-13.95_87, -15.89_83, -16.65_57], [-13.31_09, -15.73_50, -16.31_41]], [[-14.70_74, -15.43_52, -14.59_44], [-16.63_53, -18.16_63, -18.61_20], [-15.17_02, -18.03_29, -18.15_47]], [[-1.7_9_9_0, -2.0_9_5_1, -1.7_7_8_4], [-2.6_3_9_7, -3.8_2_4_5, -3.9_6_8_6], [-1.5_2_6_4, -2.8_1_2_6, -2.9_3_1_6]], ] ) else: __snake_case : Any = logits.argmax(-1 ).item() print('Predicted class:' ,model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] ,_UpperCAmelCase ,atol=1E-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) if __name__ == "__main__": A__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''segformer.b0.512x512.ade.160k''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) A__ : Optional[int] = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
352
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
0
'''simple docstring''' A__ : Any = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] A__ : Tuple = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: assert len(str(_UpperCAmelCase ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __snake_case : str = year // 1_00 __snake_case : Tuple = (5 * (century % 4) + 2) % 7 __snake_case : Any = year % 1_00 __snake_case : Optional[int] = centurian % 12 __snake_case : List[Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __snake_case : Optional[int] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) __snake_case : Dict = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
353
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) A__ : List[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[Any] = ['''MobileViTFeatureExtractor'''] A__ : Optional[int] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys A__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
354
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> str: return "\n".join( f'''{number} * {i} = {number * i}''' for i in range(1 ,number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=1_0))
355
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
0
'''simple docstring''' from __future__ import annotations from math import pow, sqrt def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ) -> dict[str, float]: if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(_UpperCAmelCase ,2 ) - pow(_UpperCAmelCase ,2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(_UpperCAmelCase ,2 ) - pow(_UpperCAmelCase ,2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(_UpperCAmelCase ,2 ) + pow(_UpperCAmelCase ,2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
356
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' import random def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Tuple = num - 1 __snake_case : str = 0 while s % 2 == 0: __snake_case : Tuple = s // 2 t += 1 for _ in range(5 ): __snake_case : List[str] = random.randrange(2 ,num - 1 ) __snake_case : Union[str, Any] = pow(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if v != 1: __snake_case : Union[str, Any] = 0 while v != (num - 1): if i == t - 1: return False else: __snake_case : Dict = i + 1 __snake_case : List[Any] = (v**2) % num return True def a_ ( _UpperCAmelCase : int ) -> bool: if num < 2: return False __snake_case : Optional[int] = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : int = 10_24 ) -> int: while True: __snake_case : Optional[int] = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) ) if is_prime_low_num(_UpperCAmelCase ): return num if __name__ == "__main__": A__ : Optional[int] = generate_large_prime() print(('''Prime number:''', num)) print(('''is_prime_low_num:''', is_prime_low_num(num)))
357
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' import inspect import unittest from transformers import MobileViTConfig 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_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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , 'hidden_sizes' ) ) self.parent.assertTrue(hasattr(__a , 'neck_hidden_sizes' ) ) self.parent.assertTrue(hasattr(__a , 'num_attention_heads' ) ) class snake_case__ : def __init__( self : Any , __a : List[str] , __a : Optional[int]=13 , __a : int=32 , __a : Tuple=2 , __a : Tuple=3 , __a : Any=640 , __a : List[str]=4 , __a : Any="silu" , __a : int=3 , __a : List[str]=32 , __a : Optional[int]=0.1 , __a : Any=0.1 , __a : List[str]=0.1 , __a : List[Any]=0.0_2 , __a : List[str]=True , __a : str=True , __a : Optional[int]=10 , __a : Optional[Any]=None , ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = parent __snake_case : List[Any] = batch_size __snake_case : int = image_size __snake_case : List[str] = patch_size __snake_case : int = num_channels __snake_case : Optional[Any] = last_hidden_size __snake_case : int = num_attention_heads __snake_case : Optional[int] = hidden_act __snake_case : Tuple = conv_kernel_size __snake_case : List[Any] = output_stride __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : List[Any] = attention_probs_dropout_prob __snake_case : Any = classifier_dropout_prob __snake_case : Any = use_labels __snake_case : Optional[int] = is_training __snake_case : Optional[int] = num_labels __snake_case : Any = initializer_range __snake_case : Union[str, Any] = scope def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : List[Any] = None __snake_case : int = None if self.use_labels: __snake_case : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __snake_case : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def A_ ( self : List[str] ) -> int: '''simple docstring''' return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def A_ ( self : str , __a : Union[str, Any] , __a : Optional[int] , __a : Optional[Any] , __a : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[Any] = MobileViTModel(config=__a ) model.to(__a ) model.eval() __snake_case : Union[str, Any] = model(__a ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A_ ( self : Optional[Any] , __a : str , __a : Dict , __a : Optional[Any] , __a : Any ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = self.num_labels __snake_case : Tuple = MobileViTForImageClassification(__a ) model.to(__a ) model.eval() __snake_case : Union[str, Any] = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A_ ( self : Dict , __a : List[Any] , __a : List[str] , __a : str , __a : Optional[int] ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = self.num_labels __snake_case : Dict = MobileViTForSemanticSegmentation(__a ) model.to(__a ) model.eval() __snake_case : Any = model(__a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __snake_case : Dict = model(__a , labels=__a ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def A_ ( self : Any ) -> Any: '''simple docstring''' __snake_case : Dict = self.prepare_config_and_inputs() __snake_case : Optional[int] = config_and_inputs __snake_case : Optional[int] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) A__ = ( { '''feature-extraction''': MobileViTModel, '''image-classification''': MobileViTForImageClassification, '''image-segmentation''': MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) A__ = False A__ = False A__ = False A__ = False def A_ ( self : Tuple ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = MobileViTModelTester(self ) __snake_case : str = MobileViTConfigTester(self , config_class=__a , has_text_modality=__a ) def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='MobileViT does not use inputs_embeds' ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' pass @unittest.skip(reason='MobileViT does not support input and output embeddings' ) def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' pass @unittest.skip(reason='MobileViT does not output attentions' ) def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' pass def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Any = model_class(__a ) __snake_case : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : List[Any] = [*signature.parameters.keys()] __snake_case : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , __a ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def A_ ( self : Optional[int] ) -> Any: '''simple docstring''' pass def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' def check_hidden_states_output(__a : Any , __a : Tuple , __a : Optional[Any] ): __snake_case : Union[str, Any] = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): __snake_case : int = model(**self._prepare_for_class(__a , __a ) ) __snake_case : int = outputs.hidden_states __snake_case : Tuple = 5 self.assertEqual(len(__a ) , __a ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __snake_case : Optional[Any] = 2 for i in range(len(__a ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : Tuple = True check_hidden_states_output(__a , __a , __a ) def A_ ( self : Optional[int] ) -> str: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) def A_ ( self : int ) -> str: '''simple docstring''' __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__a ) @slow def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Optional[int] = MobileViTModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def a_ ( ) -> List[Any]: __snake_case : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def A_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None @slow def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : Dict = MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(__a ) __snake_case : List[Any] = self.default_image_processor __snake_case : Optional[Any] = prepare_img() __snake_case : int = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): __snake_case : Optional[int] = model(**__a ) # verify the logits __snake_case : Tuple = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) __snake_case : int = torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4 ) ) @slow def A_ ( self : Any ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) __snake_case : str = model.to(__a ) __snake_case : Dict = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) __snake_case : Optional[int] = prepare_img() __snake_case : Any = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): __snake_case : int = model(**__a ) __snake_case : List[str] = outputs.logits # verify the logits __snake_case : Tuple = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , __a ) __snake_case : Union[str, Any] = torch.tensor( [ [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]], [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9_8_6_8, -9.7_1_3_2], [-11.0405, -11.0221, -10.7318]], [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]], ] , device=__a , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __a , atol=1e-4 ) ) @slow def A_ ( self : List[str] ) -> Any: '''simple docstring''' __snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) __snake_case : int = model.to(__a ) __snake_case : List[str] = MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small' ) __snake_case : str = prepare_img() __snake_case : Optional[int] = image_processor(images=__a , return_tensors='pt' ).to(__a ) # forward pass with torch.no_grad(): __snake_case : Tuple = model(**__a ) __snake_case : Tuple = outputs.logits.detach().cpu() __snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=__a , target_sizes=[(50, 60)] ) __snake_case : Tuple = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , __a ) __snake_case : Optional[int] = image_processor.post_process_semantic_segmentation(outputs=__a ) __snake_case : Dict = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , __a )
358
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
0
'''simple docstring''' import os from datetime import datetime as dt from github import Github A__ : Union[str, Any] = [ '''good first issue''', '''feature request''', '''wip''', ] def a_ ( ) -> Optional[int]: __snake_case : List[str] = Github(os.environ['GITHUB_TOKEN'] ) __snake_case : Any = g.get_repo('huggingface/accelerate' ) __snake_case : List[Any] = repo.get_issues(state='open' ) for issue in open_issues: __snake_case : Tuple = sorted([comment for comment in issue.get_comments()] ,key=lambda _UpperCAmelCase : i.created_at ,reverse=_UpperCAmelCase ) __snake_case : Tuple = comments[0] if len(_UpperCAmelCase ) > 0 else None __snake_case : Dict = dt.utcnow() __snake_case : Dict = (current_time - issue.updated_at).days __snake_case : str = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state='closed' ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
359
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
360
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging A__ : List[str] = logging.get_logger(__name__) A__ : str = { '''bigscience/bloom''': '''https://huggingface.co/bigscience/bloom/resolve/main/config.json''', '''bigscience/bloom-560m''': '''https://huggingface.co/bigscience/bloom-560m/blob/main/config.json''', '''bigscience/bloom-1b1''': '''https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json''', '''bigscience/bloom-1b7''': '''https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json''', '''bigscience/bloom-3b''': '''https://huggingface.co/bigscience/bloom-3b/blob/main/config.json''', '''bigscience/bloom-7b1''': '''https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''bloom''' A__ = ['''past_key_values'''] A__ = { '''num_hidden_layers''': '''n_layer''', '''num_attention_heads''': '''n_head''', } def __init__( self : Optional[int] , __a : Optional[Any]=250880 , __a : Union[str, Any]=64 , __a : Any=2 , __a : Optional[int]=8 , __a : List[Any]=1e-5 , __a : List[Any]=0.0_2 , __a : Union[str, Any]=True , __a : Dict=1 , __a : str=2 , __a : Optional[int]=False , __a : List[str]=0.0 , __a : Union[str, Any]=0.0 , __a : Optional[int]=1 , __a : Tuple=False , **__a : Optional[int] , ) -> Optional[Any]: '''simple docstring''' __snake_case : str = vocab_size # Backward compatibility with n_embed kwarg __snake_case : str = kwargs.pop('n_embed' , __a ) __snake_case : Any = hidden_size if n_embed is None else n_embed __snake_case : Any = n_layer __snake_case : Union[str, Any] = n_head __snake_case : Optional[Any] = layer_norm_epsilon __snake_case : List[str] = initializer_range __snake_case : Dict = use_cache __snake_case : Union[str, Any] = pretraining_tp __snake_case : str = apply_residual_connection_post_layernorm __snake_case : Union[str, Any] = hidden_dropout __snake_case : Tuple = attention_dropout __snake_case : Dict = bos_token_id __snake_case : Optional[Any] = eos_token_id __snake_case : Any = slow_but_exact super().__init__(bos_token_id=__a , eos_token_id=__a , **__a ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = version.parse('''1.12''' ) def __init__( self : List[Any] , __a : PretrainedConfig , __a : str = "default" , __a : List[PatchingSpec] = None , __a : bool = False , ) -> Optional[int]: '''simple docstring''' super().__init__(__a , task=__a , patching_specs=__a , use_past=__a ) if not getattr(self._config , 'pad_token_id' , __a ): # TODO: how to do that better? __snake_case : Optional[int] = 0 @property def A_ ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : int = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(__a , direction='inputs' , inverted_values_shape=__a ) __snake_case : str = {0: 'batch', 1: 'past_sequence + sequence'} else: __snake_case : Optional[Any] = {0: 'batch', 1: 'sequence'} return common_inputs @property def A_ ( self : Tuple ) -> int: '''simple docstring''' return self._config.n_layer @property def A_ ( self : Any ) -> int: '''simple docstring''' return self._config.n_head @property def A_ ( self : Tuple ) -> float: '''simple docstring''' return 1e-3 def A_ ( self : Tuple , __a : "PreTrainedTokenizer" , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional["TensorType"] = None , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case : List[Any] = super(__a , self ).generate_dummy_inputs( __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a ) # We need to order the input in the way they appears in the forward() __snake_case : Any = 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 __snake_case : str = common_inputs['input_ids'].shape # Not using the same length for past_key_values __snake_case : Tuple = seqlen + 2 __snake_case : str = self._config.hidden_size // self.num_attention_heads __snake_case : Dict = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) __snake_case : List[Any] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) __snake_case : List[Any] = [ (torch.zeros(__a ), torch.zeros(__a )) for _ in range(self.num_layers ) ] __snake_case : int = common_inputs['attention_mask'] if self.use_past: __snake_case : int = ordered_inputs['attention_mask'].dtype __snake_case : Optional[int] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(__a , __a , dtype=__a )] , dim=1 ) return ordered_inputs @property def A_ ( self : Optional[int] ) -> int: '''simple docstring''' return 13
361
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class snake_case__ : # setable values A__ = None A__ = None A__ = None # sigma(t_i) @classmethod def A_ ( cls : Optional[int] ) -> List[str]: '''simple docstring''' return cls() @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = 42 A__ = 42 class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return True @register_to_config def __init__( self : Any , __a : float = 0.0_2 , __a : float = 100 , __a : float = 1.0_0_7 , __a : float = 80 , __a : float = 0.0_5 , __a : float = 50 , ) -> Dict: '''simple docstring''' pass def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' return KarrasVeSchedulerState.create() def A_ ( self : Dict , __a : KarrasVeSchedulerState , __a : int , __a : Tuple = () ) -> KarrasVeSchedulerState: '''simple docstring''' __snake_case : Dict = jnp.arange(0 , __a )[::-1].copy() __snake_case : List[Any] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=__a , schedule=jnp.array(__a , dtype=jnp.floataa ) , timesteps=__a , ) def A_ ( self : List[Any] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : random.KeyArray , ) -> Tuple[jnp.ndarray, float]: '''simple docstring''' if self.config.s_min <= sigma <= self.config.s_max: __snake_case : Union[str, Any] = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: __snake_case : Optional[Any] = 0 # sample eps ~ N(0, S_noise^2 * I) __snake_case : Optional[int] = random.split(__a , num=1 ) __snake_case : List[str] = self.config.s_noise * random.normal(key=__a , shape=sample.shape ) __snake_case : Optional[Any] = sigma + gamma * sigma __snake_case : Dict = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def A_ ( self : List[str] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' __snake_case : Union[str, Any] = sample_hat + sigma_hat * model_output __snake_case : str = (sample_hat - pred_original_sample) / sigma_hat __snake_case : int = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def A_ ( self : Tuple , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : jnp.ndarray , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: '''simple docstring''' __snake_case : Union[str, Any] = sample_prev + sigma_prev * model_output __snake_case : Optional[int] = (sample_prev - pred_original_sample) / sigma_prev __snake_case : Tuple = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a ) def A_ ( self : Dict , __a : KarrasVeSchedulerState , __a : Any , __a : Dict , __a : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError()
362
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : str = logging.get_logger(__name__) A__ : Dict = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''', # See all CANINE models at https://huggingface.co/models?filter=canine } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''canine''' def __init__( self : Optional[int] , __a : Union[str, Any]=768 , __a : Optional[int]=12 , __a : Optional[int]=12 , __a : List[str]=3072 , __a : List[str]="gelu" , __a : Union[str, Any]=0.1 , __a : str=0.1 , __a : List[str]=16384 , __a : Union[str, Any]=16 , __a : List[Any]=0.0_2 , __a : List[Any]=1e-12 , __a : List[str]=0 , __a : Dict=0Xe_0_0_0 , __a : List[str]=0Xe_0_0_1 , __a : Union[str, Any]=4 , __a : Dict=4 , __a : Optional[int]=8 , __a : Tuple=16384 , __a : Optional[int]=128 , **__a : int , ) -> List[Any]: '''simple docstring''' super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) __snake_case : Union[str, Any] = max_position_embeddings __snake_case : Dict = hidden_size __snake_case : Union[str, Any] = num_hidden_layers __snake_case : Tuple = num_attention_heads __snake_case : List[Any] = intermediate_size __snake_case : str = hidden_act __snake_case : Union[str, Any] = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : Optional[Any] = initializer_range __snake_case : int = type_vocab_size __snake_case : Any = layer_norm_eps # Character config: __snake_case : Optional[int] = downsampling_rate __snake_case : List[str] = upsampling_kernel_size __snake_case : List[Any] = num_hash_functions __snake_case : List[Any] = num_hash_buckets __snake_case : Any = local_transformer_stride
363
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : Optional[int] = { '''edbeeching/decision-transformer-gym-hopper-medium''': ( '''https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json''' ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''decision_transformer''' A__ = ['''past_key_values'''] A__ = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : str , __a : Union[str, Any]=17 , __a : Dict=4 , __a : str=128 , __a : Tuple=4096 , __a : str=True , __a : List[str]=1 , __a : Optional[Any]=1024 , __a : Any=3 , __a : List[str]=1 , __a : str=None , __a : Union[str, Any]="relu" , __a : Optional[Any]=0.1 , __a : str=0.1 , __a : List[str]=0.1 , __a : Any=1e-5 , __a : Dict=0.0_2 , __a : str=True , __a : str=True , __a : List[str]=50256 , __a : Any=50256 , __a : str=False , __a : List[str]=False , **__a : List[str] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[Any] = state_dim __snake_case : Dict = act_dim __snake_case : Optional[int] = hidden_size __snake_case : int = max_ep_len __snake_case : Tuple = action_tanh __snake_case : str = vocab_size __snake_case : Tuple = n_positions __snake_case : Optional[Any] = n_layer __snake_case : int = n_head __snake_case : List[str] = n_inner __snake_case : List[Any] = activation_function __snake_case : Optional[Any] = resid_pdrop __snake_case : List[str] = embd_pdrop __snake_case : List[Any] = attn_pdrop __snake_case : Any = layer_norm_epsilon __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = scale_attn_weights __snake_case : str = use_cache __snake_case : List[Any] = scale_attn_by_inverse_layer_idx __snake_case : Optional[int] = reorder_and_upcast_attn __snake_case : Dict = bos_token_id __snake_case : Tuple = eos_token_id super().__init__(bos_token_id=__a , eos_token_id=__a , **__a )
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' from math import sqrt def a_ ( _UpperCAmelCase : int ) -> bool: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' must been an int and positive" __snake_case : Tuple = True # 0 and 1 are none primes. if number <= 1: __snake_case : Dict = False for divisor in range(2 ,int(round(sqrt(_UpperCAmelCase ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: __snake_case : str = False break # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'status' must been from type bool" return status def a_ ( _UpperCAmelCase : Optional[int] ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N __snake_case : Union[str, Any] = list(range(2 ,n + 1 ) ) __snake_case : Tuple = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(_UpperCAmelCase ) ): for j in range(i + 1 ,len(_UpperCAmelCase ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): __snake_case : Dict = 0 # filters actual prime numbers. __snake_case : Optional[Any] = [x for x in begin_list if x != 0] # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n > 2), "'N' must been an int and > 2" __snake_case : Union[str, Any] = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 ,n + 1 ): if is_prime(_UpperCAmelCase ): ans.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Any ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and number >= 0, "'number' must been an int and >= 0" __snake_case : Any = [] # this list will be returns of the function. # potential prime number factors. __snake_case : Any = 2 __snake_case : Union[str, Any] = number if number == 0 or number == 1: ans.append(_UpperCAmelCase ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(_UpperCAmelCase ): while quotient != 1: if is_prime(_UpperCAmelCase ) and (quotient % factor == 0): ans.append(_UpperCAmelCase ) quotient /= factor else: factor += 1 else: ans.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type list" return ans def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" __snake_case : Optional[Any] = 0 # prime factorization of 'number' __snake_case : Dict = prime_factorization(_UpperCAmelCase ) __snake_case : Union[str, Any] = max(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type int" return ans def a_ ( _UpperCAmelCase : List[Any] ) -> str: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number >= 0 ), "'number' bust been an int and >= 0" __snake_case : List[str] = 0 # prime factorization of 'number' __snake_case : int = prime_factorization(_UpperCAmelCase ) __snake_case : int = min(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'ans' must been from type int" return ans def a_ ( _UpperCAmelCase : List[str] ) -> Any: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'number' must been an int" assert isinstance(number % 2 == 0 ,_UpperCAmelCase ), "compare bust been from type bool" return number % 2 == 0 def a_ ( _UpperCAmelCase : str ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ), "'number' must been an int" assert isinstance(number % 2 != 0 ,_UpperCAmelCase ), "compare bust been from type bool" return number % 2 != 0 def a_ ( _UpperCAmelCase : Tuple ) -> Tuple: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (number > 2) and is_even(_UpperCAmelCase ) ), "'number' must been an int, even and > 2" __snake_case : Optional[Any] = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' __snake_case : List[str] = get_prime_numbers(_UpperCAmelCase ) __snake_case : Optional[Any] = len(_UpperCAmelCase ) # run variable for while-loops. __snake_case : Any = 0 __snake_case : Tuple = None # exit variable. for break up the loops __snake_case : Optional[int] = True while i < len_pn and loop: __snake_case : Union[str, Any] = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: __snake_case : Optional[int] = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (len(_UpperCAmelCase ) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0] ) and is_prime(ans[1] ) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." __snake_case : Optional[Any] = 0 while numbera != 0: __snake_case : Tuple = numbera % numbera __snake_case : Any = numbera __snake_case : Tuple = rest # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ) -> Any: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." __snake_case : Any = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' __snake_case : Optional[int] = prime_factorization(_UpperCAmelCase ) __snake_case : Dict = prime_factorization(_UpperCAmelCase ) elif numbera == 1 or numbera == 1: __snake_case : Union[str, Any] = [] __snake_case : Union[str, Any] = [] __snake_case : List[str] = max(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : Union[str, Any] = 0 __snake_case : str = 0 __snake_case : Optional[int] = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: __snake_case : Optional[Any] = prime_fac_a.count(_UpperCAmelCase ) __snake_case : Optional[int] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(max(_UpperCAmelCase ,_UpperCAmelCase ) ): ans *= n else: __snake_case : List[str] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ): ans *= n done.append(_UpperCAmelCase ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: __snake_case : List[Any] = prime_fac_a.count(_UpperCAmelCase ) for _ in range(_UpperCAmelCase ): ans *= n done.append(_UpperCAmelCase ) # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def a_ ( _UpperCAmelCase : Tuple ) -> Union[str, Any]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'number' must been a positive int" __snake_case : int = 0 __snake_case : Tuple = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(_UpperCAmelCase ): ans += 1 # precondition assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and is_prime( _UpperCAmelCase ), "'ans' must been a prime number and from type int" return ans def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[Any] ) -> List[str]: assert ( is_prime(_UpperCAmelCase ) and is_prime(_UpperCAmelCase ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" __snake_case : Any = p_number_a + 1 # jump to the next number __snake_case : List[Any] = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(_UpperCAmelCase ): number += 1 while number < p_number_a: ans.append(_UpperCAmelCase ) number += 1 # fetch the next prime number. while not is_prime(_UpperCAmelCase ): number += 1 # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ans[0] != p_number_a and ans[len(_UpperCAmelCase ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def a_ ( _UpperCAmelCase : Any ) -> str: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 1), "'n' must been int and >= 1" __snake_case : Union[str, Any] = [] # will be returned. for divisor in range(1 ,n + 1 ): if n % divisor == 0: ans.append(_UpperCAmelCase ) # precondition assert ans[0] == 1 and ans[len(_UpperCAmelCase ) - 1] == n, "Error in function getDivisiors(...)" return ans def a_ ( _UpperCAmelCase : List[Any] ) -> List[str]: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and ( number > 1 ), "'number' must been an int and >= 1" __snake_case : Tuple = get_divisors(_UpperCAmelCase ) # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (divisors[0] == 1) and (divisors[len(_UpperCAmelCase ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str] ) -> Tuple: assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. __snake_case : Optional[int] = gcd(abs(_UpperCAmelCase ) ,abs(_UpperCAmelCase ) ) # precondition assert ( isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) def a_ ( _UpperCAmelCase : int ) -> int: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'n' must been a int and >= 0" __snake_case : List[str] = 1 # this will be return. for factor in range(1 ,n + 1 ): ans *= factor return ans def a_ ( _UpperCAmelCase : str ) -> Dict: assert isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and (n >= 0), "'n' must been an int and >= 0" __snake_case : int = 0 __snake_case : List[str] = 1 __snake_case : Optional[Any] = 1 # this will be return for _ in range(n - 1 ): __snake_case : Dict = ans ans += fiba __snake_case : Dict = tmp return ans
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
0
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract A__ : int = logging.get_logger(__name__) def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Union[str, Any] ) -> int: return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def a_ ( _UpperCAmelCase : np.ndarray ,_UpperCAmelCase : Optional[str] ,_UpperCAmelCase : Optional[str] = None ) -> List[Any]: __snake_case : int = tesseract_config if tesseract_config is not None else '' # apply OCR __snake_case : List[str] = to_pil_image(_UpperCAmelCase ) __snake_case : str = pil_image.size __snake_case : Optional[Any] = pytesseract.image_to_data(_UpperCAmelCase ,lang=_UpperCAmelCase ,output_type='dict' ,config=_UpperCAmelCase ) __snake_case : Tuple = data['text'], data['left'], data['top'], data['width'], data['height'] # filter empty words and corresponding coordinates __snake_case : Dict = [idx for idx, word in enumerate(_UpperCAmelCase ) if not word.strip()] __snake_case : Tuple = [word for idx, word in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __snake_case : Any = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __snake_case : int = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __snake_case : Union[str, Any] = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] __snake_case : List[Any] = [coord for idx, coord in enumerate(_UpperCAmelCase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format __snake_case : Tuple = [] for x, y, w, h in zip(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Any = [x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase ) # finally, normalize the bounding boxes __snake_case : Optional[Any] = [] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) assert len(_UpperCAmelCase ) == len(_UpperCAmelCase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = ['''pixel_values'''] def __init__( self : Any , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BILINEAR , __a : bool = True , __a : Optional[str] = None , __a : Optional[str] = "" , **__a : List[Any] , ) -> None: '''simple docstring''' super().__init__(**__a ) __snake_case : List[Any] = size if size is not None else {'height': 224, 'width': 224} __snake_case : List[Any] = get_size_dict(__a ) __snake_case : List[Any] = do_resize __snake_case : Dict = size __snake_case : Dict = resample __snake_case : Dict = apply_ocr __snake_case : List[Any] = ocr_lang __snake_case : List[str] = tesseract_config def A_ ( self : Dict , __a : np.ndarray , __a : Dict[str, int] , __a : PILImageResampling = PILImageResampling.BILINEAR , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[Any] , ) -> np.ndarray: '''simple docstring''' __snake_case : Union[str, Any] = get_size_dict(__a ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) __snake_case : Dict = (size['height'], size['width']) return resize(__a , size=__a , resample=__a , data_format=__a , **__a ) def A_ ( self : Optional[Any] , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : Optional[str] = None , __a : Optional[str] = None , __a : Optional[Union[str, TensorType]] = None , __a : ChannelDimension = ChannelDimension.FIRST , **__a : Any , ) -> PIL.Image.Image: '''simple docstring''' __snake_case : int = do_resize if do_resize is not None else self.do_resize __snake_case : Optional[int] = size if size is not None else self.size __snake_case : Tuple = get_size_dict(__a ) __snake_case : List[Any] = resample if resample is not None else self.resample __snake_case : Union[str, Any] = apply_ocr if apply_ocr is not None else self.apply_ocr __snake_case : Any = ocr_lang if ocr_lang is not None else self.ocr_lang __snake_case : Tuple = tesseract_config if tesseract_config is not None else self.tesseract_config __snake_case : Tuple = make_list_of_images(__a ) if not valid_images(__a ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) # All transformations expect numpy arrays. __snake_case : List[Any] = [to_numpy_array(__a ) for image in images] if apply_ocr: requires_backends(self , 'pytesseract' ) __snake_case : List[Any] = [] __snake_case : Union[str, Any] = [] for image in images: __snake_case : Optional[Any] = apply_tesseract(__a , __a , __a ) words_batch.append(__a ) boxes_batch.append(__a ) if do_resize: __snake_case : Any = [self.resize(image=__a , size=__a , resample=__a ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) __snake_case : List[Any] = [flip_channel_order(__a ) for image in images] __snake_case : Dict = [to_channel_dimension_format(__a , __a ) for image in images] __snake_case : Optional[Any] = BatchFeature(data={'pixel_values': images} , tensor_type=__a ) if apply_ocr: __snake_case : int = words_batch __snake_case : List[str] = boxes_batch return data
366
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list[int]: if num <= 0: raise ValueError('Input must be a positive integer' ) __snake_case : Tuple = [True] * (num + 1) __snake_case : Tuple = 2 while p * p <= num: if primes[p]: for i in range(p * p ,num + 1 ,_UpperCAmelCase ): __snake_case : str = False p += 1 return [prime for prime in range(2 ,num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() A__ : Any = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
367
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
0
'''simple docstring''' from __future__ import annotations A__ : Tuple = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] A__ : str = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def a_ ( _UpperCAmelCase : list[float] ) -> list[float]: __snake_case : Optional[Any] = [] __snake_case : Optional[int] = len(_UpperCAmelCase ) for i in range(_UpperCAmelCase ): __snake_case : float = -1 for j in range(i + 1 ,_UpperCAmelCase ): if arr[i] < arr[j]: __snake_case : Dict = arr[j] break result.append(_UpperCAmelCase ) return result def a_ ( _UpperCAmelCase : list[float] ) -> list[float]: __snake_case : Tuple = [] for i, outer in enumerate(_UpperCAmelCase ): __snake_case : float = -1 for inner in arr[i + 1 :]: if outer < inner: __snake_case : Union[str, Any] = inner break result.append(_UpperCAmelCase ) return result def a_ ( _UpperCAmelCase : list[float] ) -> list[float]: __snake_case : List[str] = len(_UpperCAmelCase ) __snake_case : list[float] = [] __snake_case : list[float] = [-1] * arr_size for index in reversed(range(_UpperCAmelCase ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: __snake_case : Any = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) A__ : Tuple = ( '''from __main__ import arr, next_greatest_element_slow, ''' '''next_greatest_element_fast, next_greatest_element''' ) print( '''next_greatest_element_slow():''', timeit('''next_greatest_element_slow(arr)''', setup=setup), ) print( '''next_greatest_element_fast():''', timeit('''next_greatest_element_fast(arr)''', setup=setup), ) print( ''' next_greatest_element():''', timeit('''next_greatest_element(arr)''', setup=setup), )
368
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
0
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values A__ = argparse.ArgumentParser() parser.add_argument('''--user''', type=str, default='''ubuntu''') parser.add_argument('''--host''', type=str, default='''localhost''') parser.add_argument('''--key_path''', type=str, default=None) parser.add_argument('''--instance''', type=str, default='''V100:1''') parser.add_argument('''--provider''', type=str, default='''cheapest''') parser.add_argument('''--use_spot''', type=bool, default=False) parser.add_argument('''--example''', type=str, default='''pytorch/text-generation/run_generation.py''') A__ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError('''Cannot specify both BYO and on-demand cluster args''') A__ = rh.cluster( name='''rh-cluster''', ips=[args.host], ssh_creds={'''ssh_user''': args.user, '''ssh_private_key''': args.key_path} ) else: A__ = rh.cluster( name='''rh-cluster''', instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) A__ = args.example.rsplit('''/''', 1)[0] # Set up remote environment cluster.install_packages(['''pip:./''']) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([F"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(['''pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117''']) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([F"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
369
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
0
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig A__ : Optional[Any] = logging.get_logger(__name__) # General docstring A__ : List[str] = '''PoolFormerConfig''' # Base docstring A__ : List[Any] = '''sail/poolformer_s12''' A__ : Optional[int] = [1, 5_1_2, 7, 7] # Image classification docstring A__ : str = '''sail/poolformer_s12''' A__ : List[Any] = '''tabby, tabby cat''' A__ : Union[str, Any] = [ '''sail/poolformer_s12''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : float = 0.0 ,_UpperCAmelCase : bool = False ) -> int: if drop_prob == 0.0 or not training: return input __snake_case : List[str] = 1 - drop_prob __snake_case : int = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets __snake_case : Optional[Any] = keep_prob + torch.rand(_UpperCAmelCase ,dtype=input.dtype ,device=input.device ) random_tensor.floor_() # binarize __snake_case : Any = input.div(_UpperCAmelCase ) * random_tensor return output class snake_case__ ( nn.Module ): def __init__( self : str , __a : Optional[float] = None ): '''simple docstring''' super().__init__() __snake_case : int = drop_prob def A_ ( self : Any , __a : torch.Tensor ): '''simple docstring''' return drop_path(__a , self.drop_prob , self.training ) def A_ ( self : Any ): '''simple docstring''' return "p={}".format(self.drop_prob ) class snake_case__ ( nn.Module ): def __init__( self : Optional[int] , __a : int , __a : int , __a : List[str] , __a : Dict , __a : Dict , __a : str=None ): '''simple docstring''' super().__init__() __snake_case : Union[str, Any] = patch_size if isinstance(__a , collections.abc.Iterable ) else (patch_size, patch_size) __snake_case : int = stride if isinstance(__a , collections.abc.Iterable ) else (stride, stride) __snake_case : str = padding if isinstance(__a , collections.abc.Iterable ) else (padding, padding) __snake_case : str = nn.Convad(__a , __a , kernel_size=__a , stride=__a , padding=__a ) __snake_case : Tuple = norm_layer(__a ) if norm_layer else nn.Identity() def A_ ( self : Optional[Any] , __a : int ): '''simple docstring''' __snake_case : str = self.projection(__a ) __snake_case : int = self.norm(__a ) return embeddings class snake_case__ ( nn.GroupNorm ): def __init__( self : List[Any] , __a : List[str] , **__a : Any ): '''simple docstring''' super().__init__(1 , __a , **__a ) class snake_case__ ( nn.Module ): def __init__( self : str , __a : Dict ): '''simple docstring''' super().__init__() __snake_case : Dict = nn.AvgPoolad(__a , stride=1 , padding=pool_size // 2 , count_include_pad=__a ) def A_ ( self : Any , __a : Dict ): '''simple docstring''' return self.pool(__a ) - hidden_states class snake_case__ ( nn.Module ): def __init__( self : Dict , __a : Union[str, Any] , __a : Tuple , __a : List[str] , __a : int ): '''simple docstring''' super().__init__() __snake_case : str = nn.Convad(__a , __a , 1 ) __snake_case : Optional[int] = nn.Convad(__a , __a , 1 ) __snake_case : Union[str, Any] = PoolFormerDropPath(__a ) if isinstance(config.hidden_act , __a ): __snake_case : Union[str, Any] = ACTaFN[config.hidden_act] else: __snake_case : Dict = config.hidden_act def A_ ( self : List[Any] , __a : List[str] ): '''simple docstring''' __snake_case : int = self.conva(__a ) __snake_case : Tuple = self.act_fn(__a ) __snake_case : Optional[Any] = self.drop(__a ) __snake_case : Optional[int] = self.conva(__a ) __snake_case : int = self.drop(__a ) return hidden_states class snake_case__ ( nn.Module ): def __init__( self : str , __a : Dict , __a : Optional[int] , __a : Any , __a : Any , __a : List[str] , __a : Dict ): '''simple docstring''' super().__init__() __snake_case : Tuple = PoolFormerPooling(__a ) __snake_case : Dict = PoolFormerOutput(__a , __a , __a , __a ) __snake_case : str = PoolFormerGroupNorm(__a ) __snake_case : Optional[int] = PoolFormerGroupNorm(__a ) # Useful for training neural nets __snake_case : Dict = PoolFormerDropPath(__a ) if drop_path > 0.0 else nn.Identity() __snake_case : Union[str, Any] = config.use_layer_scale if config.use_layer_scale: __snake_case : List[str] = nn.Parameter( config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a ) __snake_case : Any = nn.Parameter( config.layer_scale_init_value * torch.ones((__a) ) , requires_grad=__a ) def A_ ( self : Any , __a : List[str] ): '''simple docstring''' if self.use_layer_scale: __snake_case : Union[str, Any] = self.pooling(self.before_norm(__a ) ) __snake_case : Union[str, Any] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection __snake_case : Tuple = hidden_states + self.drop_path(__a ) __snake_case : Union[str, Any] = () __snake_case : Optional[Any] = self.output(self.after_norm(__a ) ) __snake_case : str = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection __snake_case : Optional[Any] = hidden_states + self.drop_path(__a ) __snake_case : str = (output,) + outputs return outputs else: __snake_case : List[Any] = self.drop_path(self.pooling(self.before_norm(__a ) ) ) # First residual connection __snake_case : List[Any] = pooling_output + hidden_states __snake_case : Optional[Any] = () # Second residual connection inside the PoolFormerOutput block __snake_case : Union[str, Any] = self.drop_path(self.output(self.after_norm(__a ) ) ) __snake_case : Union[str, Any] = hidden_states + layer_output __snake_case : Optional[Any] = (output,) + outputs return outputs class snake_case__ ( nn.Module ): def __init__( self : Union[str, Any] , __a : str ): '''simple docstring''' super().__init__() __snake_case : Union[str, Any] = config # stochastic depth decay rule __snake_case : List[Any] = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings __snake_case : List[str] = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) __snake_case : List[Any] = nn.ModuleList(__a ) # Transformer blocks __snake_case : Dict = [] __snake_case : Optional[Any] = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers __snake_case : Optional[Any] = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( __a , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(__a ) ) __snake_case : Dict = nn.ModuleList(__a ) def A_ ( self : Union[str, Any] , __a : str , __a : Optional[Any]=False , __a : List[Any]=True ): '''simple docstring''' __snake_case : List[str] = () if output_hidden_states else None __snake_case : Any = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): __snake_case : str = layers # Get patch embeddings from hidden_states __snake_case : List[Any] = embedding_layer(__a ) # Send the embeddings through the blocks for _, blk in enumerate(__a ): __snake_case : str = blk(__a ) __snake_case : Tuple = layer_outputs[0] if output_hidden_states: __snake_case : List[str] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=__a , hidden_states=__a ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = PoolFormerConfig A__ = '''poolformer''' A__ = '''pixel_values''' A__ = True def A_ ( self : List[str] , __a : Optional[Any] ): '''simple docstring''' if isinstance(__a , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(__a , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def A_ ( self : int , __a : Optional[Any] , __a : Dict=False ): '''simple docstring''' if isinstance(__a , __a ): __snake_case : List[Any] = value A__ : str = R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' A__ : Dict = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. ''' @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE_ , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : int , __a : List[str] ): '''simple docstring''' super().__init__(__a ) __snake_case : int = config __snake_case : Optional[int] = PoolFormerEncoder(__a ) # Initialize weights and apply final processing self.post_init() def A_ ( self : List[Any] ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__a , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def A_ ( self : Optional[Any] , __a : Optional[torch.FloatTensor] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , ): '''simple docstring''' __snake_case : str = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('You have to specify pixel_values' ) __snake_case : str = self.encoder( __a , output_hidden_states=__a , return_dict=__a , ) __snake_case : Union[str, Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=__a , hidden_states=encoder_outputs.hidden_states , ) class snake_case__ ( nn.Module ): def __init__( self : Optional[int] , __a : List[str] ): '''simple docstring''' super().__init__() __snake_case : str = nn.Linear(config.hidden_size , config.hidden_size ) def A_ ( self : Dict , __a : Optional[Any] ): '''simple docstring''' __snake_case : Any = self.dense(__a ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , SCREAMING_SNAKE_CASE_ , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ): '''simple docstring''' super().__init__(__a ) __snake_case : Any = config.num_labels __snake_case : List[str] = PoolFormerModel(__a ) # Final norm __snake_case : Union[str, Any] = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head __snake_case : Tuple = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(__a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def A_ ( self : Tuple , __a : Optional[torch.FloatTensor] = None , __a : Optional[torch.LongTensor] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , ): '''simple docstring''' __snake_case : Tuple = return_dict if return_dict is not None else self.config.use_return_dict __snake_case : List[str] = self.poolformer( __a , output_hidden_states=__a , return_dict=__a , ) __snake_case : Optional[Any] = outputs[0] __snake_case : str = self.classifier(self.norm(__a ).mean([-2, -1] ) ) __snake_case : Tuple = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __snake_case : List[str] = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __snake_case : Dict = 'single_label_classification' else: __snake_case : Tuple = 'multi_label_classification' if self.config.problem_type == "regression": __snake_case : Any = MSELoss() if self.num_labels == 1: __snake_case : Dict = loss_fct(logits.squeeze() , labels.squeeze() ) else: __snake_case : Any = loss_fct(__a , __a ) elif self.config.problem_type == "single_label_classification": __snake_case : int = CrossEntropyLoss() __snake_case : Tuple = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __snake_case : Optional[Any] = BCEWithLogitsLoss() __snake_case : str = loss_fct(__a , __a ) if not return_dict: __snake_case : Dict = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=__a , logits=__a , hidden_states=outputs.hidden_states )
370
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Union[str, Any] = logging.get_logger(__name__) A__ : Optional[int] = { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''lxmert''' A__ = {} def __init__( self : Optional[int] , __a : List[str]=30522 , __a : int=768 , __a : List[str]=12 , __a : int=9500 , __a : Optional[Any]=1600 , __a : str=400 , __a : str=3072 , __a : Optional[Any]="gelu" , __a : Optional[int]=0.1 , __a : List[str]=0.1 , __a : Tuple=512 , __a : List[Any]=2 , __a : List[Any]=0.0_2 , __a : Union[str, Any]=1e-12 , __a : Optional[Any]=9 , __a : Union[str, Any]=5 , __a : List[Any]=5 , __a : Optional[Any]=2048 , __a : int=4 , __a : List[Any]=6.6_7 , __a : Optional[int]=True , __a : Tuple=True , __a : Dict=True , __a : Tuple=True , __a : Optional[Any]=True , __a : Optional[int]=True , __a : int=True , **__a : Dict , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : int = hidden_size __snake_case : Union[str, Any] = num_attention_heads __snake_case : Union[str, Any] = hidden_act __snake_case : Tuple = intermediate_size __snake_case : Any = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : Any = max_position_embeddings __snake_case : str = type_vocab_size __snake_case : Optional[int] = initializer_range __snake_case : Any = layer_norm_eps __snake_case : List[Any] = num_qa_labels __snake_case : List[str] = num_object_labels __snake_case : Any = num_attr_labels __snake_case : str = l_layers __snake_case : List[str] = x_layers __snake_case : int = r_layers __snake_case : Optional[Any] = visual_feat_dim __snake_case : Any = visual_pos_dim __snake_case : List[Any] = visual_loss_normalizer __snake_case : int = task_matched __snake_case : str = task_mask_lm __snake_case : int = task_obj_predict __snake_case : Optional[Any] = task_qa __snake_case : Tuple = visual_obj_loss __snake_case : Any = visual_attr_loss __snake_case : Any = visual_feat_loss __snake_case : List[str] = {'vision': r_layers, 'cross_encoder': x_layers, 'language': l_layers} super().__init__(**__a )
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
0
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : """simple docstring""" def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
'''simple docstring''' import math import tensorflow as tf from packaging import version def a_ ( _UpperCAmelCase : Optional[Any] ) -> Union[str, Any]: __snake_case : Optional[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : str = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) ,x.dtype ) )) return x * cdf def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : Dict = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : List[Any] = tf.cast(math.pi ,x.dtype ) __snake_case : List[str] = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) __snake_case : Optional[Any] = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(_UpperCAmelCase ,3 )) )) return x * cdf def a_ ( _UpperCAmelCase : Optional[int] ) -> Optional[Any]: __snake_case : Any = tf.convert_to_tensor(_UpperCAmelCase ) return x * tf.tanh(tf.math.softplus(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : str ) -> Dict: __snake_case : Optional[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : List[Any] = tf.cast(0.0_4_4_7_1_5 ,x.dtype ) __snake_case : List[str] = tf.cast(0.7_9_7_8_8_4_5_6_0_8 ,x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def a_ ( _UpperCAmelCase : Dict ) -> Optional[int]: __snake_case : List[Any] = tf.convert_to_tensor(_UpperCAmelCase ) __snake_case : str = tf.cast(1.7_0_2 ,x.dtype ) return x * tf.math.sigmoid(coeff * x ) def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: return tf.clip_by_value(_gelu(_UpperCAmelCase ) ,-10 ,10 ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : str=-1 ) -> Dict: __snake_case : Dict = tf.split(_UpperCAmelCase ,2 ,axis=_UpperCAmelCase ) return a * tf.math.sigmoid(_UpperCAmelCase ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def a_ ( _UpperCAmelCase : int ) -> Dict: return tf.keras.activations.gelu(_UpperCAmelCase ,approximate=_UpperCAmelCase ) A__ : List[Any] = tf.keras.activations.gelu A__ : str = approximate_gelu_wrap else: A__ : List[str] = _gelu A__ : List[str] = _gelu_new A__ : str = { '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def a_ ( _UpperCAmelCase : int ) -> int: if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor A__ : Optional[Any] = logging.get_logger(__name__) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , *__a : Optional[Any] , **__a : List[str] ) -> None: '''simple docstring''' warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , __a , ) super().__init__(*__a , **__a )
352
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
0
'''simple docstring''' import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, Any]=[] ) -> str: __snake_case : Any = size[0] - overlap_pixels * 2 __snake_case : List[str] = size[1] - overlap_pixels * 2 for letter in ["l", "r"]: if letter in remove_borders: size_x += overlap_pixels for letter in ["t", "b"]: if letter in remove_borders: size_y += overlap_pixels __snake_case : Any = np.ones((size_y, size_x) ,dtype=np.uinta ) * 2_55 __snake_case : Optional[Any] = np.pad(_UpperCAmelCase ,mode='linear_ramp' ,pad_width=_UpperCAmelCase ,end_values=0 ) if "l" in remove_borders: __snake_case : Dict = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: __snake_case : Tuple = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: __snake_case : Any = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: __snake_case : Tuple = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Dict ) -> Union[str, Any]: return max(_UpperCAmelCase ,min(_UpperCAmelCase ,_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : [int] ,_UpperCAmelCase : [int] ,_UpperCAmelCase : [int] ) -> Optional[Any]: return ( clamp(rect[0] ,min[0] ,max[0] ), clamp(rect[1] ,min[1] ,max[1] ), clamp(rect[2] ,min[0] ,max[0] ), clamp(rect[3] ,min[1] ,max[1] ), ) def a_ ( _UpperCAmelCase : [int] ,_UpperCAmelCase : int ,_UpperCAmelCase : [int] ) -> Union[str, Any]: __snake_case : List[Any] = list(_UpperCAmelCase ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap __snake_case : Tuple = clamp_rect(_UpperCAmelCase ,[0, 0] ,[image_size[0], image_size[1]] ) return rect def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[int] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ) -> List[str]: __snake_case : Union[str, Any] = Image.new('RGB' ,(tile.size[0] + original_slice, tile.size[1]) ) result.paste( original_image.resize((tile.size[0], tile.size[1]) ,Image.BICUBIC ).crop( (slice_x, 0, slice_x + original_slice, tile.size[1]) ) ,(0, 0) ,) result.paste(_UpperCAmelCase ,(original_slice, 0) ) return result def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : int ) -> List[str]: __snake_case : Tuple = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) __snake_case : Dict = tile.crop(_UpperCAmelCase ) return tile def a_ ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : str ) -> Tuple: __snake_case : List[str] = n % d return n - divisor class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Any , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : DDPMScheduler , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : int = 350 , ) -> Any: '''simple docstring''' super().__init__( vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , low_res_scheduler=__a , scheduler=__a , max_noise_level=__a , ) def A_ ( self : int , __a : Optional[int] , __a : str , __a : Any , __a : Optional[int] , __a : Optional[int] , __a : Tuple , __a : List[str] , **__a : Optional[int] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = ( min(image.size[0] - (tile_size + original_image_slice) , x * tile_size ), min(image.size[1] - (tile_size + original_image_slice) , y * tile_size ), min(image.size[0] , (x + 1) * tile_size ), min(image.size[1] , (y + 1) * tile_size ), ) __snake_case : Tuple = add_overlap_rect(__a , __a , image.size ) __snake_case : Optional[Any] = image.crop(__a ) __snake_case : Optional[Any] = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] __snake_case : Optional[int] = translated_slice_x - (original_image_slice / 2) __snake_case : Tuple = max(0 , __a ) __snake_case : Optional[int] = squeeze_tile(__a , __a , __a , __a ) __snake_case : Optional[int] = to_input.size __snake_case : Optional[Any] = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) __snake_case : Union[str, Any] = super(__a , self ).__call__(image=__a , **__a ).images[0] __snake_case : List[Any] = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) __snake_case : Optional[int] = unsqueeze_tile(__a , __a ) __snake_case : Optional[Any] = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) __snake_case : Dict = [] if x == 0: remove_borders.append('l' ) elif crop_rect[2] == image.size[0]: remove_borders.append('r' ) if y == 0: remove_borders.append('t' ) elif crop_rect[3] == image.size[1]: remove_borders.append('b' ) __snake_case : Optional[Any] = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__a ) , mode='L' , ) final_image.paste( __a , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __a ) @torch.no_grad() def __call__( self : List[Any] , __a : Union[str, List[str]] , __a : Union[PIL.Image.Image, List[PIL.Image.Image]] , __a : int = 75 , __a : float = 9.0 , __a : int = 50 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , __a : int = 128 , __a : int = 32 , __a : int = 32 , ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = Image.new('RGB' , (image.size[0] * 4, image.size[1] * 4) ) __snake_case : List[str] = math.ceil(image.size[0] / tile_size ) __snake_case : List[str] = math.ceil(image.size[1] / tile_size ) __snake_case : int = tcx * tcy __snake_case : int = 0 for y in range(__a ): for x in range(__a ): self._process_tile( __a , __a , __a , __a , __a , __a , __a , prompt=__a , num_inference_steps=__a , guidance_scale=__a , noise_level=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , ) current_count += 1 if callback is not None: callback({'progress': current_count / total_tile_count, 'image': final_image} ) return final_image def a_ ( ) -> int: # Run a demo __snake_case : Optional[Any] = 'stabilityai/stable-diffusion-x4-upscaler' __snake_case : str = StableDiffusionTiledUpscalePipeline.from_pretrained(_UpperCAmelCase ,revision='fp16' ,torch_dtype=torch.floataa ) __snake_case : Tuple = pipe.to('cuda' ) __snake_case : Any = Image.open('../../docs/source/imgs/diffusers_library.jpg' ) def callback(_UpperCAmelCase : Union[str, Any] ): print(f'''progress: {obj["progress"]:.4f}''' ) obj["image"].save('diffusers_library_progress.jpg' ) __snake_case : Tuple = pipe(image=_UpperCAmelCase ,prompt='Black font, white background, vector' ,noise_level=40 ,callback=_UpperCAmelCase ) final_image.save('diffusers_library.jpg' ) if __name__ == "__main__": main()
353
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
0
'''simple docstring''' import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : int ) -> Optional[int]: __snake_case : str = 1.5 __snake_case : int = int(factor * num_class_images ) __snake_case : Optional[int] = ClipClient( url='https://knn.laion.ai/knn-service' ,indice_name='laion_400m' ,num_images=_UpperCAmelCase ,aesthetic_weight=0.1 ) os.makedirs(f'''{class_data_dir}/images''' ,exist_ok=_UpperCAmelCase ) if len(list(Path(f'''{class_data_dir}/images''' ).iterdir() ) ) >= num_class_images: return while True: __snake_case : str = client.query(text=_UpperCAmelCase ) if len(_UpperCAmelCase ) >= factor * num_class_images or num_images > 1E4: break else: __snake_case : int = int(factor * num_images ) __snake_case : List[Any] = ClipClient( url='https://knn.laion.ai/knn-service' ,indice_name='laion_400m' ,num_images=_UpperCAmelCase ,aesthetic_weight=0.1 ,) __snake_case : Tuple = 0 __snake_case : Dict = 0 __snake_case : Optional[Any] = tqdm(desc='downloading real regularization images' ,total=_UpperCAmelCase ) with open(f'''{class_data_dir}/caption.txt''' ,'w' ) as fa, open(f'''{class_data_dir}/urls.txt''' ,'w' ) as fa, open( f'''{class_data_dir}/images.txt''' ,'w' ) as fa: while total < num_class_images: __snake_case : str = class_images[count] count += 1 try: __snake_case : Union[str, Any] = requests.get(images['url'] ) if img.status_code == 2_00: __snake_case : List[Any] = Image.open(BytesIO(img.content ) ) with open(f'''{class_data_dir}/images/{total}.jpg''' ,'wb' ) as f: f.write(img.content ) fa.write(images['caption'] + '\n' ) fa.write(images['url'] + '\n' ) fa.write(f'''{class_data_dir}/images/{total}.jpg''' + '\n' ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def a_ ( ) -> Optional[int]: __snake_case : Optional[Any] = argparse.ArgumentParser('' ,add_help=_UpperCAmelCase ) parser.add_argument('--class_prompt' ,help='text prompt to retrieve images' ,required=_UpperCAmelCase ,type=_UpperCAmelCase ) parser.add_argument('--class_data_dir' ,help='path to save images' ,required=_UpperCAmelCase ,type=_UpperCAmelCase ) parser.add_argument('--num_class_images' ,help='number of images to download' ,default=2_00 ,type=_UpperCAmelCase ) return parser.parse_args() if __name__ == "__main__": A__ : str = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
354
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
355
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
0
'''simple docstring''' def a_ ( ) -> str: __snake_case : Optional[int] = 0 for i in range(1 ,10_01 ): total += i**i return str(_UpperCAmelCase )[-10:] if __name__ == "__main__": print(solution())
356
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
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 a_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Optional[int] = 3_84 __snake_case : str = 7 if "tiny" in model_name: __snake_case : str = 96 __snake_case : Tuple = (2, 2, 6, 2) __snake_case : List[Any] = (3, 6, 12, 24) elif "small" in model_name: __snake_case : List[Any] = 96 __snake_case : Union[str, Any] = (2, 2, 18, 2) __snake_case : int = (3, 6, 12, 24) elif "base" in model_name: __snake_case : Union[str, Any] = 1_28 __snake_case : int = (2, 2, 18, 2) __snake_case : Dict = (4, 8, 16, 32) __snake_case : List[Any] = 12 __snake_case : Optional[int] = 5_12 elif "large" in model_name: __snake_case : Optional[Any] = 1_92 __snake_case : Dict = (2, 2, 18, 2) __snake_case : List[Any] = (6, 12, 24, 48) __snake_case : Union[str, Any] = 12 __snake_case : List[Any] = 7_68 # set label information __snake_case : Optional[int] = 1_50 __snake_case : str = 'huggingface/label-files' __snake_case : List[Any] = 'ade20k-id2label.json' __snake_case : Any = json.load(open(hf_hub_download(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ,'r' ) ) __snake_case : int = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[int] = {v: k for k, v in idalabel.items()} __snake_case : List[Any] = SwinConfig( embed_dim=_UpperCAmelCase ,depths=_UpperCAmelCase ,num_heads=_UpperCAmelCase ,window_size=_UpperCAmelCase ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) __snake_case : str = UperNetConfig( backbone_config=_UpperCAmelCase ,auxiliary_in_channels=_UpperCAmelCase ,num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ,) return config def a_ ( _UpperCAmelCase : Optional[Any] ) -> List[Any]: __snake_case : str = [] # 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 a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : str ) -> Tuple: __snake_case : List[Any] = dct.pop(_UpperCAmelCase ) __snake_case : str = val def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Optional[int] ) -> str: __snake_case : str = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __snake_case : str = 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) __snake_case : Optional[Any] = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' ) __snake_case : Tuple = 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 __snake_case : Any = in_proj_weight[:dim, :] __snake_case : int = in_proj_bias[: dim] __snake_case : str = in_proj_weight[ dim : dim * 2, : ] __snake_case : str = in_proj_bias[ dim : dim * 2 ] __snake_case : Optional[Any] = in_proj_weight[ -dim :, : ] __snake_case : Any = in_proj_bias[-dim :] # fmt: on def a_ ( _UpperCAmelCase : Any ) -> Optional[Any]: __snake_case : Union[str, Any] = x.shape __snake_case : Any = x.reshape(_UpperCAmelCase ,4 ,in_channel // 4 ) __snake_case : str = x[:, [0, 2, 1, 3], :].transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : str ) -> List[Any]: __snake_case : Union[str, Any] = x.shape __snake_case : Tuple = x.reshape(_UpperCAmelCase ,in_channel // 4 ,4 ) __snake_case : Any = x[:, :, [0, 2, 1, 3]].transpose(1 ,2 ).reshape(_UpperCAmelCase ,_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : List[str] ) -> List[str]: __snake_case : int = x.shape[0] __snake_case : Optional[Any] = x.reshape(4 ,in_channel // 4 ) __snake_case : int = x[[0, 2, 1, 3], :].transpose(0 ,1 ).reshape(_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : Optional[int] ) -> Any: __snake_case : Tuple = x.shape[0] __snake_case : Tuple = x.reshape(in_channel // 4 ,4 ) __snake_case : Dict = x[:, [0, 2, 1, 3]].transpose(0 ,1 ).reshape(_UpperCAmelCase ) return x def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ) -> str: __snake_case : Optional[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', } __snake_case : List[str] = model_name_to_url[model_name] __snake_case : str = torch.hub.load_state_dict_from_url(_UpperCAmelCase ,map_location='cpu' ,file_name=_UpperCAmelCase )[ 'state_dict' ] for name, param in state_dict.items(): print(_UpperCAmelCase ,param.shape ) __snake_case : List[str] = get_upernet_config(_UpperCAmelCase ) __snake_case : List[Any] = UperNetForSemanticSegmentation(_UpperCAmelCase ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __snake_case : int = state_dict.pop(_UpperCAmelCase ) if "bn" in key: __snake_case : Tuple = key.replace('bn' ,'batch_norm' ) __snake_case : Union[str, Any] = val # rename keys __snake_case : Any = create_rename_keys(_UpperCAmelCase ) for src, dest in rename_keys: rename_key(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) read_in_q_k_v(_UpperCAmelCase ,config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __snake_case : str = reverse_correct_unfold_reduction_order(_UpperCAmelCase ) if "norm" in key: __snake_case : List[str] = reverse_correct_unfold_norm_order(_UpperCAmelCase ) model.load_state_dict(_UpperCAmelCase ) # verify on image __snake_case : List[str] = 'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg' __snake_case : Union[str, Any] = Image.open(requests.get(_UpperCAmelCase ,stream=_UpperCAmelCase ).raw ).convert('RGB' ) __snake_case : Tuple = SegformerImageProcessor() __snake_case : str = processor(_UpperCAmelCase ,return_tensors='pt' ).pixel_values with torch.no_grad(): __snake_case : Any = model(_UpperCAmelCase ) __snake_case : Dict = outputs.logits print(logits.shape ) print('First values of logits:' ,logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __snake_case : int = torch.tensor( [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]] ) elif model_name == "upernet-swin-small": __snake_case : Any = torch.tensor( [[-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.1_9_2_1, -7.1_9_2_1, -6.9_5_3_2], [-7.0_9_0_8, -7.0_9_0_8, -6.8_5_3_4]] ) elif model_name == "upernet-swin-base": __snake_case : Dict = torch.tensor( [[-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.5_8_5_1, -6.5_8_5_1, -6.4_3_3_0], [-6.4_7_6_3, -6.4_7_6_3, -6.3_2_5_4]] ) elif model_name == "upernet-swin-large": __snake_case : List[str] = torch.tensor( [[-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.5_2_9_7, -7.5_2_9_7, -7.3_8_0_2], [-7.4_0_4_4, -7.4_0_4_4, -7.2_5_8_6]] ) print('Logits:' ,outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] ,_UpperCAmelCase ,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(_UpperCAmelCase ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_UpperCAmelCase ) 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__": A__ : List[str] = 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.''' ) A__ : str = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
357
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__ : List[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__ : Tuple = ['''ElectraTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : 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[Any] = [ '''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__ : Optional[Any] = [ '''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__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
358
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
0
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin A__ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''') A__ : Dict = {'''target_lang''': '''fi''', '''source_lang''': '''en'''} A__ : Any = '''>>zh<<''' A__ : List[Any] = '''Helsinki-NLP/''' if is_torch_available(): A__ : Union[str, Any] = '''pt''' elif is_tf_available(): A__ : Union[str, Any] = '''tf''' else: A__ : str = '''jax''' @require_sentencepiece class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = MarianTokenizer A__ = False A__ = True def A_ ( self : Any ) -> Tuple: '''simple docstring''' super().setUp() __snake_case : List[str] = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>'] __snake_case : Any = dict(zip(__a , range(len(__a ) ) ) ) __snake_case : List[str] = Path(self.tmpdirname ) save_json(__a , save_dir / VOCAB_FILES_NAMES['vocab'] ) save_json(__a , save_dir / VOCAB_FILES_NAMES['tokenizer_config_file'] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__a , save_dir / VOCAB_FILES_NAMES['source_spm'] ) copyfile(__a , save_dir / VOCAB_FILES_NAMES['target_spm'] ) __snake_case : Union[str, Any] = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def A_ ( self : Any , **__a : int ) -> MarianTokenizer: '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : List[Any] , __a : Dict ) -> Any: '''simple docstring''' return ( "This is a test", "This is a test", ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Optional[int] = '</s>' __snake_case : List[str] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def A_ ( self : List[str] ) -> int: '''simple docstring''' __snake_case : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '</s>' ) self.assertEqual(vocab_keys[1] , '<unk>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(__a ) , 9 ) def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : str = MarianTokenizer.from_pretrained(f'''{ORG_NAME}opus-mt-en-de''' ) __snake_case : Tuple = en_de_tokenizer(['I am a small frog'] , return_tensors=__a ) self.assertIsInstance(__a , __a ) __snake_case : Tuple = [38, 121, 14, 697, 38848, 0] self.assertListEqual(__a , batch.input_ids[0] ) __snake_case : List[Any] = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__a ) __snake_case : Optional[Any] = [x.name for x in Path(__a ).glob('*' )] self.assertIn('source.spm' , __a ) MarianTokenizer.from_pretrained(__a ) def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = self.get_tokenizer() __snake_case : Dict = tok( ['I am a small frog' * 1000, 'I am a small frog'] , padding=__a , truncation=__a , return_tensors=__a ) self.assertIsInstance(__a , __a ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def A_ ( self : Any ) -> Dict: '''simple docstring''' __snake_case : int = self.get_tokenizer() __snake_case : List[str] = tok(['I am a tiny frog', 'I am a small frog'] , padding=__a , return_tensors=__a ) self.assertIsInstance(__a , __a ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = {'input_ids': [[43495, 462, 20, 42164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 38999, 6, 8, 464, 132, 1703, 492, 13, 4669, 37867, 13, 7525, 27, 1593, 988, 13, 33972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 12338, 2, 13958, 387, 2, 3629, 6953, 188, 2900, 2, 13958, 8011, 11501, 23, 8460, 4073, 34009, 20, 435, 11439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 37867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 26453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10767, 6, 316, 304, 4239, 3, 0], [148, 15722, 19, 1839, 12, 1350, 13, 22327, 5082, 5418, 47567, 35938, 59, 318, 19552, 108, 2183, 54, 14976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 19088, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100], [36, 6395, 12570, 39147, 11597, 6, 266, 4, 45405, 7296, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name='Helsinki-NLP/opus-mt-en-de' , revision='1a8c2263da11e68e50938f97e10cd57820bd504c' , decode_kwargs={'use_source_tokenizer': True} , ) def A_ ( self : Tuple ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = MarianTokenizer.from_pretrained('hf-internal-testing/test-marian-two-vocabs' ) __snake_case : List[Any] = 'Tämä on testi' __snake_case : List[str] = 'This is a test' __snake_case : Union[str, Any] = [76, 7, 2047, 2] __snake_case : Tuple = [69, 12, 11, 940, 2] __snake_case : Optional[Any] = tokenizer(__a ).input_ids self.assertListEqual(__a , __a ) __snake_case : str = tokenizer(text_target=__a ).input_ids self.assertListEqual(__a , __a ) __snake_case : Dict = tokenizer.decode(__a , skip_special_tokens=__a ) self.assertEqual(__a , __a )
359
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
0
'''simple docstring''' from __future__ import annotations from collections import namedtuple def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ,_UpperCAmelCase : float ) -> tuple: __snake_case : Optional[int] = namedtuple('result' ,'name value' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('Only one argument must be 0' ) elif power < 0: raise ValueError( 'Power cannot be negative in any electrical/electronics system' ) elif voltage == 0: return result('voltage' ,power / current ) elif current == 0: return result('current' ,power / voltage ) elif power == 0: return result('power' ,float(round(abs(voltage * current ) ,2 ) ) ) else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
360
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
0
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
361
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''Salesforce/blip-image-captioning-base''' A__ = ( '''This is a tool that generates a description of an image. It takes an input named `image` which should be the ''' '''image to caption, and returns a text that contains the description in English.''' ) A__ = '''image_captioner''' A__ = AutoModelForVisionaSeq A__ = ['''image'''] A__ = ['''text'''] def __init__( self : Optional[Any] , *__a : List[Any] , **__a : List[str] ) -> Union[str, Any]: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*__a , **__a ) def A_ ( self : Optional[Any] , __a : "Image" ) -> int: '''simple docstring''' return self.pre_processor(images=__a , return_tensors='pt' ) def A_ ( self : Union[str, Any] , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' return self.model.generate(**__a ) def A_ ( self : Any , __a : List[str] ) -> Any: '''simple docstring''' return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
362
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
0
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
363
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
0
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' import importlib import os from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Optional, Union import torch from ..utils import BaseOutput A__ : List[str] = '''scheduler_config.json''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 1 A__ = 2 A__ = 3 A__ = 4 A__ = 5 A__ = 6 A__ = 7 A__ = 8 A__ = 9 A__ = 10 A__ = 11 A__ = 12 A__ = 13 A__ = 14 @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 class snake_case__ : A__ = SCHEDULER_CONFIG_NAME A__ = [] A__ = True @classmethod def A_ ( cls : str , __a : Dict[str, Any] = None , __a : Optional[str] = None , __a : str=False , **__a : Tuple , ) -> List[str]: '''simple docstring''' __snake_case : int = cls.load_config( pretrained_model_name_or_path=__a , subfolder=__a , return_unused_kwargs=__a , return_commit_hash=__a , **__a , ) return cls.from_config(__a , return_unused_kwargs=__a , **__a ) def A_ ( self : Dict , __a : Union[str, os.PathLike] , __a : bool = False , **__a : Any ) -> List[str]: '''simple docstring''' self.save_config(save_directory=__a , push_to_hub=__a , **__a ) @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self._get_compatibles() @classmethod def A_ ( cls : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = list(set([cls.__name__] + cls._compatibles ) ) __snake_case : str = importlib.import_module(__name__.split('.' )[0] ) __snake_case : Dict = [ getattr(__a , __a ) for c in compatible_classes_str if hasattr(__a , __a ) ] return compatible_classes
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
0
'''simple docstring''' import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Dict ,_UpperCAmelCase : Any ) -> Union[str, Any]: # load base model __snake_case : Optional[Any] = StableDiffusionPipeline.from_pretrained(_UpperCAmelCase ,torch_dtype=torch.floataa ) # load LoRA weight from .safetensors __snake_case : List[Any] = load_file(_UpperCAmelCase ) __snake_case : Optional[int] = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: __snake_case : Union[str, Any] = key.split('.' )[0].split(LORA_PREFIX_TEXT_ENCODER + '_' )[-1].split('_' ) __snake_case : List[str] = pipeline.text_encoder else: __snake_case : Union[str, Any] = key.split('.' )[0].split(LORA_PREFIX_UNET + '_' )[-1].split('_' ) __snake_case : List[str] = pipeline.unet # find the target layer __snake_case : Union[str, Any] = layer_infos.pop(0 ) while len(_UpperCAmelCase ) > -1: try: __snake_case : List[str] = curr_layer.__getattr__(_UpperCAmelCase ) if len(_UpperCAmelCase ) > 0: __snake_case : Tuple = layer_infos.pop(0 ) elif len(_UpperCAmelCase ) == 0: break except Exception: if len(_UpperCAmelCase ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: __snake_case : Optional[int] = layer_infos.pop(0 ) __snake_case : Tuple = [] if "lora_down" in key: pair_keys.append(key.replace('lora_down' ,'lora_up' ) ) pair_keys.append(_UpperCAmelCase ) else: pair_keys.append(_UpperCAmelCase ) pair_keys.append(key.replace('lora_up' ,'lora_down' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: __snake_case : Optional[Any] = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) __snake_case : List[str] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_UpperCAmelCase ,_UpperCAmelCase ).unsqueeze(2 ).unsqueeze(3 ) else: __snake_case : str = state_dict[pair_keys[0]].to(torch.floataa ) __snake_case : Tuple = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(_UpperCAmelCase ,_UpperCAmelCase ) # update visited list for item in pair_keys: visited.append(_UpperCAmelCase ) return pipeline if __name__ == "__main__": A__ : str = argparse.ArgumentParser() parser.add_argument( '''--base_model_path''', default=None, type=str, required=True, help='''Path to the base model in diffusers format.''' ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--lora_prefix_unet''', default='''lora_unet''', type=str, help='''The prefix of UNet weight in safetensors''' ) parser.add_argument( '''--lora_prefix_text_encoder''', default='''lora_te''', type=str, help='''The prefix of text encoder weight in safetensors''', ) parser.add_argument('''--alpha''', default=0.75, type=float, help='''The merging ratio in W = W0 + alpha * deltaW''') parser.add_argument( '''--to_safetensors''', action='''store_true''', help='''Whether to store pipeline in safetensors format or not.''' ) parser.add_argument('''--device''', type=str, help='''Device to use (e.g. cpu, cuda:0, cuda:1, etc.)''') A__ : str = parser.parse_args() A__ : Optional[Any] = args.base_model_path A__ : int = args.checkpoint_path A__ : str = args.dump_path A__ : Tuple = args.lora_prefix_unet A__ : Optional[Any] = args.lora_prefix_text_encoder A__ : Optional[Any] = args.alpha A__ : int = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) A__ : int = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
366
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' from importlib import import_module from .logging import get_logger A__ : Dict = get_logger(__name__) class snake_case__ : def __init__( self : Union[str, Any] , __a : int , __a : Tuple=None ) -> int: '''simple docstring''' __snake_case : List[Any] = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith('__' ): setattr(self , __a , getattr(__a , __a ) ) __snake_case : Optional[int] = module._original_module if isinstance(__a , _PatchedModuleObj ) else module class snake_case__ : A__ = [] def __init__( self : List[str] , __a : str , __a : str , __a : Any , __a : Optional[int]=None ) -> Any: '''simple docstring''' __snake_case : Optional[Any] = obj __snake_case : Tuple = target __snake_case : List[str] = new __snake_case : int = target.split('.' )[0] __snake_case : Dict = {} __snake_case : Union[str, Any] = attrs or [] def __enter__( self : List[str] ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = self.target.split('.' ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__a ) ): try: __snake_case : Union[str, Any] = import_module('.'.join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): __snake_case : Any = getattr(self.obj , __a ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__a , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): __snake_case : Optional[Any] = obj_attr # patch at top level setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs ) ) __snake_case : Optional[int] = getattr(self.obj , __a ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a ) , attrs=self.attrs ) ) __snake_case : Dict = getattr(__a , __a ) # finally set the target attribute setattr(__a , __a , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: __snake_case : str = getattr(import_module('.'.join(__a ) ) , __a ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __a ) is attr_value: __snake_case : List[str] = getattr(self.obj , __a ) setattr(self.obj , __a , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" __snake_case : Union[str, Any] = globals()['__builtins__'][target_attr] setattr(self.obj , __a , self.new ) else: raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.''' ) def __exit__( self : int , *__a : Optional[int] ) -> str: '''simple docstring''' for attr in list(self.original ): setattr(self.obj , __a , self.original.pop(__a ) ) def A_ ( self : Any ) -> Dict: '''simple docstring''' self.__enter__() self._active_patches.append(self ) def A_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
367
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> int: if divisor % 5 == 0 or divisor % 2 == 0: return 0 __snake_case : Dict = 1 __snake_case : List[str] = 1 while repunit: __snake_case : Dict = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def a_ ( _UpperCAmelCase : int = 1_00_00_00 ) -> int: __snake_case : Optional[int] = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(_UpperCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"""{solution() = }""")
368
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
0
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class snake_case__ ( unittest.TestCase ): A__ = JukeboxTokenizer A__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def A_ ( self : Any ) -> Dict: '''simple docstring''' import torch __snake_case : List[Any] = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) __snake_case : Optional[Any] = tokenizer(**self.metas )['input_ids'] # fmt: off __snake_case : List[str] = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' import torch __snake_case : List[str] = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) __snake_case : str = tokenizer(**self.metas )['input_ids'] # fmt: off __snake_case : Optional[Any] = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
369
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A__ : List[Any] = logging.get_logger(__name__) class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): A__ = '''maskformer-swin''' A__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Any , __a : Union[str, Any]=224 , __a : Optional[int]=4 , __a : Optional[int]=3 , __a : Any=96 , __a : int=[2, 2, 6, 2] , __a : Tuple=[3, 6, 12, 24] , __a : Tuple=7 , __a : List[Any]=4.0 , __a : Any=True , __a : Dict=0.0 , __a : Optional[Any]=0.0 , __a : Dict=0.1 , __a : Union[str, Any]="gelu" , __a : Union[str, Any]=False , __a : Any=0.0_2 , __a : Union[str, Any]=1e-5 , __a : List[str]=None , __a : Dict=None , **__a : List[Any] , ): '''simple docstring''' super().__init__(**__a ) __snake_case : Optional[int] = image_size __snake_case : Any = patch_size __snake_case : List[str] = num_channels __snake_case : List[Any] = embed_dim __snake_case : Union[str, Any] = depths __snake_case : Dict = len(__a ) __snake_case : Optional[int] = num_heads __snake_case : Union[str, Any] = window_size __snake_case : Optional[Any] = mlp_ratio __snake_case : int = qkv_bias __snake_case : Union[str, Any] = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Dict = drop_path_rate __snake_case : List[str] = hidden_act __snake_case : int = use_absolute_embeddings __snake_case : Dict = layer_norm_eps __snake_case : Tuple = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __snake_case : Dict = int(embed_dim * 2 ** (len(__a ) - 1) ) __snake_case : Union[str, Any] = ['stem'] + [f'''stage{idx}''' for idx in range(1 , len(__a ) + 1 )] __snake_case : Optional[int] = get_aligned_output_features_output_indices( out_features=__a , out_indices=__a , stage_names=self.stage_names )
370
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Any = logging.get_logger(__name__) A__ : List[Any] = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json''', # See all GLPN models at https://huggingface.co/models?filter=glpn } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''glpn''' def __init__( self : Tuple , __a : int=3 , __a : Union[str, Any]=4 , __a : List[Any]=[2, 2, 2, 2] , __a : Dict=[8, 4, 2, 1] , __a : str=[32, 64, 160, 256] , __a : Optional[Any]=[7, 3, 3, 3] , __a : Optional[int]=[4, 2, 2, 2] , __a : int=[1, 2, 5, 8] , __a : Any=[4, 4, 4, 4] , __a : Dict="gelu" , __a : List[Any]=0.0 , __a : Any=0.0 , __a : Optional[Any]=0.0_2 , __a : Optional[Any]=0.1 , __a : Union[str, Any]=1e-6 , __a : str=64 , __a : List[str]=10 , __a : Dict=-1 , **__a : Union[str, Any] , ) -> List[Any]: '''simple docstring''' super().__init__(**__a ) __snake_case : List[Any] = num_channels __snake_case : Tuple = num_encoder_blocks __snake_case : Optional[Any] = depths __snake_case : Any = sr_ratios __snake_case : int = hidden_sizes __snake_case : Any = patch_sizes __snake_case : Optional[int] = strides __snake_case : Dict = mlp_ratios __snake_case : int = num_attention_heads __snake_case : List[Any] = hidden_act __snake_case : Optional[int] = hidden_dropout_prob __snake_case : Any = attention_probs_dropout_prob __snake_case : Optional[int] = initializer_range __snake_case : Union[str, Any] = drop_path_rate __snake_case : Any = layer_norm_eps __snake_case : Any = decoder_hidden_size __snake_case : str = max_depth __snake_case : List[Any] = head_in_index
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
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 A__ : Optional[int] = '''bert-base-cased''' A__ : Optional[Any] = '''google/pegasus-xsum''' A__ : List[Any] = [''' Sam ate lunch today.''', '''Sams lunch ingredients.'''] A__ : str = ['''A very interesting story about what I ate for lunch.''', '''Avocado, celery, turkey, coffee'''] A__ : str = '''patrickvonplaten/t5-tiny-random''' A__ : Union[str, Any] = '''sshleifer/bart-tiny-random''' A__ : List[Any] = '''sshleifer/tiny-mbart''' A__ : Dict = '''sshleifer/tiny-marian-en-de''' def a_ ( _UpperCAmelCase : Path ,_UpperCAmelCase : list ) -> List[str]: __snake_case : Tuple = '\n'.join(_UpperCAmelCase ) Path(_UpperCAmelCase ).open('w' ).writelines(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Any: for split in ["train", "val", "test"]: _dump_articles(os.path.join(_UpperCAmelCase ,f'''{split}.source''' ) ,_UpperCAmelCase ) _dump_articles(os.path.join(_UpperCAmelCase ,f'''{split}.target''' ) ,_UpperCAmelCase ) return tmp_dir class snake_case__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def A_ ( self : str , __a : Tuple ) -> str: '''simple docstring''' __snake_case : List[str] = AutoTokenizer.from_pretrained(__a ) __snake_case : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : int = max(len(tokenizer.encode(__a ) ) for a in ARTICLES ) __snake_case : Dict = max(len(tokenizer.encode(__a ) ) for a in SUMMARIES ) __snake_case : Any = 4 __snake_case : Optional[Any] = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated __snake_case : Optional[int] = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error. __snake_case : Any = SeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=__a , max_target_length=__a , src_lang=__a , tgt_lang=__a , ) __snake_case : Union[str, Any] = DataLoader(__a , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(__a , __a ) 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 __snake_case : Tuple = 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 A_ ( self : Optional[Any] , __a : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : int = AutoTokenizer.from_pretrained(__a ) __snake_case : Optional[Any] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) __snake_case : str = max(len(tokenizer.encode(__a ) ) for a in ARTICLES ) __snake_case : Union[str, Any] = max(len(tokenizer.encode(__a ) ) for a in SUMMARIES ) __snake_case : Any = 4 __snake_case : Dict = LegacySeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=20 , max_target_length=__a , ) __snake_case : str = DataLoader(__a , 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 20 >= 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 A_ ( self : List[Any] ) -> str: '''simple docstring''' __snake_case : str = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25' ) __snake_case : Dict = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) __snake_case : Any = tmp_dir.joinpath('train.source' ).open().readlines() __snake_case : List[str] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(__a , __a , 128 , __a ) __snake_case : int = {x.name for x in tmp_dir.iterdir()} __snake_case : int = {x.name for x in save_dir.iterdir()} __snake_case : Dict = 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(__a ) < len(__a ) assert len(__a ) == 1 assert len(packed_examples[0] ) == sum(len(__a ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='This test requires fairseq' ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' if not FAIRSEQ_AVAILABLE: return __snake_case : str = self._get_dataset(max_len=64 ) __snake_case : Union[str, Any] = 64 __snake_case : Union[str, Any] = ds.make_dynamic_sampler(__a , required_batch_size_multiple=__a ) __snake_case : Any = [len(__a ) for x in batch_sampler] assert len(set(__a ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(__a ) == len(__a ) # no dropped or added examples __snake_case : Union[str, Any] = DataLoader(__a , batch_sampler=__a , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : Optional[Any] = [] __snake_case : Dict = [] for batch in data_loader: __snake_case : int = batch['input_ids'].shape __snake_case : List[Any] = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple __snake_case : Tuple = np.product(batch['input_ids'].shape ) num_src_per_batch.append(__a ) if num_src_tokens > (max_tokens * 1.1): failures.append(__a ) assert num_src_per_batch[0] == max(__a ) if failures: raise AssertionError(f'''too many tokens in {len(__a )} batches''' ) def A_ ( self : Tuple ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = self._get_dataset(max_len=512 ) __snake_case : Any = 2 __snake_case : Dict = ds.make_sortish_sampler(__a , shuffle=__a ) __snake_case : List[Any] = DataLoader(__a , batch_size=__a , collate_fn=ds.collate_fn , num_workers=2 ) __snake_case : int = DataLoader(__a , batch_size=__a , collate_fn=ds.collate_fn , num_workers=2 , sampler=__a ) __snake_case : Any = tokenizer.pad_token_id def count_pad_tokens(__a : Tuple , __a : Optional[int]="input_ids" ): return [batch[k].eq(__a ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(__a , k='labels' ) ) < sum(count_pad_tokens(__a , k='labels' ) ) assert sum(count_pad_tokens(__a ) ) < sum(count_pad_tokens(__a ) ) assert len(__a ) == len(__a ) def A_ ( self : Optional[Any] , __a : int=1000 , __a : int=128 ) -> str: '''simple docstring''' if os.getenv('USE_REAL_DATA' , __a ): __snake_case : str = 'examples/seq2seq/wmt_en_ro' __snake_case : Union[str, Any] = max_len * 2 * 64 if not Path(__a ).joinpath('train.len' ).exists(): save_len_file(__a , __a ) else: __snake_case : List[Any] = 'examples/seq2seq/test_data/wmt_en_ro' __snake_case : List[Any] = max_len * 4 save_len_file(__a , __a ) __snake_case : Optional[Any] = AutoTokenizer.from_pretrained(__a ) __snake_case : Optional[Any] = SeqaSeqDataset( __a , data_dir=__a , type_path='train' , max_source_length=__a , max_target_length=__a , n_obs=__a , ) return ds, max_tokens, tokenizer def A_ ( self : Any ) -> Dict: '''simple docstring''' __snake_case : List[str] = self._get_dataset() __snake_case : Dict = set(DistributedSortishSampler(__a , 256 , num_replicas=2 , rank=0 , add_extra_examples=__a ) ) __snake_case : str = set(DistributedSortishSampler(__a , 256 , num_replicas=2 , rank=1 , add_extra_examples=__a ) ) assert idsa.intersection(__a ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def A_ ( self : int , __a : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = AutoTokenizer.from_pretrained(__a , use_fast=__a ) if tok_name == MBART_TINY: __snake_case : Union[str, Any] = SeqaSeqDataset( __a , 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' , ) __snake_case : List[Any] = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: __snake_case : Optional[Any] = SeqaSeqDataset( __a , 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 , ) __snake_case : Dict = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(__a ) == 1 if tok_name == BART_TINY else len(__a ) == 0
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
'''simple docstring''' from typing import Dict import numpy as np import torch from . import residue_constants as rc from .tensor_utils import tensor_tree_map, tree_map def a_ ( _UpperCAmelCase : Dict[str, torch.Tensor] ) -> Dict[str, torch.Tensor]: __snake_case : Any = [] __snake_case : List[str] = [] __snake_case : Optional[int] = [] for rt in rc.restypes: __snake_case : int = rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]] restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] ) __snake_case : Optional[int] = {name: i for i, name in enumerate(_UpperCAmelCase )} restype_atomaa_to_atomaa_list.append( [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] ) restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] ) # Add dummy mapping for restype 'UNK' restype_atomaa_to_atomaa_list.append([0] * 14 ) restype_atomaa_to_atomaa_list.append([0] * 37 ) restype_atomaa_mask_list.append([0.0] * 14 ) __snake_case : Optional[Any] = torch.tensor( _UpperCAmelCase ,dtype=torch.intaa ,device=protein['aatype'].device ,) __snake_case : Union[str, Any] = torch.tensor( _UpperCAmelCase ,dtype=torch.intaa ,device=protein['aatype'].device ,) __snake_case : Optional[Any] = torch.tensor( _UpperCAmelCase ,dtype=torch.floataa ,device=protein['aatype'].device ,) __snake_case : Dict = protein['aatype'].to(torch.long ) # create the mapping for (residx, atom14) --> atom37, i.e. an array # with shape (num_res, 14) containing the atom37 indices for this protein __snake_case : Any = restype_atomaa_to_atomaa[protein_aatype] __snake_case : List[str] = restype_atomaa_mask[protein_aatype] __snake_case : Tuple = residx_atomaa_mask __snake_case : Union[str, Any] = residx_atomaa_to_atomaa.long() # create the gather indices for mapping back __snake_case : Optional[Any] = restype_atomaa_to_atomaa[protein_aatype] __snake_case : Any = residx_atomaa_to_atomaa.long() # create the corresponding mask __snake_case : Any = torch.zeros([21, 37] ,dtype=torch.floataa ,device=protein['aatype'].device ) for restype, restype_letter in enumerate(rc.restypes ): __snake_case : Optional[Any] = rc.restype_atoa[restype_letter] __snake_case : Optional[int] = rc.residue_atoms[restype_name] for atom_name in atom_names: __snake_case : Tuple = rc.atom_order[atom_name] __snake_case : List[str] = 1 __snake_case : str = restype_atomaa_mask[protein_aatype] __snake_case : List[str] = residx_atomaa_mask return protein def a_ ( _UpperCAmelCase : Dict[str, torch.Tensor] ) -> Dict[str, np.ndarray]: __snake_case : Union[str, Any] = tree_map(lambda _UpperCAmelCase : torch.tensor(_UpperCAmelCase ,device=batch['aatype'].device ) ,_UpperCAmelCase ,np.ndarray ) __snake_case : List[Any] = tensor_tree_map(lambda _UpperCAmelCase : np.array(_UpperCAmelCase ) ,make_atomaa_masks(_UpperCAmelCase ) ) return out
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
352
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
0
'''simple docstring''' from __future__ import annotations def a_ ( _UpperCAmelCase : list ,_UpperCAmelCase : int | None = None ,_UpperCAmelCase : int | None = None ) -> None: if start is None: __snake_case : Dict = 0 if end is None: __snake_case : Optional[Any] = len(_UpperCAmelCase ) - 1 if start >= end: return __snake_case : List[str] = (start + end) // 2 slowsort(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) slowsort(_UpperCAmelCase ,mid + 1 ,_UpperCAmelCase ) if sequence[end] < sequence[mid]: __snake_case : Union[str, Any] = sequence[mid], sequence[end] slowsort(_UpperCAmelCase ,_UpperCAmelCase ,end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
353
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
0
'''simple docstring''' import fire from utils import calculate_rouge, save_json def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : str=None ,**_UpperCAmelCase : str ) -> str: __snake_case : List[str] = [x.strip() for x in open(_UpperCAmelCase ).readlines()] __snake_case : List[str] = [x.strip() for x in open(_UpperCAmelCase ).readlines()][: len(_UpperCAmelCase )] __snake_case : List[Any] = calculate_rouge(_UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) if save_path is not None: save_json(_UpperCAmelCase ,_UpperCAmelCase ,indent=_UpperCAmelCase ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
354
'''simple docstring''' from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = SMALL_MODEL_IDENTIFIER __snake_case : str = 'pt' __snake_case : Union[str, Any] = 'tf' def A_ ( self : Dict , __a : Tuple ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__a ) def A_ ( self : Any , __a : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TFAutoModel.from_pretrained(self.test_model , from_pt=__a ) model_tf.save_pretrained(__a ) def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Tuple = 'mock_framework' # Framework provided - return whatever the user provides __snake_case : int = FeaturesManager.determine_framework(self.test_model , __a ) self.assertEqual(__a , __a ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : List[Any] = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a , __a ) self.assertEqual(__a , __a ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__a ) __snake_case : Tuple = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__a ) __snake_case : Union[str, Any] = FeaturesManager.determine_framework(__a ) self.assertEqual(__a , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__a ): __snake_case : Optional[int] = FeaturesManager.determine_framework(__a ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ): __snake_case : int = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # PyTorch not in environment -> use TensorFlow __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_tf ) # Both in environment -> use PyTorch __snake_case : Optional[Any] = MagicMock(return_value=__a ) __snake_case : Tuple = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): __snake_case : Dict = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__a , self.framework_pt ) # Both not in environment -> raise error __snake_case : str = MagicMock(return_value=__a ) __snake_case : List[Any] = MagicMock(return_value=__a ) with patch('transformers.onnx.features.is_tf_available' , __a ), patch( 'transformers.onnx.features.is_torch_available' , __a ): with self.assertRaises(__a ): __snake_case : Tuple = FeaturesManager.determine_framework(self.test_model )
0
0
'''simple docstring''' import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL A__ : Union[str, Any] = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : tuple ,_UpperCAmelCase : Path ,_UpperCAmelCase : Any ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Dict ,_UpperCAmelCase : str=False ,) -> Dict: output_path.parent.mkdir(parents=_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( _UpperCAmelCase ,_UpperCAmelCase ,f=output_path.as_posix() ,input_names=_UpperCAmelCase ,output_names=_UpperCAmelCase ,dynamic_axes=_UpperCAmelCase ,do_constant_folding=_UpperCAmelCase ,use_external_data_format=_UpperCAmelCase ,enable_onnx_checker=_UpperCAmelCase ,opset_version=_UpperCAmelCase ,) else: export( _UpperCAmelCase ,_UpperCAmelCase ,f=output_path.as_posix() ,input_names=_UpperCAmelCase ,output_names=_UpperCAmelCase ,dynamic_axes=_UpperCAmelCase ,do_constant_folding=_UpperCAmelCase ,opset_version=_UpperCAmelCase ,) @torch.no_grad() def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : str ,_UpperCAmelCase : int ,_UpperCAmelCase : bool = False ) -> List[Any]: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __snake_case : Union[str, Any] = 'cuda' elif fpaa and not torch.cuda.is_available(): raise ValueError('`float16` model export is only supported on GPUs with CUDA' ) else: __snake_case : List[str] = 'cpu' __snake_case : List[Any] = Path(_UpperCAmelCase ) # VAE DECODER __snake_case : Optional[int] = AutoencoderKL.from_pretrained(model_path + '/vae' ) __snake_case : Any = vae_decoder.config.latent_channels # forward only through the decoder part __snake_case : str = vae_decoder.decode onnx_export( _UpperCAmelCase ,model_args=( torch.randn(1 ,_UpperCAmelCase ,25 ,25 ).to(device=_UpperCAmelCase ,dtype=_UpperCAmelCase ), False, ) ,output_path=output_path / 'vae_decoder' / 'model.onnx' ,ordered_input_names=['latent_sample', 'return_dict'] ,output_names=['sample'] ,dynamic_axes={ 'latent_sample': {0: 'batch', 1: 'channels', 2: 'height', 3: 'width'}, } ,opset=_UpperCAmelCase ,) del vae_decoder if __name__ == "__main__": A__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=1_4, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') A__ : int = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print('''SD: Done: ONNX''')
355
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ProphetNetTokenizer A__ = False def A_ ( self : Optional[int] ) -> Dict: '''simple docstring''' super().setUp() __snake_case : Dict = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def A_ ( self : int , __a : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[int] = 'UNwant\u00E9d,running' __snake_case : List[str] = 'unwanted, running' return input_text, output_text def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Dict = self.tokenizer_class(self.vocab_file ) __snake_case : List[str] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(__a , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def A_ ( self : Union[str, Any] ) -> str: '''simple docstring''' __snake_case : Optional[int] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def A_ ( self : int ) -> Any: '''simple docstring''' __snake_case : int = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Union[str, Any] = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Any ) -> List[str]: '''simple docstring''' __snake_case : str = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = BasicTokenizer(do_lower_case=__a , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : Any = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] __snake_case : List[Any] = {} for i, token in enumerate(__a ): __snake_case : List[str] = i __snake_case : Any = WordpieceTokenizer(vocab=__a , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Optional[Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : int = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] __snake_case : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] __snake_case : Union[str, Any] = tokenizer(__a , padding=__a , return_tensors='pt' ) self.assertIsInstance(__a , __a ) __snake_case : int = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def A_ ( self : Dict ) -> Optional[Any]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) @slow def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : str = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) __snake_case : Optional[int] = tokenizer.encode('sequence builders' , add_special_tokens=__a ) __snake_case : Optional[int] = tokenizer.encode('multi-sequence build' , add_special_tokens=__a ) __snake_case : Optional[Any] = tokenizer.build_inputs_with_special_tokens(__a ) __snake_case : List[Any] = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
0
'''simple docstring''' import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case__ : def __init__( self : Tuple , __a : int , __a : Optional[Any]=13 , __a : Optional[Any]=7 , __a : Dict=True , __a : Optional[Any]=True , __a : Any=True , __a : Optional[int]=True , __a : Tuple=True , __a : Any=False , __a : int=False , __a : Dict=False , __a : Optional[int]=2 , __a : Optional[Any]=99 , __a : Tuple=0 , __a : str=32 , __a : List[Any]=5 , __a : List[Any]=4 , __a : Optional[int]=0.1 , __a : List[str]=0.1 , __a : Dict=512 , __a : str=2 , __a : List[str]=0.0_2 , __a : Any=2 , __a : str=4 , __a : int="last" , __a : Any=True , __a : Optional[int]=None , __a : Tuple=0 , ) -> str: '''simple docstring''' __snake_case : Union[str, Any] = parent __snake_case : Any = batch_size __snake_case : Optional[Any] = seq_length __snake_case : List[str] = is_training __snake_case : Tuple = use_input_lengths __snake_case : List[Any] = use_token_type_ids __snake_case : Optional[Any] = use_labels __snake_case : List[Any] = gelu_activation __snake_case : List[Any] = sinusoidal_embeddings __snake_case : Any = causal __snake_case : str = asm __snake_case : int = n_langs __snake_case : int = vocab_size __snake_case : Tuple = n_special __snake_case : Optional[Any] = hidden_size __snake_case : str = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Any = hidden_dropout_prob __snake_case : Optional[Any] = attention_probs_dropout_prob __snake_case : Union[str, Any] = max_position_embeddings __snake_case : List[str] = type_sequence_label_size __snake_case : Optional[Any] = initializer_range __snake_case : Dict = num_labels __snake_case : Dict = num_choices __snake_case : Dict = summary_type __snake_case : Dict = use_proj __snake_case : List[str] = scope __snake_case : Optional[int] = bos_token_id def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' __snake_case : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : Optional[int] = None if self.use_input_lengths: __snake_case : Dict = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __snake_case : int = None if self.use_token_type_ids: __snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __snake_case : List[Any] = None __snake_case : str = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : Union[str, Any] = ids_tensor([self.batch_size] , 2 ).float() __snake_case : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __snake_case : str = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' return XLMConfig( 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 , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def A_ ( self : Optional[Any] , __a : Dict , __a : Tuple , __a : str , __a : Dict , __a : Optional[Any] , __a : str , __a : List[Any] , __a : int , __a : Tuple , ) -> str: '''simple docstring''' __snake_case : Optional[int] = XLMModel(config=__a ) model.to(__a ) model.eval() __snake_case : Optional[int] = model(__a , lengths=__a , langs=__a ) __snake_case : Dict = model(__a , langs=__a ) __snake_case : Union[str, Any] = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A_ ( self : Any , __a : List[Any] , __a : List[str] , __a : Optional[Any] , __a : str , __a : int , __a : Union[str, Any] , __a : str , __a : Dict , __a : str , ) -> List[Any]: '''simple docstring''' __snake_case : str = XLMWithLMHeadModel(__a ) model.to(__a ) model.eval() __snake_case : Union[str, Any] = 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 A_ ( self : List[str] , __a : str , __a : Tuple , __a : Optional[int] , __a : Any , __a : Optional[Any] , __a : Union[str, Any] , __a : Union[str, Any] , __a : int , __a : List[str] , ) -> int: '''simple docstring''' __snake_case : Any = XLMForQuestionAnsweringSimple(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a ) __snake_case : List[str] = model(__a , start_positions=__a , end_positions=__a ) __snake_case : Any = outputs 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 : str , __a : List[Any] , __a : Optional[Any] , __a : Any , __a : Union[str, Any] , __a : Dict , __a : Any , __a : str , __a : Tuple , __a : int , ) -> List[str]: '''simple docstring''' __snake_case : int = XLMForQuestionAnswering(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a ) __snake_case : Tuple = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , p_mask=__a , ) __snake_case : Tuple = model( __a , start_positions=__a , end_positions=__a , cls_index=__a , is_impossible=__a , ) (__snake_case ) : Optional[int] = result_with_labels.to_tuple() __snake_case : Tuple = model(__a , start_positions=__a , end_positions=__a ) (__snake_case ) : Optional[Any] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def A_ ( self : Union[str, Any] , __a : Union[str, Any] , __a : List[str] , __a : int , __a : Tuple , __a : Any , __a : List[Any] , __a : Tuple , __a : List[str] , __a : Tuple , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = XLMForSequenceClassification(__a ) model.to(__a ) model.eval() __snake_case : Dict = model(__a ) __snake_case : Dict = model(__a , labels=__a ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A_ ( self : Dict , __a : List[str] , __a : Any , __a : List[str] , __a : Dict , __a : str , __a : Tuple , __a : Optional[Any] , __a : List[Any] , __a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = self.num_labels __snake_case : Any = XLMForTokenClassification(__a ) model.to(__a ) model.eval() __snake_case : Tuple = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def A_ ( self : List[str] , __a : Optional[Any] , __a : Tuple , __a : Dict , __a : Optional[Any] , __a : Any , __a : List[Any] , __a : str , __a : Optional[Any] , __a : Optional[int] , ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.num_choices __snake_case : str = XLMForMultipleChoice(config=__a ) model.to(__a ) model.eval() __snake_case : Optional[int] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Dict = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def A_ ( self : int ) -> str: '''simple docstring''' __snake_case : List[Any] = self.prepare_config_and_inputs() ( __snake_case ) : Optional[Any] = config_and_inputs __snake_case : Optional[int] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths} return config, inputs_dict @require_torch class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) A__ = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable A__ = ( { '''feature-extraction''': XLMModel, '''fill-mask''': XLMWithLMHeadModel, '''question-answering''': XLMForQuestionAnsweringSimple, '''text-classification''': XLMForSequenceClassification, '''text-generation''': XLMWithLMHeadModel, '''token-classification''': XLMForTokenClassification, '''zero-shot''': XLMForSequenceClassification, } if is_torch_available() else {} ) def A_ ( self : Optional[int] , __a : Tuple , __a : Optional[int] , __a : List[str] , __a : List[Any] , __a : Any ) -> List[Any]: '''simple docstring''' 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 A_ ( self : List[Any] , __a : Any , __a : Optional[Any] , __a : Any=False ) -> Tuple: '''simple docstring''' __snake_case : Optional[int] = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": __snake_case : Optional[int] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) __snake_case : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def A_ ( self : Dict ) -> int: '''simple docstring''' __snake_case : Union[str, Any] = XLMModelTester(self ) __snake_case : List[str] = ConfigTester(self , config_class=__a , emb_dim=37 ) def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : int ) -> Optional[Any]: '''simple docstring''' __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*__a ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' __snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*__a ) def A_ ( self : Dict ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*__a ) def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*__a ) def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*__a ) def A_ ( self : Optional[int] ) -> Tuple: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*__a ) def A_ ( self : Optional[int] ) -> int: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*__a ) def A_ ( self : int , __a : Union[str, Any] , __a : int , __a : int , __a : Optional[Any] , __a : Any , __a : Optional[Any]=False , __a : Union[str, Any]=1 ) -> Optional[Any]: '''simple docstring''' self.assertIsInstance(__a , __a ) self.assertListEqual( [isinstance(__a , __a ) for iter_attentions in attentions] , [True] * len(__a ) ) self.assertEqual(len(__a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(__a ): # adds PAD dummy token __snake_case : Tuple = min_length + idx + 1 __snake_case : Optional[Any] = min_length + idx + 1 __snake_case : Optional[Any] = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__a ) ) def A_ ( self : Optional[Any] , __a : List[str] , __a : Dict , __a : Optional[Any] , __a : List[str] , __a : List[str] , __a : List[str]=False , __a : Any=1 ) -> List[str]: '''simple docstring''' self.assertIsInstance(__a , __a ) self.assertListEqual( [isinstance(__a , __a ) for iter_hidden_states in hidden_states] , [True] * len(__a ) , ) self.assertEqual(len(__a ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(__a ): # adds PAD dummy token __snake_case : Optional[Any] = min_length + idx + 1 __snake_case : List[Any] = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__a ) , ) pass @slow def A_ ( self : str ) -> str: '''simple docstring''' for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : Tuple = XLMModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch class snake_case__ ( unittest.TestCase ): @slow def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : str = XLMWithLMHeadModel.from_pretrained('xlm-mlm-en-2048' ) model.to(__a ) __snake_case : List[str] = torch.tensor([[14, 447]] , dtype=torch.long , device=__a ) # the president __snake_case : List[str] = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference __snake_case : int = model.generate(__a , do_sample=__a ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __a )
356
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : Optional[Any] = { '''configuration_nllb_moe''': [ '''NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''NllbMoeConfig''', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Dict = [ '''NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''NllbMoeForConditionalGeneration''', '''NllbMoeModel''', '''NllbMoePreTrainedModel''', '''NllbMoeTop2Router''', '''NllbMoeSparseMLP''', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys A__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
357
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('The given input must be positive' ) # get the generated string sequence __snake_case : Optional[Any] = gray_code_sequence_string(_UpperCAmelCase ) # # convert them to integers for i in range(len(_UpperCAmelCase ) ): __snake_case : Optional[Any] = int(sequence[i] ,2 ) return sequence def a_ ( _UpperCAmelCase : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __snake_case : Dict = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __snake_case : Dict = gray_code_sequence_string(bit_count - 1 ) __snake_case : Any = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): __snake_case : str = '0' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): __snake_case : Any = '1' + smaller_sequence[i] sequence.append(_UpperCAmelCase ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : List[str] = logging.get_logger(__name__) A__ : Optional[Any] = { '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''autoformer''' A__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Union[str, Any] , __a : Optional[int] = None , __a : Optional[int] = None , __a : str = "student_t" , __a : str = "nll" , __a : int = 1 , __a : List[int] = [1, 2, 3, 4, 5, 6, 7] , __a : bool = True , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : int = 0 , __a : Optional[List[int]] = None , __a : Optional[List[int]] = None , __a : int = 64 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : int = 2 , __a : int = 32 , __a : int = 32 , __a : str = "gelu" , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : float = 0.1 , __a : int = 100 , __a : float = 0.0_2 , __a : bool = True , __a : int=True , __a : int = 10 , __a : int = 25 , __a : int = 3 , **__a : int , ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[int] = prediction_length __snake_case : int = context_length if context_length is not None else prediction_length __snake_case : Any = distribution_output __snake_case : List[str] = loss __snake_case : List[Any] = input_size __snake_case : List[str] = num_time_features __snake_case : int = lags_sequence __snake_case : List[str] = scaling __snake_case : Optional[int] = num_dynamic_real_features __snake_case : Tuple = num_static_real_features __snake_case : str = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The cardinality should be a list of the same length as `num_static_categorical_features`' ) __snake_case : List[Any] = cardinality else: __snake_case : List[Any] = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__a ) != num_static_categorical_features: raise ValueError( 'The embedding dimension should be a list of the same length as `num_static_categorical_features`' ) __snake_case : int = embedding_dimension else: __snake_case : Optional[Any] = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] __snake_case : Any = num_parallel_samples # Transformer architecture configuration __snake_case : List[str] = input_size * len(self.lags_sequence ) + self._number_of_features __snake_case : Optional[int] = d_model __snake_case : List[Any] = encoder_attention_heads __snake_case : List[Any] = decoder_attention_heads __snake_case : Any = encoder_ffn_dim __snake_case : Optional[int] = decoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Any = decoder_layers __snake_case : List[str] = dropout __snake_case : Optional[int] = attention_dropout __snake_case : Optional[Any] = activation_dropout __snake_case : Optional[Any] = encoder_layerdrop __snake_case : List[Any] = decoder_layerdrop __snake_case : Optional[Any] = activation_function __snake_case : Tuple = init_std __snake_case : Optional[int] = use_cache # Autoformer __snake_case : List[str] = label_length __snake_case : Optional[int] = moving_average __snake_case : List[str] = autocorrelation_factor super().__init__(is_encoder_decoder=__a , **__a ) @property def A_ ( self : Optional[Any] ) -> int: '''simple docstring''' return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
358
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case__ ( unittest.TestCase ): def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : Any = tempfile.mkdtemp() # fmt: off __snake_case : List[str] = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest'] # fmt: on __snake_case : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) __snake_case : List[str] = { 'do_resize': True, 'size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.5, 0.5, 0.5], 'image_std': [0.5, 0.5, 0.5], } __snake_case : Optional[Any] = os.path.join(self.tmpdirname , __a ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__a , __a ) def A_ ( self : Optional[int] , **__a : Dict ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : int , **__a : Dict ) -> Tuple: '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__a ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[str] = [Image.fromarray(np.moveaxis(__a , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : Dict = self.get_image_processor() __snake_case : Any = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) processor.save_pretrained(self.tmpdirname ) __snake_case : Any = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : str ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __snake_case : Tuple = self.get_image_processor(do_normalize=__a , padding_value=1.0 ) __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=__a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __a ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Tuple = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : str = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = self.prepare_image_inputs() __snake_case : List[str] = image_processor(__a , return_tensors='np' ) __snake_case : List[str] = processor(images=__a , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : int = self.get_tokenizer() __snake_case : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Optional[int] = 'lower newer' __snake_case : Dict = processor(text=__a ) __snake_case : List[Any] = tokenizer(__a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Dict = self.get_image_processor() __snake_case : Union[str, Any] = self.get_tokenizer() __snake_case : int = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : List[Any] = 'lower newer' __snake_case : Optional[Any] = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with self.assertRaises(__a ): processor() def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = self.get_image_processor() __snake_case : Any = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __snake_case : int = processor.batch_decode(__a ) __snake_case : Optional[Any] = tokenizer.batch_decode(__a ) self.assertListEqual(__a , __a ) def A_ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = self.get_tokenizer() __snake_case : Dict = VisionTextDualEncoderProcessor(tokenizer=__a , image_processor=__a ) __snake_case : Union[str, Any] = 'lower newer' __snake_case : Tuple = self.prepare_image_inputs() __snake_case : Union[str, Any] = processor(text=__a , images=__a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class snake_case__ : A__ = PegasusConfig A__ = {} A__ = '''gelu''' def __init__( self : Tuple , __a : Any , __a : str=13 , __a : Union[str, Any]=7 , __a : Optional[Any]=True , __a : Optional[int]=False , __a : Tuple=99 , __a : Optional[Any]=32 , __a : Any=2 , __a : Tuple=4 , __a : List[str]=37 , __a : Any=0.1 , __a : int=0.1 , __a : List[str]=40 , __a : List[str]=2 , __a : Optional[int]=1 , __a : Any=0 , ) -> List[Any]: '''simple docstring''' __snake_case : Union[str, Any] = parent __snake_case : List[Any] = batch_size __snake_case : Tuple = seq_length __snake_case : Dict = is_training __snake_case : str = use_labels __snake_case : str = vocab_size __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = num_hidden_layers __snake_case : List[str] = num_attention_heads __snake_case : Optional[Any] = intermediate_size __snake_case : List[Any] = hidden_dropout_prob __snake_case : Tuple = attention_probs_dropout_prob __snake_case : List[Any] = max_position_embeddings __snake_case : List[str] = eos_token_id __snake_case : Any = pad_token_id __snake_case : Tuple = bos_token_id def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __snake_case : List[Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __snake_case : Optional[int] = tf.concat([input_ids, eos_tensor] , axis=1 ) __snake_case : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Any = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __snake_case : Dict = prepare_pegasus_inputs_dict(__a , __a , __a ) return config, inputs_dict def A_ ( self : Union[str, Any] , __a : Optional[Any] , __a : List[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : List[str] = TFPegasusModel(config=__a ).get_decoder() __snake_case : Union[str, Any] = inputs_dict['input_ids'] __snake_case : Optional[Any] = input_ids[:1, :] __snake_case : int = inputs_dict['attention_mask'][:1, :] __snake_case : Optional[Any] = inputs_dict['head_mask'] __snake_case : str = 1 # first forward pass __snake_case : Tuple = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) __snake_case : Dict = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __snake_case : str = ids_tensor((self.batch_size, 3) , config.vocab_size ) __snake_case : List[Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __snake_case : Any = tf.concat([input_ids, next_tokens] , axis=-1 ) __snake_case : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __snake_case : Union[str, Any] = model(__a , attention_mask=__a )[0] __snake_case : Tuple = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __snake_case : str = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __snake_case : Optional[int] = output_from_no_past[:, -3:, random_slice_idx] __snake_case : Tuple = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def a_ ( _UpperCAmelCase : Any ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : Dict=None ,_UpperCAmelCase : List[Any]=None ,_UpperCAmelCase : int=None ,_UpperCAmelCase : str=None ,) -> Optional[Any]: if attention_mask is None: __snake_case : List[Any] = tf.cast(tf.math.not_equal(_UpperCAmelCase ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __snake_case : str = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __snake_case : Tuple = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __snake_case : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __snake_case : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () A__ = (TFPegasusForConditionalGeneration,) if is_tf_available() else () A__ = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) A__ = True A__ = False A__ = False def A_ ( self : Optional[int] ) -> List[Any]: '''simple docstring''' __snake_case : List[Any] = TFPegasusModelTester(self ) __snake_case : Dict = ConfigTester(self , config_class=__a ) def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : int ) -> List[Any]: '''simple docstring''' __snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) @require_sentencepiece @require_tokenizers @require_tf class snake_case__ ( unittest.TestCase ): A__ = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] A__ = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers A__ = '''google/pegasus-xsum''' @cached_property def A_ ( self : int ) -> str: '''simple docstring''' return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : str = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def A_ ( self : Tuple , **__a : Optional[int] ) -> Any: '''simple docstring''' __snake_case : Dict = self.translate_src_text(**__a ) assert self.expected_text == generated_words def A_ ( self : Optional[int] , **__a : Dict ) -> List[str]: '''simple docstring''' __snake_case : Dict = self.tokenizer(self.src_text , **__a , padding=__a , return_tensors='tf' ) __snake_case : str = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__a , ) __snake_case : int = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__a ) return generated_words @slow def A_ ( self : Dict ) -> str: '''simple docstring''' self._assert_generated_batch_equal_expected()
359
'''simple docstring''' import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def a_ ( _UpperCAmelCase : List[Any] ) -> Tuple: __snake_case : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Optional[int] ) -> List[str]: __snake_case : Tuple = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: __snake_case : Union[str, Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def a_ ( ) -> Optional[Any]: __snake_case : Any = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ) -> Tuple: __snake_case : List[str] = 'imagenet-1k-id2label.json' __snake_case : Dict = 10_00 __snake_case : Union[str, Any] = 'huggingface/label-files' __snake_case : str = num_labels __snake_case : str = json.load(open(cached_download(hf_hub_url(_UpperCAmelCase ,_UpperCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __snake_case : Tuple = {int(_UpperCAmelCase ): v for k, v in idalabel.items()} __snake_case : Optional[Any] = idalabel __snake_case : str = {v: k for k, v in idalabel.items()} __snake_case : Dict = CvtConfig(num_labels=_UpperCAmelCase ,idalabel=_UpperCAmelCase ,labelaid=_UpperCAmelCase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' ,1 )[-1][4:6] == "13": __snake_case : Tuple = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' ,1 )[-1][4:6] == "21": __snake_case : str = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __snake_case : Dict = [2, 2, 20] __snake_case : Any = [3, 12, 16] __snake_case : Tuple = [1_92, 7_68, 10_24] __snake_case : str = CvtForImageClassification(_UpperCAmelCase ) __snake_case : List[Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) __snake_case : int = image_size __snake_case : int = torch.load(_UpperCAmelCase ,map_location=torch.device('cpu' ) ) __snake_case : List[Any] = OrderedDict() __snake_case : Union[str, Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __snake_case : Optional[Any] = list_of_state_dict + cls_token(_UpperCAmelCase ) __snake_case : Tuple = list_of_state_dict + embeddings(_UpperCAmelCase ) for cnt in range(config.depth[idx] ): __snake_case : Optional[int] = list_of_state_dict + attention(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = list_of_state_dict + final() for gg in list_of_state_dict: print(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) ): __snake_case : List[str] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) image_processor.save_pretrained(_UpperCAmelCase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": A__ : Dict = argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A__ : Tuple = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
0
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 10 ,_UpperCAmelCase : int = 22 ) -> int: __snake_case : List[str] = range(1 ,_UpperCAmelCase ) __snake_case : Optional[int] = range(1 ,_UpperCAmelCase ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F"""{solution(1_0, 2_2) = }""")
360
'''simple docstring''' from __future__ import annotations A__ : List[Any] = list[list[int]] # assigning initial values to the grid A__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution A__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def a_ ( _UpperCAmelCase : Matrix ,_UpperCAmelCase : int ,_UpperCAmelCase : int ,_UpperCAmelCase : int ) -> bool: for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def a_ ( _UpperCAmelCase : Matrix ) -> tuple[int, int] | None: for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def a_ ( _UpperCAmelCase : Matrix ) -> Matrix | None: if location := find_empty_location(_UpperCAmelCase ): __snake_case , __snake_case : Optional[int] = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Union[str, Any] = digit if sudoku(_UpperCAmelCase ) is not None: return grid __snake_case : Optional[Any] = 0 return None def a_ ( _UpperCAmelCase : Matrix ) -> None: for row in grid: for cell in row: print(_UpperCAmelCase ,end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('''\nExample grid:\n''' + '''=''' * 2_0) print_solution(example_grid) print('''\nExample grid solution:''') A__ : List[str] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('''Cannot find a solution.''')
0
0
import os def a_ ( ) -> int: with open(os.path.dirname(_UpperCAmelCase ) + '/p022_names.txt' ) as file: __snake_case : Optional[Any] = str(file.readlines()[0] ) __snake_case : int = names.replace('"' ,'' ).split(',' ) names.sort() __snake_case : Optional[int] = 0 __snake_case : int = 0 for i, name in enumerate(_UpperCAmelCase ): for letter in name: name_score += ord(_UpperCAmelCase ) - 64 total_score += (i + 1) * name_score __snake_case : Dict = 0 return total_score if __name__ == "__main__": print(solution())
361
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = KandinskyVaaPriorPipeline A__ = ['''prompt'''] A__ = ['''prompt''', '''negative_prompt'''] A__ = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Dict ) -> List[str]: '''simple docstring''' return 32 @property def A_ ( self : Any ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return self.time_input_dim @property def A_ ( self : str ) -> int: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' return 100 @property def A_ ( self : Tuple ) -> List[str]: '''simple docstring''' __snake_case : Tuple = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> Any: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Any = { 'num_attention_heads': 2, 'attention_head_dim': 12, 'embedding_dim': self.text_embedder_hidden_size, 'num_layers': 1, } __snake_case : List[Any] = PriorTransformer(**__a ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 __snake_case : Any = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , ) __snake_case : Optional[Any] = CLIPVisionModelWithProjection(__a ) return model @property def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : Dict = CLIPImageProcessor( crop_size=224 , do_center_crop=__a , do_normalize=__a , do_resize=__a , image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] , image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] , resample=3 , size=224 , ) return image_processor def A_ ( self : Dict ) -> Optional[int]: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : List[str] = self.dummy_image_encoder __snake_case : str = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : List[str] = self.dummy_image_processor __snake_case : Any = UnCLIPScheduler( variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=1000 , clip_sample=__a , clip_sample_range=1_0.0 , ) __snake_case : str = { 'prior': prior, 'image_encoder': image_encoder, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'scheduler': scheduler, 'image_processor': image_processor, } return components def A_ ( self : List[Any] , __a : Optional[Any] , __a : Tuple=0 ) -> Any: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : List[str] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : List[Any] = { 'prompt': 'horse', 'generator': generator, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def A_ ( self : str ) -> Dict: '''simple docstring''' __snake_case : str = 'cpu' __snake_case : List[str] = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Optional[Any] = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : List[str] = output.image_embeds __snake_case : str = pipe( **self.get_dummy_inputs(__a ) , return_dict=__a , )[0] __snake_case : Union[str, Any] = image[0, -10:] __snake_case : Any = image_from_tuple[0, -10:] assert image.shape == (1, 32) __snake_case : List[Any] = np.array( [-0.0_5_3_2, 1.7_1_2_0, 0.3_6_5_6, -1.0_8_5_2, -0.8_9_4_6, -1.1_7_5_6, 0.4_3_4_8, 0.2_4_8_2, 0.5_1_4_6, -0.1_1_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' __snake_case : Union[str, Any] = torch_device == 'cpu' __snake_case : Dict = True __snake_case : Union[str, Any] = False self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , test_mean_pixel_difference=__a , ) @skip_mps def A_ ( self : str ) -> Union[str, Any]: '''simple docstring''' __snake_case : Dict = torch_device == 'cpu' __snake_case : Optional[Any] = False self._test_attention_slicing_forward_pass( test_max_difference=__a , test_mean_pixel_difference=__a , )
0
0
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. A__ : Optional[int] = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class snake_case__ ( unittest.TestCase ): A__ = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING A__ = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: A__ = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: A__ = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def A_ ( self : Union[str, Any] , __a : str , __a : Optional[Any] , __a : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = ZeroShotClassificationPipeline( model=__a , tokenizer=__a , candidate_labels=['polics', 'health'] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def A_ ( self : List[Any] , __a : Union[str, Any] , __a : Optional[int] ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = classifier('Who are you voting for in 2020?' , candidate_labels='politics' ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) # No kwarg __snake_case : List[str] = classifier('Who are you voting for in 2020?' , ['politics'] ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) __snake_case : int = classifier('Who are you voting for in 2020?' , candidate_labels=['politics'] ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) __snake_case : Dict = classifier('Who are you voting for in 2020?' , candidate_labels='politics, public health' ) self.assertEqual( __a , {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __snake_case : Optional[Any] = classifier('Who are you voting for in 2020?' , candidate_labels=['politics', 'public health'] ) self.assertEqual( __a , {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['scores'] ) ) , 1.0 ) __snake_case : Tuple = classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='This text is about {}' ) self.assertEqual(__a , {'sequence': ANY(__a ), 'labels': [ANY(__a )], 'scores': [ANY(__a )]} ) # https://github.com/huggingface/transformers/issues/13846 __snake_case : List[Any] = classifier(['I am happy'] , ['positive', 'negative'] ) self.assertEqual( __a , [ {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} for i in range(1 ) ] , ) __snake_case : Union[str, Any] = classifier(['I am happy', 'I am sad'] , ['positive', 'negative'] ) self.assertEqual( __a , [ {'sequence': ANY(__a ), 'labels': [ANY(__a ), ANY(__a )], 'scores': [ANY(__a ), ANY(__a )]} for i in range(2 ) ] , ) with self.assertRaises(__a ): classifier('' , candidate_labels='politics' ) with self.assertRaises(__a ): classifier(__a , candidate_labels='politics' ) with self.assertRaises(__a ): classifier('Who are you voting for in 2020?' , candidate_labels='' ) with self.assertRaises(__a ): classifier('Who are you voting for in 2020?' , candidate_labels=__a ) with self.assertRaises(__a ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template='Not formatting template' , ) with self.assertRaises(__a ): classifier( 'Who are you voting for in 2020?' , candidate_labels='politics' , hypothesis_template=__a , ) self.run_entailment_id(__a ) def A_ ( self : int , __a : Pipeline ) -> Dict: '''simple docstring''' __snake_case : List[str] = zero_shot_classifier.model.config __snake_case : Union[str, Any] = config.labelaid __snake_case : int = zero_shot_classifier.entailment_id __snake_case : str = {'LABEL_0': 0, 'LABEL_1': 1, 'LABEL_2': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) __snake_case : int = {'entailment': 0, 'neutral': 1, 'contradiction': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __snake_case : Optional[Any] = {'ENTAIL': 0, 'NON-ENTAIL': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) __snake_case : Optional[int] = {'ENTAIL': 2, 'NEUTRAL': 1, 'CONTR': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) __snake_case : str = original_labelaid self.assertEqual(__a , zero_shot_classifier.entailment_id ) @require_torch def A_ ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' __snake_case : List[str] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( 'Who are you voting for in 2020?' * 100 , candidate_labels=['politics', 'public health', 'science'] ) @require_torch def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : Optional[int] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='pt' , ) __snake_case : str = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @require_tf def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : List[str] = pipeline( 'zero-shot-classification' , model='sshleifer/tiny-distilbert-base-cased-distilled-squad' , framework='tf' , ) __snake_case : str = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['science', 'public health', 'politics'], 'scores': [0.3_3_3, 0.3_3_3, 0.3_3_3], } , ) @slow @require_torch def A_ ( self : List[str] ) -> Any: '''simple docstring''' __snake_case : List[str] = pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='pt' ) __snake_case : List[str] = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) __snake_case : str = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=__a , ) self.assertEqual( nested_simplify(__a ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , ) @slow @require_tf def A_ ( self : str ) -> Any: '''simple docstring''' __snake_case : Union[str, Any] = pipeline('zero-shot-classification' , model='roberta-large-mnli' , framework='tf' ) __snake_case : Tuple = zero_shot_classifier( 'Who are you voting for in 2020?' , candidate_labels=['politics', 'public health', 'science'] ) self.assertEqual( nested_simplify(__a ) , { 'sequence': 'Who are you voting for in 2020?', 'labels': ['politics', 'public health', 'science'], 'scores': [0.9_7_6, 0.0_1_5, 0.0_0_9], } , ) __snake_case : int = zero_shot_classifier( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural networks' ' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder' ' through an attention mechanism. We propose a new simple network architecture, the Transformer, based' ' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two' ' machine translation tasks show these models to be superior in quality while being more parallelizable' ' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014' ' English-to-German translation task, improving over the existing best results, including ensembles by' ' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new' ' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small' ' fraction of the training costs of the best models from the literature. We show that the Transformer' ' generalizes well to other tasks by applying it successfully to English constituency parsing both with' ' large and limited training data.' , candidate_labels=['machine learning', 'statistics', 'translation', 'vision'] , multi_label=__a , ) self.assertEqual( nested_simplify(__a ) , { 'sequence': ( 'The dominant sequence transduction models are based on complex recurrent or convolutional neural' ' networks in an encoder-decoder configuration. The best performing models also connect the' ' encoder and decoder through an attention mechanism. We propose a new simple network' ' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence' ' and convolutions entirely. Experiments on two machine translation tasks show these models to be' ' superior in quality while being more parallelizable and requiring significantly less time to' ' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,' ' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014' ' English-to-French translation task, our model establishes a new single-model state-of-the-art' ' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training' ' costs of the best models from the literature. We show that the Transformer generalizes well to' ' other tasks by applying it successfully to English constituency parsing both with large and' ' limited training data.' ), 'labels': ['translation', 'machine learning', 'vision', 'statistics'], 'scores': [0.8_1_7, 0.7_1_3, 0.0_1_8, 0.0_1_8], } , )
362
'''simple docstring''' from math import factorial A__ : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)} def a_ ( _UpperCAmelCase : int ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_UpperCAmelCase ) ) def a_ ( _UpperCAmelCase : int = 60 ,_UpperCAmelCase : int = 1_00_00_00 ) -> int: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ) or not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length __snake_case : List[str] = 0 # the cached sizes of the previous chains __snake_case : dict[int, int] = {} for start_chain_element in range(1 ,_UpperCAmelCase ): # The temporary set will contain the elements of the chain __snake_case : Optional[int] = set() __snake_case : List[Any] = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. __snake_case : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_UpperCAmelCase ) chain_set_length += 1 __snake_case : Tuple = digit_factorial_sum(_UpperCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] __snake_case : Optional[Any] = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F"""{solution()}""")
0
0
'''simple docstring''' import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def a_ ( _UpperCAmelCase : Features ) -> Optional[int]: __snake_case : str = np.inf def set_batch_size(_UpperCAmelCase : FeatureType ) -> None: nonlocal batch_size if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Any = min(_UpperCAmelCase ,config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : List[str] = min(_UpperCAmelCase ,config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ) and feature.dtype == "binary": __snake_case : Optional[int] = min(_UpperCAmelCase ,config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(_UpperCAmelCase ,_UpperCAmelCase ) return None if batch_size is np.inf else batch_size class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Optional[Any] , __a : NestedDataStructureLike[PathLike] , __a : Optional[NamedSplit] = None , __a : Optional[Features] = None , __a : str = None , __a : bool = False , __a : bool = False , __a : Optional[int] = None , **__a : Tuple , ) -> Tuple: '''simple docstring''' super().__init__( __a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , ) __snake_case : Any = path_or_paths if isinstance(__a , __a ) else {self.split: path_or_paths} __snake_case : Tuple = _PACKAGED_DATASETS_MODULES['parquet'][1] __snake_case : Union[str, Any] = Parquet( cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , ) def A_ ( self : List[str] ) -> List[Any]: '''simple docstring''' # Build iterable dataset if self.streaming: __snake_case : Optional[Any] = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __snake_case : int = None __snake_case : Any = None __snake_case : Optional[int] = None __snake_case : str = None self.builder.download_and_prepare( download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , ) __snake_case : Union[str, Any] = self.builder.as_dataset( split=self.split , verification_mode=__a , in_memory=self.keep_in_memory ) return dataset class snake_case__ : def __init__( self : List[Any] , __a : Dataset , __a : Union[PathLike, BinaryIO] , __a : Optional[int] = None , **__a : List[Any] , ) -> int: '''simple docstring''' __snake_case : List[str] = dataset __snake_case : Optional[Any] = path_or_buf __snake_case : List[Any] = batch_size or get_writer_batch_size(dataset.features ) __snake_case : Tuple = parquet_writer_kwargs def A_ ( self : List[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , 'wb+' ) as buffer: __snake_case : Union[str, Any] = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs ) else: __snake_case : Optional[Any] = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs ) return written def A_ ( self : List[str] , __a : BinaryIO , __a : int , **__a : Any ) -> int: '''simple docstring''' __snake_case : Any = 0 __snake_case : Union[str, Any] = parquet_writer_kwargs.pop('path_or_buf' , __a ) __snake_case : List[str] = self.dataset.features.arrow_schema __snake_case : Tuple = pq.ParquetWriter(__a , schema=__a , **__a ) for offset in logging.tqdm( range(0 , len(self.dataset ) , __a ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating parquet from Arrow format' , ): __snake_case : Dict = query_table( table=self.dataset._data , key=slice(__a , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(__a ) written += batch.nbytes writer.close() return written
363
'''simple docstring''' def a_ ( _UpperCAmelCase : int = 1_00 ) -> int: __snake_case : Any = n * (n + 1) * (2 * n + 1) / 6 __snake_case : Union[str, Any] = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
0
0
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets A__ : List[str] = '''\ @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ''' A__ : Optional[int] = '''\ This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset. It first canonicalizes the inputs (e.g., converting "1/2" to "\\frac{1}{2}") and then computes accuracy. ''' A__ : Dict = R''' Calculates accuracy after canonicalizing inputs. Args: predictions: list of predictions to score. Each prediction is a string that contains natural language and LaTex. references: list of reference for each prediction. Each reference is a string that contains natural language and LaTex. Returns: accuracy: accuracy after canonicalizing inputs (e.g., converting "1/2" to "\\frac{1}{2}") Examples: >>> metric = datasets.load_metric("competition_math") >>> results = metric.compute(references=["\\frac{1}{2}"], predictions=["1/2"]) >>> print(results) {\'accuracy\': 1.0} ''' @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case__ ( datasets.Metric ): def A_ ( self : str ) -> Tuple: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/hendrycks/math' , codebase_urls=['https://github.com/hendrycks/math'] , ) def A_ ( self : str , __a : List[str] , __a : Optional[Any] ) -> int: '''simple docstring''' __snake_case : Optional[int] = 0.0 for i, j in zip(__a , __a ): n_correct += 1.0 if math_equivalence.is_equiv(__a , __a ) else 0.0 __snake_case : Optional[Any] = n_correct / len(__a ) return { "accuracy": accuracy, }
364
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available A__ : int = { '''configuration_groupvit''': [ '''GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GroupViTConfig''', '''GroupViTOnnxConfig''', '''GroupViTTextConfig''', '''GroupViTVisionConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GroupViTModel''', '''GroupViTPreTrainedModel''', '''GroupViTTextModel''', '''GroupViTVisionModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFGroupViTModel''', '''TFGroupViTPreTrainedModel''', '''TFGroupViTTextModel''', '''TFGroupViTVisionModel''', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
0
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
365
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ShapEPipeline A__ = ['''prompt'''] A__ = ['''prompt'''] A__ = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] A__ = False @property def A_ ( self : Optional[Any] ) -> str: '''simple docstring''' return 32 @property def A_ ( self : str ) -> Optional[int]: '''simple docstring''' return 32 @property def A_ ( self : Tuple ) -> List[Any]: '''simple docstring''' return self.time_input_dim * 4 @property def A_ ( self : Tuple ) -> Dict: '''simple docstring''' return 8 @property def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) return tokenizer @property def A_ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Dict = { 'num_attention_heads': 2, 'attention_head_dim': 16, 'embedding_dim': self.time_input_dim, 'num_embeddings': 32, 'embedding_proj_dim': self.text_embedder_hidden_size, 'time_embed_dim': self.time_embed_dim, 'num_layers': 1, 'clip_embed_dim': self.time_input_dim * 2, 'additional_embeddings': 0, 'time_embed_act_fn': 'gelu', 'norm_in_type': 'layer', 'encoder_hid_proj_type': None, 'added_emb_type': None, } __snake_case : Optional[Any] = PriorTransformer(**__a ) return model @property def A_ ( self : Dict ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) __snake_case : Tuple = { 'param_shapes': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), 'd_latent': self.time_input_dim, 'd_hidden': self.renderer_dim, 'n_output': 12, 'background': ( 0.1, 0.1, 0.1, ), } __snake_case : Optional[int] = ShapERenderer(**__a ) return model def A_ ( self : Tuple ) -> Tuple: '''simple docstring''' __snake_case : Tuple = self.dummy_prior __snake_case : Union[str, Any] = self.dummy_text_encoder __snake_case : List[str] = self.dummy_tokenizer __snake_case : Optional[Any] = self.dummy_renderer __snake_case : List[Any] = HeunDiscreteScheduler( beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=__a , clip_sample=__a , clip_sample_range=1.0 , ) __snake_case : int = { 'prior': prior, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'renderer': renderer, 'scheduler': scheduler, } return components def A_ ( self : Union[str, Any] , __a : Dict , __a : int=0 ) -> Optional[Any]: '''simple docstring''' if str(__a ).startswith('mps' ): __snake_case : List[str] = torch.manual_seed(__a ) else: __snake_case : Optional[Any] = torch.Generator(device=__a ).manual_seed(__a ) __snake_case : Optional[int] = { 'prompt': 'horse', 'generator': generator, 'num_inference_steps': 1, 'frame_size': 32, 'output_type': 'np', } return inputs def A_ ( self : List[Any] ) -> List[Any]: '''simple docstring''' __snake_case : Dict = 'cpu' __snake_case : Dict = self.get_dummy_components() __snake_case : int = self.pipeline_class(**__a ) __snake_case : str = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[Any] = pipe(**self.get_dummy_inputs(__a ) ) __snake_case : Dict = output.images[0] __snake_case : int = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) __snake_case : str = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def A_ ( self : Any ) -> List[str]: '''simple docstring''' # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : int = torch_device == 'cpu' __snake_case : str = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__a , relax_max_difference=__a , ) def A_ ( self : List[str] ) -> Dict: '''simple docstring''' __snake_case : str = self.get_dummy_components() __snake_case : Tuple = self.pipeline_class(**__a ) __snake_case : Dict = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : int = 1 __snake_case : Tuple = 2 __snake_case : Tuple = self.get_dummy_inputs(__a ) for key in inputs.keys(): if key in self.batch_params: __snake_case : Union[str, Any] = batch_size * [inputs[key]] __snake_case : str = pipe(**__a , num_images_per_prompt=__a )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Dict: '''simple docstring''' # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Optional[int] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/shap_e/test_shap_e_np_out.npy' ) __snake_case : Union[str, Any] = ShapEPipeline.from_pretrained('openai/shap-e' ) __snake_case : Any = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __snake_case : Optional[int] = torch.Generator(device=__a ).manual_seed(0 ) __snake_case : Union[str, Any] = pipe( 'a shark' , generator=__a , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__a , __a )
0
0
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __get__( self : Optional[Any] , __a : List[str] , __a : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError('unreadable attribute' ) __snake_case : Tuple = '__cached_' + self.fget.__name__ __snake_case : int = getattr(__a , __a , __a ) if cached is None: __snake_case : Optional[int] = self.fget(__a ) setattr(__a , __a , __a ) return cached def a_ ( _UpperCAmelCase : int ) -> List[Any]: __snake_case : int = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f'''invalid truth value {val!r}''' ) def a_ ( _UpperCAmelCase : List[Any] ) -> str: if is_torch_fx_proxy(_UpperCAmelCase ): return True if is_torch_available(): import torch if isinstance(_UpperCAmelCase ,torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(_UpperCAmelCase ,tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(_UpperCAmelCase ,(jnp.ndarray, Tracer) ): return True return isinstance(_UpperCAmelCase ,np.ndarray ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> List[Any]: return isinstance(_UpperCAmelCase ,np.ndarray ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Optional[int]: return _is_numpy(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[str] ) -> List[Any]: import torch return isinstance(_UpperCAmelCase ,torch.Tensor ) def a_ ( _UpperCAmelCase : List[Any] ) -> List[Any]: return False if not is_torch_available() else _is_torch(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: import torch return isinstance(_UpperCAmelCase ,torch.device ) def a_ ( _UpperCAmelCase : Union[str, Any] ) -> Dict: return False if not is_torch_available() else _is_torch_device(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[Any] ) -> Any: import torch if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): if hasattr(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : int = getattr(_UpperCAmelCase ,_UpperCAmelCase ) else: return False return isinstance(_UpperCAmelCase ,torch.dtype ) def a_ ( _UpperCAmelCase : str ) -> Optional[int]: return False if not is_torch_available() else _is_torch_dtype(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Tuple: import tensorflow as tf return isinstance(_UpperCAmelCase ,tf.Tensor ) def a_ ( _UpperCAmelCase : Tuple ) -> str: return False if not is_tf_available() else _is_tensorflow(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Any: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(_UpperCAmelCase ,'is_symbolic_tensor' ): return tf.is_symbolic_tensor(_UpperCAmelCase ) return type(_UpperCAmelCase ) == tf.Tensor def a_ ( _UpperCAmelCase : List[Any] ) -> Union[str, Any]: return False if not is_tf_available() else _is_tf_symbolic_tensor(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import jax.numpy as jnp # noqa: F811 return isinstance(_UpperCAmelCase ,jnp.ndarray ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Optional[Any]: return False if not is_flax_available() else _is_jax(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> List[Any]: if isinstance(_UpperCAmelCase ,(dict, UserDict) ): return {k: to_py_obj(_UpperCAmelCase ) for k, v in obj.items()} elif isinstance(_UpperCAmelCase ,(list, tuple) ): return [to_py_obj(_UpperCAmelCase ) for o in obj] elif is_tf_tensor(_UpperCAmelCase ): return obj.numpy().tolist() elif is_torch_tensor(_UpperCAmelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(_UpperCAmelCase ): return np.asarray(_UpperCAmelCase ).tolist() elif isinstance(_UpperCAmelCase ,(np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def a_ ( _UpperCAmelCase : Any ) -> Any: if isinstance(_UpperCAmelCase ,(dict, UserDict) ): return {k: to_numpy(_UpperCAmelCase ) for k, v in obj.items()} elif isinstance(_UpperCAmelCase ,(list, tuple) ): return np.array(_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): return obj.numpy() elif is_torch_tensor(_UpperCAmelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(_UpperCAmelCase ): return np.asarray(_UpperCAmelCase ) else: return obj class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : int ) -> Tuple: '''simple docstring''' __snake_case : Dict = fields(self ) # Safety and consistency checks if not len(__a ): raise ValueError(f'''{self.__class__.__name__} has no fields.''' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'''{self.__class__.__name__} should not have more than one required field.''' ) __snake_case : Dict = getattr(self , class_fields[0].name ) __snake_case : Any = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__a ): if isinstance(__a , __a ): __snake_case : Optional[int] = first_field.items() __snake_case : List[Any] = True else: try: __snake_case : Optional[int] = iter(__a ) __snake_case : List[str] = True except TypeError: __snake_case : Optional[int] = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(__a ): if ( not isinstance(__a , (list, tuple) ) or not len(__a ) == 2 or not isinstance(element[0] , __a ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute __snake_case : Union[str, Any] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'''Cannot set key/value for {element}. It needs to be a tuple (key, value).''' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: __snake_case : Optional[int] = element[1] elif first_field is not None: __snake_case : Optional[int] = first_field else: for field in class_fields: __snake_case : Optional[Any] = getattr(self , field.name ) if v is not None: __snake_case : List[str] = v def __delitem__( self : List[str] , *__a : Dict , **__a : Union[str, Any] ) -> Tuple: '''simple docstring''' raise Exception(f'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Optional[int] , *__a : List[Any] , **__a : Any ) -> Union[str, Any]: '''simple docstring''' raise Exception(f'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Union[str, Any] , *__a : Dict , **__a : Any ) -> Dict: '''simple docstring''' raise Exception(f'''You cannot use ``pop`` on a {self.__class__.__name__} instance.''' ) def A_ ( self : Dict , *__a : str , **__a : str ) -> Dict: '''simple docstring''' raise Exception(f'''You cannot use ``update`` on a {self.__class__.__name__} instance.''' ) def __getitem__( self : str , __a : Any ) -> int: '''simple docstring''' if isinstance(__a , __a ): __snake_case : List[Any] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : List[Any] , __a : Union[str, Any] , __a : List[Any] ) -> int: '''simple docstring''' if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__a , __a ) super().__setattr__(__a , __a ) def __setitem__( self : List[Any] , __a : Optional[Any] , __a : Any ) -> int: '''simple docstring''' super().__setitem__(__a , __a ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__a , __a ) def A_ ( self : Dict ) -> Tuple[Any]: '''simple docstring''' return tuple(self[k] for k in self.keys() ) class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : List[str] , __a : List[Any] ) -> Dict: '''simple docstring''' raise ValueError( f'''{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}''' ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''longest''' A__ = '''max_length''' A__ = '''do_not_pad''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''pt''' A__ = '''tf''' A__ = '''np''' A__ = '''jax''' class snake_case__ : def __init__( self : Union[str, Any] , __a : List[ContextManager] ) -> List[str]: '''simple docstring''' __snake_case : Tuple = context_managers __snake_case : Optional[int] = ExitStack() def __enter__( self : List[str] ) -> Optional[Any]: '''simple docstring''' for context_manager in self.context_managers: self.stack.enter_context(__a ) def __exit__( self : Tuple , *__a : Any , **__a : Any ) -> List[Any]: '''simple docstring''' self.stack.__exit__(*__a , **__a ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: __snake_case : Any = infer_framework(_UpperCAmelCase ) if framework == "tf": __snake_case : Optional[int] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __snake_case : Any = inspect.signature(model_class.forward ) # PyTorch models else: __snake_case : Optional[Any] = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def a_ ( _UpperCAmelCase : Any ) -> Dict: __snake_case : str = model_class.__name__ __snake_case : str = infer_framework(_UpperCAmelCase ) if framework == "tf": __snake_case : Optional[Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": __snake_case : List[str] = inspect.signature(model_class.forward ) # PyTorch models else: __snake_case : Dict = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def a_ ( _UpperCAmelCase : MutableMapping ,_UpperCAmelCase : str = "" ,_UpperCAmelCase : str = "." ) -> int: def _flatten_dict(_UpperCAmelCase : Tuple ,_UpperCAmelCase : str="" ,_UpperCAmelCase : Dict="." ): for k, v in d.items(): __snake_case : str = str(_UpperCAmelCase ) + delimiter + str(_UpperCAmelCase ) if parent_key else k if v and isinstance(_UpperCAmelCase ,_UpperCAmelCase ): yield from flatten_dict(_UpperCAmelCase ,_UpperCAmelCase ,delimiter=_UpperCAmelCase ).items() else: yield key, v return dict(_flatten_dict(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) ) @contextmanager def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : bool = False ) -> List[Any]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def a_ ( _UpperCAmelCase : Optional[int] ,_UpperCAmelCase : Tuple=None ) -> Any: if is_numpy_array(_UpperCAmelCase ): return np.transpose(_UpperCAmelCase ,axes=_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.T if axes is None else array.permute(*_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.transpose(_UpperCAmelCase ,perm=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.transpose(_UpperCAmelCase ,axes=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for transpose: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : Any ) -> int: if is_numpy_array(_UpperCAmelCase ): return np.reshape(_UpperCAmelCase ,_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.reshape(*_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.reshape(_UpperCAmelCase ,_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.reshape(_UpperCAmelCase ,_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for reshape: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Tuple ,_UpperCAmelCase : int=None ) -> Optional[int]: if is_numpy_array(_UpperCAmelCase ): return np.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.squeeze() if axis is None else array.squeeze(dim=_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.squeeze(_UpperCAmelCase ,axis=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for squeeze: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : int ) -> Any: if is_numpy_array(_UpperCAmelCase ): return np.expand_dims(_UpperCAmelCase ,_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.unsqueeze(dim=_UpperCAmelCase ) elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.expand_dims(_UpperCAmelCase ,axis=_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return jnp.expand_dims(_UpperCAmelCase ,axis=_UpperCAmelCase ) else: raise ValueError(f'''Type not supported for expand_dims: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: if is_numpy_array(_UpperCAmelCase ): return np.size(_UpperCAmelCase ) elif is_torch_tensor(_UpperCAmelCase ): return array.numel() elif is_tf_tensor(_UpperCAmelCase ): import tensorflow as tf return tf.size(_UpperCAmelCase ) elif is_jax_tensor(_UpperCAmelCase ): return array.size else: raise ValueError(f'''Type not supported for expand_dims: {type(_UpperCAmelCase )}.''' ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Any ) -> Dict: for key, value in auto_map.items(): if isinstance(_UpperCAmelCase ,(tuple, list) ): __snake_case : Any = [f'''{repo_id}--{v}''' if (v is not None and '--' not in v) else v for v in value] elif value is not None and "--" not in value: __snake_case : List[Any] = f'''{repo_id}--{value}''' return auto_map def a_ ( _UpperCAmelCase : Optional[int] ) -> List[str]: for base_class in inspect.getmro(_UpperCAmelCase ): __snake_case : Optional[Any] = base_class.__module__ __snake_case : Optional[int] = base_class.__name__ if module.startswith('tensorflow' ) or module.startswith('keras' ) or name == "TFPreTrainedModel": return "tf" elif module.startswith('torch' ) or name == "PreTrainedModel": return "pt" elif module.startswith('flax' ) or module.startswith('jax' ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f'''Could not infer framework from class {model_class}.''' )
366
'''simple docstring''' from __future__ import annotations import time import numpy as np A__ : str = [8, 5, 9, 7] A__ : List[str] = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] A__ : Dict = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class snake_case__ : def __init__( self : Union[str, Any] , __a : list[int] , __a : list[list[int]] , __a : list[list[int]] , ) -> None: '''simple docstring''' __snake_case : int = claim_vector __snake_case : Optional[int] = allocated_resources_table __snake_case : List[str] = maximum_claim_table def A_ ( self : str ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def A_ ( self : int ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def A_ ( self : int ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__a ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def A_ ( self : str ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(__a ): i for i in self.__need()} def A_ ( self : Union[str, Any] , **__a : int ) -> None: '''simple docstring''' __snake_case : str = self.__need() __snake_case : List[Any] = self.__allocated_resources_table __snake_case : Optional[int] = self.__available_resources() __snake_case : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n' ) while need_list: __snake_case : Tuple = False for each_need in need_list: __snake_case : Any = True for index, need in enumerate(__a ): if need > available_resources[index]: __snake_case : List[str] = False break if execution: __snake_case : Union[str, Any] = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: __snake_case : str = original_need_index print(f'''Process {process_number + 1} is executing.''' ) # remove the process run from stack need_list.remove(__a ) # update available/freed resources stack __snake_case : Union[str, Any] = np.array(__a ) + np.array( alloc_resources_table[process_number] ) print( 'Updated available resource stack for processes: ' + ' '.join([str(__a ) for x in available_resources] ) ) break if safe: print('The process is in a safe state.\n' ) else: print('System in unsafe state. Aborting...\n' ) break def A_ ( self : List[str] ) -> Optional[int]: '''simple docstring''' print(' ' * 9 + 'Allocated Resource Table' ) for item in self.__allocated_resources_table: print( f'''P{self.__allocated_resources_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print(' ' * 9 + 'System Resource Table' ) for item in self.__maximum_claim_table: print( f'''P{self.__maximum_claim_table.index(__a ) + 1}''' + ' '.join(f'''{it:>8}''' for it in item ) + '\n' ) print( 'Current Usage by Active Processes: ' + ' '.join(str(__a ) for x in self.__claim_vector ) ) print( 'Initial Available Resources: ' + ' '.join(str(__a ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
0
'''simple docstring''' from argparse import ArgumentParser, Namespace from ..utils import logging from . import BaseTransformersCLICommand def a_ ( _UpperCAmelCase : Namespace ) -> Union[str, Any]: return ConvertCommand( args.model_type ,args.tf_checkpoint ,args.pytorch_dump_output ,args.config ,args.finetuning_task_name ) A__ : Optional[int] = ''' transformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions. ''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @staticmethod def A_ ( __a : ArgumentParser ) -> str: '''simple docstring''' __snake_case : List[str] = parser.add_parser( 'convert' , help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' , ) train_parser.add_argument('--model_type' , type=__a , required=__a , help='Model\'s type.' ) train_parser.add_argument( '--tf_checkpoint' , type=__a , required=__a , help='TensorFlow checkpoint path or folder.' ) train_parser.add_argument( '--pytorch_dump_output' , type=__a , required=__a , help='Path to the PyTorch saved model output.' ) train_parser.add_argument('--config' , type=__a , default='' , help='Configuration file path or folder.' ) train_parser.add_argument( '--finetuning_task_name' , type=__a , default=__a , help='Optional fine-tuning task name if the TF model was a finetuned model.' , ) train_parser.set_defaults(func=__a ) def __init__( self : Tuple , __a : str , __a : str , __a : str , __a : str , __a : str , *__a : int , ) -> List[str]: '''simple docstring''' __snake_case : Dict = logging.get_logger('transformers-cli/converting' ) self._logger.info(f'''Loading model {model_type}''' ) __snake_case : Dict = model_type __snake_case : Optional[Any] = tf_checkpoint __snake_case : str = pytorch_dump_output __snake_case : Dict = config __snake_case : str = finetuning_task_name def A_ ( self : List[str] ) -> List[Any]: '''simple docstring''' if self._model_type == "albert": try: from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "bert": try: from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "funnel": try: from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import ( convert_tf_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "t5": try: from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch except ImportError: raise ImportError(__a ) convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "gpt": from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import ( convert_openai_checkpoint_to_pytorch, ) convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "transfo_xl": try: from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import ( convert_transfo_xl_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) if "ckpt" in self._tf_checkpoint.lower(): __snake_case : Optional[int] = self._tf_checkpoint __snake_case : List[str] = '' else: __snake_case : int = self._tf_checkpoint __snake_case : Tuple = '' convert_transfo_xl_checkpoint_to_pytorch( __a , self._config , self._pytorch_dump_output , __a ) elif self._model_type == "gpt2": try: from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import ( convert_gpta_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) elif self._model_type == "xlnet": try: from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import ( convert_xlnet_checkpoint_to_pytorch, ) except ImportError: raise ImportError(__a ) convert_xlnet_checkpoint_to_pytorch( self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name ) elif self._model_type == "xlm": from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import ( convert_xlm_checkpoint_to_pytorch, ) convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "lxmert": from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import ( convert_lxmert_checkpoint_to_pytorch, ) convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output ) elif self._model_type == "rembert": from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import ( convert_rembert_tf_checkpoint_to_pytorch, ) convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output ) else: raise ValueError( '--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]' )
367
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer A__ : Union[str, Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} A__ : List[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } A__ : List[Any] = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } A__ : Optional[Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_INIT_CONFIGURATION A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = ElectraTokenizer def __init__( self : int , __a : List[Any]=None , __a : int=None , __a : List[str]=True , __a : Any="[UNK]" , __a : Any="[SEP]" , __a : Union[str, Any]="[PAD]" , __a : Dict="[CLS]" , __a : List[Any]="[MASK]" , __a : str=True , __a : Optional[int]=None , **__a : Optional[int] , ) -> str: '''simple docstring''' super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , tokenize_chinese_chars=__a , strip_accents=__a , **__a , ) __snake_case : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , __a ) != do_lower_case or normalizer_state.get('strip_accents' , __a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , __a ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(__a , normalizer_state.pop('type' ) ) __snake_case : str = do_lower_case __snake_case : Optional[int] = strip_accents __snake_case : Any = tokenize_chinese_chars __snake_case : Union[str, Any] = normalizer_class(**__a ) __snake_case : Any = do_lower_case def A_ ( self : Any , __a : List[str] , __a : Optional[Any]=None ) -> Dict: '''simple docstring''' __snake_case : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def A_ ( self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' __snake_case : int = [self.sep_token_id] __snake_case : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def A_ ( self : Optional[int] , __a : str , __a : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' __snake_case : Tuple = self._tokenizer.model.save(__a , name=__a ) return tuple(__a )
0
0
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
368
'''simple docstring''' def a_ ( _UpperCAmelCase : int ) -> bool: __snake_case : Union[str, Any] = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(2_7)) print(perfect_cube(4))
0
0
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker A__ = '''CompVis/stable-diffusion-v1-1''' A__ = '''CompVis/stable-diffusion-v1-2''' A__ = '''CompVis/stable-diffusion-v1-3''' A__ = '''CompVis/stable-diffusion-v1-4''' class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Optional[Any] , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , __a : bool = True , ) -> int: '''simple docstring''' super()._init_() __snake_case : List[str] = StableDiffusionPipeline.from_pretrained(__a ) __snake_case : Union[str, Any] = StableDiffusionPipeline.from_pretrained(__a ) __snake_case : Dict = StableDiffusionPipeline.from_pretrained(__a ) __snake_case : Optional[Any] = StableDiffusionPipeline( vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , requires_safety_checker=__a , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def A_ ( self : Optional[int] ) -> Dict[str, Any]: '''simple docstring''' return {k: getattr(self , __a ) for k in self.config.keys() if not k.startswith('_' )} def A_ ( self : Tuple , __a : Optional[Union[str, int]] = "auto" ) -> Any: '''simple docstring''' if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def A_ ( self : List[str] ) -> Tuple: '''simple docstring''' self.enable_attention_slicing(__a ) @torch.no_grad() def A_ ( self : Union[str, Any] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Dict , ) -> str: '''simple docstring''' return self.pipea( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) @torch.no_grad() def A_ ( self : Optional[int] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Any , ) -> Any: '''simple docstring''' return self.pipea( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) @torch.no_grad() def A_ ( self : str , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ) -> Dict: '''simple docstring''' return self.pipea( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) @torch.no_grad() def A_ ( self : List[str] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : Optional[int] , ) -> Optional[int]: '''simple docstring''' return self.pipea( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) @torch.no_grad() def A_ ( self : List[Any] , __a : Union[str, List[str]] , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ) -> List[str]: '''simple docstring''' __snake_case : Tuple = 'cuda' if torch.cuda.is_available() else 'cpu' self.to(__a ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` must be divisible by 8 but are {height} and {width}.''' ) # Get first result from Stable Diffusion Checkpoint v1.1 __snake_case : str = self.textaimg_sda_a( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) # Get first result from Stable Diffusion Checkpoint v1.2 __snake_case : Optional[Any] = self.textaimg_sda_a( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) # Get first result from Stable Diffusion Checkpoint v1.3 __snake_case : List[str] = self.textaimg_sda_a( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) # Get first result from Stable Diffusion Checkpoint v1.4 __snake_case : Union[str, Any] = self.textaimg_sda_a( prompt=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , **__a , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
369
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss A__ : Tuple = pytest.mark.integration @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Dict = Dataset.from_dict({'filename': ['my_name-train' + '_' + str(__a ) for x in np.arange(30 ).tolist()]} ) return dset def A_ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() __snake_case : Dict = dset.map( lambda __a , __a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__a , keep_in_memory=__a ) __snake_case : List[Any] = dset.add_faiss_index('vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) dset.drop_index('vecs' ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __snake_case , __snake_case : Any = dset.get_nearest_examples('vecs' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : List[Any] ) -> Dict: '''simple docstring''' import faiss __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: dset.save_faiss_index('vecs' , tmp_file.name ) dset.load_faiss_index('vecs2' , tmp_file.name ) os.unlink(tmp_file.name ) __snake_case , __snake_case : str = dset.get_nearest_examples('vecs2' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='vecs' ) dset.drop_index('vecs' ) self.assertRaises(__a , partial(dset.get_nearest_examples , 'vecs2' , np.ones(5 , dtype=np.floataa ) ) ) def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch __snake_case : Dataset = self._create_dummy_dataset() with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : Any = {'acknowledged': True} mocked_bulk.return_value([(True, None)] * 30 ) __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 29}]}} __snake_case : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index('filename' , es_client=__a ) __snake_case , __snake_case : str = dset.get_nearest_examples('filename' , 'my_name-train_29' ) self.assertEqual(examples['filename'][0] , 'my_name-train_29' ) @require_faiss class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : str ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __snake_case : Dict = np.zeros(5 , dtype=np.floataa ) __snake_case : List[str] = 1 __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertRaises(__a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __snake_case : List[str] = np.eye(5 , dtype=np.floataa )[::-1] __snake_case , __snake_case : Dict = index.search_batch(__a ) self.assertRaises(__a , index.search_batch , queries[0] ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __a ) def A_ ( self : int ) -> int: '''simple docstring''' import faiss __snake_case : int = FaissIndex(string_factory='Flat' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __snake_case : List[str] = FaissIndex(string_factory='LSH' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__a ): __snake_case : Dict = FaissIndex(string_factory='Flat' , custom_index=faiss.IndexFlat(5 ) ) def A_ ( self : str ) -> Dict: '''simple docstring''' import faiss __snake_case : Tuple = faiss.IndexFlat(5 ) __snake_case : List[Any] = FaissIndex(custom_index=__a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def A_ ( self : List[Any] ) -> int: '''simple docstring''' import faiss __snake_case : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__a ) as tmp_file: index.save(tmp_file.name ) __snake_case : List[Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __snake_case : List[Any] = np.zeros(5 , dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : int = index.search(__a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a_ ( _UpperCAmelCase : str ) -> Optional[int]: import faiss __snake_case : int = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) __snake_case : Dict = 'index.faiss' __snake_case : Any = f'''mock://{index_name}''' index.save(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = FaissIndex.load(_UpperCAmelCase ,storage_options=mockfs.storage_options ) __snake_case : Any = np.zeros(5 ,dtype=np.floataa ) __snake_case : Any = 1 __snake_case , __snake_case : Tuple = index.search(_UpperCAmelCase ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def A_ ( self : List[str] ) -> List[str]: '''simple docstring''' from elasticsearch import Elasticsearch with patch('elasticsearch.Elasticsearch.search' ) as mocked_search, patch( 'elasticsearch.client.IndicesClient.create' ) as mocked_index_create, patch('elasticsearch.helpers.streaming_bulk' ) as mocked_bulk: __snake_case : int = Elasticsearch() __snake_case : Dict = {'acknowledged': True} __snake_case : List[Any] = ElasticSearchIndex(es_client=__a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['foo', 'bar', 'foobar'] ) # single query __snake_case : Optional[Any] = 'foo' __snake_case : int = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : List[Any] = index.search(__a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __snake_case : Dict = 'foo' __snake_case : Dict = {'hits': {'hits': [{'_score': 1, '_id': 0}]}} __snake_case , __snake_case : Optional[Any] = index.search(__a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __snake_case : List[Any] = ['foo', 'bar', 'foobar'] __snake_case : str = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : Any = index.search_batch(__a ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a ) # batched queries with timeout __snake_case : Tuple = ['foo', 'bar', 'foobar'] __snake_case : List[Any] = {'hits': {'hits': [{'_score': 1, '_id': 1}]}} __snake_case , __snake_case : int = index.search_batch(__a , request_timeout=30 ) __snake_case : Any = [scores[0] for scores in total_scores] __snake_case : Dict = [indices[0] for indices in total_indices] self.assertGreater(np.min(__a ) , 0 ) self.assertListEqual([1, 1, 1] , __a )
0
0
'''simple docstring''' from datetime import datetime as dt import os from github import Github A__ : Union[str, Any] = [ '''good first issue''', '''good second issue''', '''good difficult issue''', '''feature request''', '''new model''', '''wip''', ] def a_ ( ) -> Optional[Any]: __snake_case : int = Github(os.environ['GITHUB_TOKEN'] ) __snake_case : str = g.get_repo('huggingface/transformers' ) __snake_case : Any = repo.get_issues(state='open' ) for issue in open_issues: __snake_case : int = sorted([comment for comment in issue.get_comments()] ,key=lambda _UpperCAmelCase : i.created_at ,reverse=_UpperCAmelCase ) __snake_case : Optional[int] = comments[0] if len(_UpperCAmelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='closed' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
370
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging A__ : List[Any] = logging.get_logger(__name__) A__ : Tuple = { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''', } class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''t5''' A__ = ['''past_key_values'''] A__ = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : str , __a : Dict=32128 , __a : Dict=512 , __a : Union[str, Any]=64 , __a : str=2048 , __a : Union[str, Any]=6 , __a : Any=None , __a : Any=8 , __a : List[Any]=32 , __a : Any=128 , __a : Tuple=0.1 , __a : str=1e-6 , __a : Dict=1.0 , __a : Tuple="relu" , __a : Dict=True , __a : Union[str, Any]=True , __a : Any=0 , __a : Dict=1 , **__a : Union[str, Any] , ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = vocab_size __snake_case : str = d_model __snake_case : str = d_kv __snake_case : List[Any] = d_ff __snake_case : List[str] = num_layers __snake_case : Tuple = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry __snake_case : Union[str, Any] = num_heads __snake_case : Tuple = relative_attention_num_buckets __snake_case : Optional[int] = relative_attention_max_distance __snake_case : Optional[Any] = dropout_rate __snake_case : str = layer_norm_epsilon __snake_case : List[str] = initializer_factor __snake_case : int = feed_forward_proj __snake_case : Optional[Any] = use_cache __snake_case : Optional[Any] = self.feed_forward_proj.split('-' ) __snake_case : Dict = act_info[-1] __snake_case : List[str] = act_info[0] == 'gated' if len(__a ) > 1 and act_info[0] != "gated" or len(__a ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": __snake_case : Dict = 'gelu_new' super().__init__( pad_token_id=__a , eos_token_id=__a , is_encoder_decoder=__a , **__a , ) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @property def A_ ( self : str ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' __snake_case : Union[str, Any] = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: __snake_case : Tuple = 'past_encoder_sequence + sequence' __snake_case : Dict = {0: 'batch'} __snake_case : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: __snake_case : Tuple = {0: 'batch', 1: 'decoder_sequence'} __snake_case : int = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__a , direction='inputs' ) return common_inputs @property def A_ ( self : List[Any] ) -> int: '''simple docstring''' return 13
0
0
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class snake_case__ : A__ = BlenderbotSmallConfig A__ = {} A__ = '''gelu''' def __init__( self : List[str] , __a : Optional[Any] , __a : Union[str, Any]=13 , __a : Dict=7 , __a : Tuple=True , __a : Union[str, Any]=False , __a : Optional[Any]=99 , __a : List[str]=32 , __a : Tuple=2 , __a : Dict=4 , __a : Any=37 , __a : Any=0.1 , __a : Tuple=0.1 , __a : Any=20 , __a : Tuple=2 , __a : Any=1 , __a : Optional[Any]=0 , ) -> Any: '''simple docstring''' __snake_case : int = parent __snake_case : Optional[Any] = batch_size __snake_case : List[Any] = seq_length __snake_case : int = is_training __snake_case : Optional[Any] = use_labels __snake_case : Union[str, Any] = vocab_size __snake_case : Dict = hidden_size __snake_case : Tuple = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : Dict = intermediate_size __snake_case : int = hidden_dropout_prob __snake_case : str = attention_probs_dropout_prob __snake_case : Tuple = max_position_embeddings __snake_case : int = eos_token_id __snake_case : Optional[int] = pad_token_id __snake_case : Optional[int] = bos_token_id def A_ ( self : Optional[Any] ) -> Dict: '''simple docstring''' __snake_case : Any = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __snake_case : Union[str, Any] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __snake_case : int = tf.concat([input_ids, eos_tensor] , axis=1 ) __snake_case : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : Union[str, Any] = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) __snake_case : int = prepare_blenderbot_small_inputs_dict(__a , __a , __a ) return config, inputs_dict def A_ ( self : Any , __a : int , __a : List[str] ) -> Optional[Any]: '''simple docstring''' __snake_case : str = TFBlenderbotSmallModel(config=__a ).get_decoder() __snake_case : Any = inputs_dict['input_ids'] __snake_case : int = input_ids[:1, :] __snake_case : str = inputs_dict['attention_mask'][:1, :] __snake_case : int = inputs_dict['head_mask'] __snake_case : Optional[Any] = 1 # first forward pass __snake_case : Any = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) __snake_case : Union[str, Any] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __snake_case : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __snake_case : Dict = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __snake_case : int = tf.concat([input_ids, next_tokens] , axis=-1 ) __snake_case : Union[str, Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __snake_case : Tuple = model(__a , attention_mask=__a )[0] __snake_case : int = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __snake_case : Union[str, Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __snake_case : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] __snake_case : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1e-3 ) def a_ ( _UpperCAmelCase : int ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : Any=None ,_UpperCAmelCase : Tuple=None ,_UpperCAmelCase : Optional[int]=None ,_UpperCAmelCase : Tuple=None ,) -> str: if attention_mask is None: __snake_case : Tuple = tf.cast(tf.math.not_equal(_UpperCAmelCase ,config.pad_token_id ) ,tf.inta ) if decoder_attention_mask is None: __snake_case : Any = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape ,dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] ,config.pad_token_id ) ,tf.inta ), ] ,axis=-1 ,) if head_mask is None: __snake_case : int = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __snake_case : Optional[Any] = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: __snake_case : Tuple = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class snake_case__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): A__ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) A__ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () A__ = ( { '''conversational''': TFBlenderbotSmallForConditionalGeneration, '''feature-extraction''': TFBlenderbotSmallModel, '''summarization''': TFBlenderbotSmallForConditionalGeneration, '''text2text-generation''': TFBlenderbotSmallForConditionalGeneration, '''translation''': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) A__ = True A__ = False A__ = False def A_ ( self : Any ) -> Tuple: '''simple docstring''' __snake_case : Optional[int] = TFBlenderbotSmallModelTester(self ) __snake_case : Tuple = ConfigTester(self , config_class=__a ) def A_ ( self : Tuple ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def A_ ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) @require_tokenizers @require_tf class snake_case__ ( unittest.TestCase ): A__ = [ '''Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ''' ''' i\'m going to throw up.\nand why is that?''' ] A__ = '''facebook/blenderbot_small-90M''' @cached_property def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M' ) @cached_property def A_ ( self : List[Any] ) -> Any: '''simple docstring''' __snake_case : Any = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def A_ ( self : Union[str, Any] ) -> Dict: '''simple docstring''' __snake_case : Any = self.tokenizer(self.src_text , return_tensors='tf' ) __snake_case : Dict = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__a , ) __snake_case : Union[str, Any] = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__a )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
371
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A__ : Tuple = logging.get_logger(__name__) A__ : Optional[int] = {} class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = '''llama''' A__ = ['''past_key_values'''] def __init__( self : Any , __a : List[str]=32000 , __a : Union[str, Any]=4096 , __a : Optional[Any]=11008 , __a : Any=32 , __a : str=32 , __a : Optional[int]=None , __a : Dict="silu" , __a : Dict=2048 , __a : List[str]=0.0_2 , __a : Union[str, Any]=1e-6 , __a : Dict=True , __a : List[str]=0 , __a : Tuple=1 , __a : Tuple=2 , __a : Optional[Any]=1 , __a : Any=False , __a : Tuple=None , **__a : List[Any] , ) -> Optional[int]: '''simple docstring''' __snake_case : str = vocab_size __snake_case : List[str] = max_position_embeddings __snake_case : List[Any] = hidden_size __snake_case : Union[str, Any] = intermediate_size __snake_case : Optional[int] = num_hidden_layers __snake_case : List[Any] = num_attention_heads # for backward compatibility if num_key_value_heads is None: __snake_case : Optional[int] = num_attention_heads __snake_case : Optional[Any] = num_key_value_heads __snake_case : int = hidden_act __snake_case : Any = initializer_range __snake_case : Any = rms_norm_eps __snake_case : Union[str, Any] = pretraining_tp __snake_case : Optional[int] = use_cache __snake_case : Any = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , tie_word_embeddings=__a , **__a , ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __a ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' f'''got {self.rope_scaling}''' ) __snake_case : Optional[Any] = self.rope_scaling.get('type' , __a ) __snake_case : Tuple = self.rope_scaling.get('factor' , __a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(__a , __a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
0
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A__ : str = { '''configuration_xlm_roberta''': [ '''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaConfig''', '''XLMRobertaOnnxConfig''', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = ['''XLMRobertaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any = ['''XLMRobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Union[str, Any] = [ '''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaForCausalLM''', '''XLMRobertaForMaskedLM''', '''XLMRobertaForMultipleChoice''', '''XLMRobertaForQuestionAnswering''', '''XLMRobertaForSequenceClassification''', '''XLMRobertaForTokenClassification''', '''XLMRobertaModel''', '''XLMRobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple = [ '''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMRobertaForCausalLM''', '''TFXLMRobertaForMaskedLM''', '''TFXLMRobertaForMultipleChoice''', '''TFXLMRobertaForQuestionAnswering''', '''TFXLMRobertaForSequenceClassification''', '''TFXLMRobertaForTokenClassification''', '''TFXLMRobertaModel''', '''TFXLMRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Optional[int] = [ '''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxXLMRobertaForMaskedLM''', '''FlaxXLMRobertaForCausalLM''', '''FlaxXLMRobertaForMultipleChoice''', '''FlaxXLMRobertaForQuestionAnswering''', '''FlaxXLMRobertaForSequenceClassification''', '''FlaxXLMRobertaForTokenClassification''', '''FlaxXLMRobertaModel''', '''FlaxXLMRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys A__ : List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
350
'''simple docstring''' from __future__ import annotations A__ : str = '''Muhammad Umer Farooq''' A__ : int = '''MIT''' A__ : Optional[int] = '''1.0.0''' A__ : List[Any] = '''Muhammad Umer Farooq''' A__ : Optional[Any] = '''contact@muhammadumerfarooq.me''' A__ : Optional[Any] = '''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class snake_case__ ( SCREAMING_SNAKE_CASE_ ): def __init__( self : Union[str, Any] , __a : str ) -> None: '''simple docstring''' super().__init__() __snake_case : list[str] = [] __snake_case : Dict = domain def A_ ( self : Dict , __a : str , __a : list[tuple[str, str | None]] ) -> None: '''simple docstring''' # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: __snake_case : Optional[Any] = parse.urljoin(self.domain , __a ) self.urls.append(__a ) def a_ ( _UpperCAmelCase : str ) -> str: return ".".join(get_sub_domain_name(_UpperCAmelCase ).split('.' )[-2:] ) def a_ ( _UpperCAmelCase : str ) -> str: return parse.urlparse(_UpperCAmelCase ).netloc def a_ ( _UpperCAmelCase : str = "https://github.com" ) -> list[str]: __snake_case : List[Any] = get_domain_name(_UpperCAmelCase ) # Initialize the parser __snake_case : Tuple = Parser(_UpperCAmelCase ) try: # Open URL __snake_case : Any = requests.get(_UpperCAmelCase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through __snake_case : Dict = set() for link in parser.urls: # open URL. # read = requests.get(link) try: __snake_case : List[Any] = requests.get(_UpperCAmelCase ) # Get the valid email. __snake_case : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain ,read.text ) # If not in list then append it. for email in emails: valid_emails.add(_UpperCAmelCase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_UpperCAmelCase ) if __name__ == "__main__": A__ : Tuple = emails_from_url('''https://github.com''') print(F"""{len(emails)} emails found:""") print('''\n'''.join(sorted(emails)))
0
0
'''simple docstring''' import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case__ ( unittest.TestCase ): def A_ ( self : Optional[Any] ) -> Any: '''simple docstring''' __snake_case : List[Any] = mock.Mock() __snake_case : Any = 500 __snake_case : Optional[int] = {} __snake_case : Optional[int] = HTTPError __snake_case : List[str] = {} # Download this model to make sure it's in the cache. __snake_case : Union[str, Any] = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=__a ) as mock_head: __snake_case : Tuple = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def A_ ( self : List[Any] ) -> List[str]: '''simple docstring''' __snake_case : Union[str, Any] = mock.Mock() __snake_case : Tuple = 500 __snake_case : int = {} __snake_case : List[str] = HTTPError __snake_case : List[Any] = {} # Download this model to make sure it's in the cache. __snake_case : str = GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' , return_value=__a ) as mock_head: __snake_case : Dict = GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def A_ ( self : List[Any] ) -> str: '''simple docstring''' # This test is for deprecated behavior and can be removed in v5 try: __snake_case : Optional[int] = tempfile.mktemp() with open(__a , 'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' , __a ) __snake_case : Any = AlbertTokenizer.from_pretrained(__a ) finally: os.remove(__a ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' , 'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' , __a ) __snake_case : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def A_ ( self : List[str] ) -> Any: '''simple docstring''' __snake_case : int = AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class snake_case__ ( unittest.TestCase ): A__ = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def A_ ( cls : int ) -> Dict: '''simple docstring''' __snake_case : Union[str, Any] = TOKEN HfFolder.save_token(__a ) @classmethod def A_ ( cls : List[Any] ) -> Dict: '''simple docstring''' try: delete_repo(token=cls._token , repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def A_ ( self : List[Any] ) -> Tuple: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Optional[Any] = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : int = BertTokenizer(__a ) tokenizer.push_to_hub('test-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__a , repo_id='test-tokenizer' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : Union[str, Any] = BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def A_ ( self : Optional[int] ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : str = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Union[str, Any] = BertTokenizer(__a ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' , use_auth_token=self._token ) __snake_case : List[str] = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( __a , repo_id='valid_org/test-tokenizer-org' , push_to_hub=__a , use_auth_token=self._token ) __snake_case : Dict = BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def A_ ( self : Optional[Any] ) -> Any: '''simple docstring''' CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Union[str, Any] = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Optional[Any] = CustomTokenizer(__a ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: __snake_case : Dict = os.path.join(__a , 'vocab.txt' ) with open(__a , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) __snake_case : Dict = BertTokenizerFast.from_pretrained(__a ) bert_tokenizer.save_pretrained(__a ) __snake_case : Optional[int] = CustomTokenizerFast.from_pretrained(__a ) tokenizer.push_to_hub('test-dynamic-tokenizer' , use_auth_token=self._token ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer''' , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizerFast' ) __snake_case : int = AutoTokenizer.from_pretrained( f'''{USER}/test-dynamic-tokenizer''' , use_fast=__a , trust_remote_code=__a ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , 'CustomTokenizer' ) class snake_case__ ( unittest.TestCase ): def A_ ( self : str ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data , {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def A_ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' __snake_case : Optional[Any] = Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) , ['[CLS]', ' This is a ', 'extra_id_100'] ) def A_ ( self : int ) -> Union[str, Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) , ['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) , ['BC', 'A'] ) def A_ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Dict = Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def A_ ( self : str ) -> List[Any]: '''simple docstring''' __snake_case : Dict = Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) , ['This is something ', '[SPECIAL_TOKEN]'] ) def A_ ( self : Dict ) -> Union[str, Any]: '''simple docstring''' __snake_case : int = Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) , ['AB', 'C'] ) def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Any = Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) , ['ABC', 'D'] ) def A_ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __snake_case : Optional[Any] = Trie() __snake_case : Dict = trie.cut_text('ABC' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(__a , ['AB', 'C'] )
351
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) A__ : Dict = logging.getLogger() def a_ ( ) -> Tuple: __snake_case : List[Any] = argparse.ArgumentParser() parser.add_argument('-f' ) __snake_case : Any = parser.parse_args() return args.f def a_ ( _UpperCAmelCase : Optional[int] ) -> List[Any]: __snake_case : Tuple = {} __snake_case : Union[str, Any] = os.path.join(_UpperCAmelCase ,'all_results.json' ) if os.path.exists(_UpperCAmelCase ): with open(_UpperCAmelCase ,'r' ) as f: __snake_case : List[str] = json.load(_UpperCAmelCase ) else: raise ValueError(f'''can\'t find {path}''' ) return results def a_ ( ) -> Union[str, Any]: __snake_case : Union[str, Any] = torch.cuda.is_available() and torch_device == 'cuda' return is_using_cuda and is_apex_available() A__ : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case__ ( SCREAMING_SNAKE_CASE_ ): @classmethod def A_ ( cls : Any ) -> List[str]: '''simple docstring''' # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : Dict = os.path.join(cls.tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) __snake_case : List[Any] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def A_ ( cls : List[str] ) -> List[str]: '''simple docstring''' shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Optional[Any]: '''simple docstring''' __snake_case : List[Any] = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : List[Any] = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'glue_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking '''.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertLess(result['perplexity'] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'clm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : str ) -> List[str]: '''simple docstring''' __snake_case : int = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertLess(result['perplexity'] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'mlm_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __snake_case : Any = 7 if get_gpu_count() > 1 else 2 __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.7_5 ) self.assertLess(result['train_loss'] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'ner_no_trainer' ) ) ) @unittest.skip(reason='Fix me @muellerzr' ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> List[Any]: '''simple docstring''' __snake_case : Any = self.get_auto_remove_tmp_dir() __snake_case : Tuple = f''' {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result['eval_f1'] , 28 ) self.assertGreaterEqual(result['eval_exact'] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'qa_no_trainer' ) ) ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Dict ) -> List[Any]: '''simple docstring''' __snake_case : str = self.get_auto_remove_tmp_dir() __snake_case : Any = f''' {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : str = get_results(__a ) self.assertGreaterEqual(result['eval_accuracy'] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , 'swag_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Any ) -> Union[str, Any]: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : List[str] = f''' {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : int = get_results(__a ) self.assertGreaterEqual(result['eval_rouge1'] , 10 ) self.assertGreaterEqual(result['eval_rouge2'] , 2 ) self.assertGreaterEqual(result['eval_rougeL'] , 7 ) self.assertGreaterEqual(result['eval_rougeLsum'] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'summarization_no_trainer' ) ) ) @slow @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Union[str, Any] ) -> int: '''simple docstring''' __snake_case : Tuple = self.get_auto_remove_tmp_dir() __snake_case : str = f''' {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking '''.split() run_command(self._launch_args + testargs ) __snake_case : Dict = get_results(__a ) self.assertGreaterEqual(result['eval_bleu'] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , 'epoch_0' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'translation_no_trainer' ) ) ) @slow def A_ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' __snake_case : Union[str, Any] = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) __snake_case : List[str] = self.get_auto_remove_tmp_dir() __snake_case : int = f''' {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch '''.split() run_command(self._launch_args + testargs ) __snake_case : List[str] = get_results(__a ) self.assertGreaterEqual(result['eval_overall_accuracy'] , 0.1_0 ) @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def A_ ( self : Tuple ) -> Any: '''simple docstring''' __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : Dict = f''' {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 '''.split() if is_cuda_and_apex_available(): testargs.append('--fp16' ) run_command(self._launch_args + testargs ) __snake_case : Optional[int] = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result['eval_accuracy'] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , 'step_1' ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , 'image_classification_no_trainer' ) ) )
0
0
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ) -> List[str]: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Tuple = np.full((len(_UpperCAmelCase ), sequence_length, 2) ,_UpperCAmelCase ) else: __snake_case : int = np.full((len(_UpperCAmelCase ), sequence_length) ,_UpperCAmelCase ) for i, tensor in enumerate(_UpperCAmelCase ): if padding_side == "right": if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : Dict = tensor[:sequence_length] else: __snake_case : List[Any] = tensor[:sequence_length] else: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): __snake_case : str = tensor[:sequence_length] else: __snake_case : int = tensor[:sequence_length] return out_tensor.tolist() def a_ ( _UpperCAmelCase : Any ) -> Optional[int]: __snake_case : List[Any] = ord(_UpperCAmelCase ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 1_23 and cp <= 1_26): return True __snake_case : Dict = unicodedata.category(_UpperCAmelCase ) if cat.startswith('P' ): return True return False @dataclass class snake_case__ ( SCREAMING_SNAKE_CASE_ ): A__ = 42 A__ = True A__ = None A__ = None A__ = -100 A__ = '''pt''' def A_ ( self : Any , __a : Dict ) -> List[str]: '''simple docstring''' import torch __snake_case : Optional[int] = 'label' if 'label' in features[0].keys() else 'labels' __snake_case : int = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __snake_case : Union[str, Any] = self.tokenizer.pad( __a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' if labels is None else None , ) if labels is None: return batch __snake_case : Union[str, Any] = torch.tensor(batch['entity_ids'] ).shape[1] __snake_case : Union[str, Any] = self.tokenizer.padding_side if padding_side == "right": __snake_case : Tuple = [ list(__a ) + [self.label_pad_token_id] * (sequence_length - len(__a )) for label in labels ] else: __snake_case : str = [ [self.label_pad_token_id] * (sequence_length - len(__a )) + list(__a ) for label in labels ] __snake_case : Optional[Any] = [feature['ner_tags'] for feature in features] __snake_case : List[Any] = padding_tensor(__a , -1 , __a , __a ) __snake_case : List[Any] = [feature['original_entity_spans'] for feature in features] __snake_case : List[str] = padding_tensor(__a , (-1, -1) , __a , __a ) __snake_case : Optional[Any] = {k: torch.tensor(__a , dtype=torch.intaa ) for k, v in batch.items()} return batch
352
'''simple docstring''' import math def a_ ( _UpperCAmelCase : int ) -> list: __snake_case : Optional[Any] = [True] * n __snake_case : Optional[int] = False __snake_case : Dict = False __snake_case : List[Any] = True for i in range(3 ,int(n**0.5 + 1 ) ,2 ): __snake_case : Optional[int] = i * 2 while index < n: __snake_case : Union[str, Any] = False __snake_case : int = index + i __snake_case : Dict = [2] for i in range(3 ,_UpperCAmelCase ,2 ): if is_prime[i]: primes.append(_UpperCAmelCase ) return primes def a_ ( _UpperCAmelCase : int = 99_99_66_66_33_33 ) -> int: __snake_case : List[Any] = math.floor(math.sqrt(_UpperCAmelCase ) ) + 1_00 __snake_case : Tuple = prime_sieve(_UpperCAmelCase ) __snake_case : List[Any] = 0 __snake_case : List[Any] = 0 __snake_case : Optional[int] = primes[prime_index] while (last_prime**2) <= limit: __snake_case : Optional[int] = primes[prime_index + 1] __snake_case : Union[str, Any] = last_prime**2 __snake_case : Dict = next_prime**2 # Get numbers divisible by lps(current) __snake_case : Optional[Any] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) __snake_case : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps __snake_case : List[str] = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair __snake_case : Dict = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
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() A__ : List[str] = logging.get_logger(__name__) set_seed(7_7_0) A__ : Optional[Any] = { '''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''', } A__ : Tuple = { '''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''', }, } A__ : str = os.path.dirname(os.path.abspath(__file__)) A__ : Tuple = os.path.join(os.path.expanduser('''~'''), '''.cache''') A__ : List[Any] = os.path.join(os.getenv('''XDG_CACHE_HOME''', default_cache_dir), '''suno''', '''bark_v0''') def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[str]=False ) -> int: __snake_case : int = model_type if use_small: key += "_small" return os.path.join(_UpperCAmelCase ,REMOTE_MODEL_PATHS[key]['file_name'] ) def a_ ( _UpperCAmelCase : str ,_UpperCAmelCase : List[str] ) -> Any: os.makedirs(_UpperCAmelCase ,exist_ok=_UpperCAmelCase ) hf_hub_download(repo_id=_UpperCAmelCase ,filename=_UpperCAmelCase ,local_dir=_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : int=False ,_UpperCAmelCase : str="text" ) -> Optional[Any]: if model_type == "text": __snake_case : Tuple = BarkSemanticModel __snake_case : Optional[int] = BarkSemanticConfig __snake_case : str = BarkSemanticGenerationConfig elif model_type == "coarse": __snake_case : List[Any] = BarkCoarseModel __snake_case : Optional[int] = BarkCoarseConfig __snake_case : Optional[int] = BarkCoarseGenerationConfig elif model_type == "fine": __snake_case : List[Any] = BarkFineModel __snake_case : Union[str, Any] = BarkFineConfig __snake_case : Union[str, Any] = BarkFineGenerationConfig else: raise NotImplementedError() __snake_case : List[str] = f'''{model_type}_small''' if use_small else model_type __snake_case : Tuple = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(_UpperCAmelCase ): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info['repo_id'] ,model_info['file_name'] ) __snake_case : Union[str, Any] = torch.load(_UpperCAmelCase ,map_location=_UpperCAmelCase ) # this is a hack __snake_case : List[str] = checkpoint['model_args'] if "input_vocab_size" not in model_args: __snake_case : int = model_args['vocab_size'] __snake_case : List[str] = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments __snake_case : Union[str, Any] = model_args.pop('n_head' ) __snake_case : Dict = model_args.pop('n_embd' ) __snake_case : Any = model_args.pop('n_layer' ) __snake_case : Tuple = ConfigClass(**checkpoint['model_args'] ) __snake_case : List[Any] = ModelClass(config=_UpperCAmelCase ) __snake_case : Any = GenerationConfigClass() __snake_case : Tuple = model_generation_config __snake_case : Any = checkpoint['model'] # fixup checkpoint __snake_case : Union[str, Any] = '_orig_mod.' for k, v in list(state_dict.items() ): if k.startswith(_UpperCAmelCase ): # replace part of the key with corresponding layer name in HF implementation __snake_case : int = k[len(_UpperCAmelCase ) :] for old_layer_name in new_layer_name_dict: __snake_case : Dict = new_k.replace(_UpperCAmelCase ,new_layer_name_dict[old_layer_name] ) __snake_case : List[str] = state_dict.pop(_UpperCAmelCase ) __snake_case : Optional[int] = set(state_dict.keys() ) - set(model.state_dict().keys() ) __snake_case : Any = {k for k in extra_keys if not k.endswith('.attn.bias' )} __snake_case : str = set(model.state_dict().keys() ) - set(state_dict.keys() ) __snake_case : Any = {k for k in missing_keys if not k.endswith('.attn.bias' )} if len(_UpperCAmelCase ) != 0: raise ValueError(f'''extra keys found: {extra_keys}''' ) if len(_UpperCAmelCase ) != 0: raise ValueError(f'''missing keys: {missing_keys}''' ) model.load_state_dict(_UpperCAmelCase ,strict=_UpperCAmelCase ) __snake_case : List[str] = model.num_parameters(exclude_embeddings=_UpperCAmelCase ) __snake_case : Optional[Any] = checkpoint['best_val_loss'].item() logger.info(f'''model loaded: {round(n_params/1E6 ,1 )}M params, {round(_UpperCAmelCase ,3 )} loss''' ) model.eval() model.to(_UpperCAmelCase ) del checkpoint, state_dict return model def a_ ( _UpperCAmelCase : Dict ,_UpperCAmelCase : List[Any]=False ,_UpperCAmelCase : Optional[int]="text" ) -> Union[str, Any]: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() __snake_case : int = 'cpu' # do conversion on cpu __snake_case : List[Any] = _get_ckpt_path(_UpperCAmelCase ,use_small=_UpperCAmelCase ) __snake_case : Any = _load_model(_UpperCAmelCase ,_UpperCAmelCase ,model_type=_UpperCAmelCase ,use_small=_UpperCAmelCase ) # load bark initial model __snake_case : Union[str, Any] = _bark_load_model(_UpperCAmelCase ,'cpu' ,model_type=_UpperCAmelCase ,use_small=_UpperCAmelCase ) if model_type == "text": __snake_case : Optional[int] = bark_model['model'] if model.num_parameters(exclude_embeddings=_UpperCAmelCase ) != 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 __snake_case : List[Any] = 5 __snake_case : str = 10 if model_type in ["text", "coarse"]: __snake_case : Tuple = torch.randint(2_56 ,(batch_size, sequence_length) ,dtype=torch.int ) __snake_case : Optional[int] = bark_model(_UpperCAmelCase )[0] __snake_case : List[str] = model(_UpperCAmelCase ) # take last logits __snake_case : List[Any] = output_new_model_total.logits[:, [-1], :] else: __snake_case : Optional[Any] = 3 __snake_case : List[Any] = 8 __snake_case : List[str] = torch.randint(2_56 ,(batch_size, sequence_length, n_codes_total) ,dtype=torch.int ) __snake_case : str = model(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : List[str] = bark_model(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : str = 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(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) model.save_pretrained(_UpperCAmelCase ) def a_ ( _UpperCAmelCase : List[str] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Any ,_UpperCAmelCase : str ,_UpperCAmelCase : Any ,) -> int: __snake_case : int = os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : Dict = BarkSemanticConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : Dict = BarkCoarseConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : List[Any] = BarkFineConfig.from_pretrained(os.path.join(_UpperCAmelCase ,'config.json' ) ) __snake_case : Dict = EncodecConfig.from_pretrained('facebook/encodec_24khz' ) __snake_case : List[Any] = BarkSemanticModel.from_pretrained(_UpperCAmelCase ) __snake_case : Dict = BarkCoarseModel.from_pretrained(_UpperCAmelCase ) __snake_case : Dict = BarkFineModel.from_pretrained(_UpperCAmelCase ) __snake_case : Any = EncodecModel.from_pretrained('facebook/encodec_24khz' ) __snake_case : Tuple = BarkConfig.from_sub_model_configs( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) __snake_case : List[str] = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config ,coarseAcoustic.generation_config ,fineAcoustic.generation_config ) __snake_case : str = BarkModel(_UpperCAmelCase ) __snake_case : Tuple = semantic __snake_case : Any = coarseAcoustic __snake_case : Tuple = fineAcoustic __snake_case : Any = codec __snake_case : Optional[int] = bark_generation_config Path(_UpperCAmelCase ).mkdir(exist_ok=_UpperCAmelCase ) bark.save_pretrained(_UpperCAmelCase ,repo_id=_UpperCAmelCase ,push_to_hub=_UpperCAmelCase ) if __name__ == "__main__": A__ : List[Any] = 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.''') A__ : Dict = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
353
'''simple docstring''' def a_ ( _UpperCAmelCase : float ,_UpperCAmelCase : float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(F"""{price_plus_tax(1_0_0, 0.25) = }""") print(F"""{price_plus_tax(1_25.50, 0.05) = }""")
0
0