code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import unittest import numpy as np from transformers import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING, TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING from transformers.pipelines import AudioClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_torchaudio, slow, ) from .test_pipelines_common import ANY @is_pipeline_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' __snake_case = MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING __snake_case = TF_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] ) ->List[str]: """simple docstring""" a = AudioClassificationPipeline(model=__UpperCAmelCase , feature_extractor=__UpperCAmelCase ) # test with a raw waveform a = np.zeros((34_000,) ) a = np.zeros((14_000,) ) return audio_classifier, [audioa, audio] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict ) ->Any: """simple docstring""" a , a = examples a = audio_classifier(__UpperCAmelCase ) # by default a model is initialized with num_labels=2 self.assertEqual( __UpperCAmelCase , [ {'''score''': ANY(__UpperCAmelCase ), '''label''': ANY(__UpperCAmelCase )}, {'''score''': ANY(__UpperCAmelCase ), '''label''': ANY(__UpperCAmelCase )}, ] , ) a = audio_classifier(__UpperCAmelCase , top_k=1 ) self.assertEqual( __UpperCAmelCase , [ {'''score''': ANY(__UpperCAmelCase ), '''label''': ANY(__UpperCAmelCase )}, ] , ) self.run_torchaudio(__UpperCAmelCase ) @require_torchaudio def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Dict ) ->Dict: """simple docstring""" import datasets # test with a local file a = datasets.load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) a = dataset[0]['''audio''']['''array'''] a = audio_classifier(__UpperCAmelCase ) self.assertEqual( __UpperCAmelCase , [ {'''score''': ANY(__UpperCAmelCase ), '''label''': ANY(__UpperCAmelCase )}, {'''score''': ANY(__UpperCAmelCase ), '''label''': ANY(__UpperCAmelCase )}, ] , ) @require_torch def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" a = '''anton-l/wav2vec2-random-tiny-classifier''' a = pipeline('''audio-classification''' , model=__UpperCAmelCase ) a = np.ones((8_000,) ) a = audio_classifier(__UpperCAmelCase , top_k=4 ) a = [ {'''score''': 0.0842, '''label''': '''no'''}, {'''score''': 0.0838, '''label''': '''up'''}, {'''score''': 0.0837, '''label''': '''go'''}, {'''score''': 0.0834, '''label''': '''right'''}, ] a = [ {'''score''': 0.0845, '''label''': '''stop'''}, {'''score''': 0.0844, '''label''': '''on'''}, {'''score''': 0.0841, '''label''': '''right'''}, {'''score''': 0.0834, '''label''': '''left'''}, ] self.assertIn(nested_simplify(__UpperCAmelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) a = {'''array''': np.ones((8_000,) ), '''sampling_rate''': audio_classifier.feature_extractor.sampling_rate} a = audio_classifier(__UpperCAmelCase , top_k=4 ) self.assertIn(nested_simplify(__UpperCAmelCase , decimals=4 ) , [EXPECTED_OUTPUT, EXPECTED_OUTPUT_PT_2] ) @require_torch @slow def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" import datasets a = '''superb/wav2vec2-base-superb-ks''' a = pipeline('''audio-classification''' , model=__UpperCAmelCase ) a = datasets.load_dataset('''anton-l/superb_dummy''' , '''ks''' , split='''test''' ) a = np.array(dataset[3]['''speech'''] , dtype=np.floataa ) a = audio_classifier(__UpperCAmelCase , top_k=4 ) self.assertEqual( nested_simplify(__UpperCAmelCase , decimals=3 ) , [ {'''score''': 0.981, '''label''': '''go'''}, {'''score''': 0.007, '''label''': '''up'''}, {'''score''': 0.006, '''label''': '''_unknown_'''}, {'''score''': 0.001, '''label''': '''down'''}, ] , ) @require_tf @unittest.skip('''Audio classification is not implemented for TF''' ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" pass
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class lowercase_ : '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Any , __UpperCAmelCase : Any , __UpperCAmelCase : bool = True , __UpperCAmelCase : bool = False ) ->Dict: """simple docstring""" a = scheduler a = optimizers if isinstance(__UpperCAmelCase , (list, tuple) ) else [optimizers] a = split_batches a = step_with_optimizer a = GradientState() def __lowerCAmelCase ( self : int , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : str ) ->str: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step a = AcceleratorState().num_processes for _ in range(__UpperCAmelCase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" return self.scheduler.get_last_lr() def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return self.scheduler.state_dict() def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" self.scheduler.load_state_dict(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" return self.scheduler.get_lr() def __lowerCAmelCase ( self : Union[str, Any] , *__UpperCAmelCase : str , **__UpperCAmelCase : Any ) ->Union[str, Any]: """simple docstring""" return self.scheduler.print_lr(*__UpperCAmelCase , **__UpperCAmelCase )
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
def _a ( ) -> Optional[int]: a = 0 for i in range(1 , 1_001 ): total += i**i return str(a )[-10:] if __name__ == "__main__": print(solution())
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class lowercase_ : '''simple docstring''' def __init__( self : str ) ->int: """simple docstring""" a = '''''' a = '''''' a = [] a = 0 a = 256 a = 0 a = 0 a = 0 a = 0 def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = cva.imread(__UpperCAmelCase , 0 ) a = copy.deepcopy(self.img ) a , a , a = plt.hist(self.img.ravel() , 256 , [0, 256] , label='''x''' ) a = np.sum(__UpperCAmelCase ) for i in range(len(__UpperCAmelCase ) ): a = x[i] / self.k self.sk += prk a = (self.L - 1) * self.sk if self.rem != 0: a = int(last % last ) a = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__UpperCAmelCase ) a = int(np.ma.count(self.img ) / self.img[1].size ) a = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a = self.img[j][i] if num != self.last_list[num]: a = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(5_000 ) cva.destroyAllWindows() if __name__ == "__main__": UpperCAmelCase__ = os.path.join(os.path.basename(__file__), "image_data/input.jpg") UpperCAmelCase__ = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''char''' __snake_case = '''bpe''' __snake_case = '''wp''' UpperCAmelCase__ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = ['''image_processor''', '''char_tokenizer'''] __snake_case = '''ViTImageProcessor''' __snake_case = '''MgpstrTokenizer''' def __init__( self : Optional[int] , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Dict=None , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) a = kwargs.pop('''feature_extractor''' ) a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) a = tokenizer a = AutoTokenizer.from_pretrained('''gpt2''' ) a = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self : List[str] , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : List[str] ) ->List[Any]: """simple docstring""" if images is None and text is None: raise ValueError('''You need to specify either an `images` or `text` input to process.''' ) if images is not None: a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None: a = self.char_tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: a = encodings['''input_ids'''] return inputs def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[Any] ) ->List[Any]: """simple docstring""" a , a , a = sequences a = char_preds.size(0 ) a , a = self._decode_helper(__UpperCAmelCase , '''char''' ) a , a = self._decode_helper(__UpperCAmelCase , '''bpe''' ) a , a = self._decode_helper(__UpperCAmelCase , '''wp''' ) a = [] a = [] for i in range(__UpperCAmelCase ): a = [char_scores[i], bpe_scores[i], wp_scores[i]] a = [char_strs[i], bpe_strs[i], wp_strs[i]] a = scores.index(max(__UpperCAmelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) a = {} a = final_strs a = final_scores a = char_strs a = bpe_strs a = wp_strs return out def __lowerCAmelCase ( self : int , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str ) ->int: """simple docstring""" if format == DecodeType.CHARACTER: a = self.char_decode a = 1 a = '''[s]''' elif format == DecodeType.BPE: a = self.bpe_decode a = 2 a = '''#''' elif format == DecodeType.WORDPIECE: a = self.wp_decode a = 102 a = '''[SEP]''' else: raise ValueError(F"""Format {format} is not supported.""" ) a , a = [], [] a = pred_logits.size(0 ) a = pred_logits.size(1 ) a , a = pred_logits.topk(1 , dim=-1 , largest=__UpperCAmelCase , sorted=__UpperCAmelCase ) a = preds_index.view(-1 , __UpperCAmelCase )[:, 1:] a = decoder(__UpperCAmelCase ) a , a = torch.nn.functional.softmax(__UpperCAmelCase , dim=2 ).max(dim=2 ) a = preds_max_prob[:, 1:] for index in range(__UpperCAmelCase ): a = preds_str[index].find(__UpperCAmelCase ) a = preds_str[index][:pred_eos] a = preds_index[index].cpu().tolist() a = pred_index.index(__UpperCAmelCase ) if eos_token in pred_index else -1 a = preds_max_prob[index][: pred_eos_index + 1] a = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__UpperCAmelCase ) conf_scores.append(__UpperCAmelCase ) return dec_strs, conf_scores def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(__UpperCAmelCase )] return decode_strs def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[Any] ) ->List[Any]: """simple docstring""" return self.bpe_tokenizer.batch_decode(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : List[Any] ) ->List[Any]: """simple docstring""" a = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(__UpperCAmelCase )] return decode_strs
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "huggingface/informer-tourism-monthly": ( "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json" ), # See all Informer models at https://huggingface.co/models?filter=informer } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''informer''' __snake_case = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : str = "student_t" , __UpperCAmelCase : str = "nll" , __UpperCAmelCase : int = 1 , __UpperCAmelCase : List[int] = None , __UpperCAmelCase : Optional[Union[str, bool]] = "mean" , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : int = 64 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : bool = True , __UpperCAmelCase : str = "gelu" , __UpperCAmelCase : float = 0.05 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : int = 100 , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : str=True , __UpperCAmelCase : str = "prob" , __UpperCAmelCase : int = 5 , __UpperCAmelCase : bool = True , **__UpperCAmelCase : List[str] , ) ->str: """simple docstring""" a = prediction_length a = context_length or prediction_length a = distribution_output a = loss a = input_size a = num_time_features a = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7] a = scaling a = num_dynamic_real_features a = num_static_real_features a = num_static_categorical_features # set cardinality if cardinality and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) a = cardinality else: a = [0] # set embedding_dimension if embedding_dimension and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) a = embedding_dimension else: a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] a = num_parallel_samples # Transformer architecture configuration a = input_size * len(self.lags_sequence ) + self._number_of_features a = d_model a = encoder_attention_heads a = decoder_attention_heads a = encoder_ffn_dim a = decoder_ffn_dim a = encoder_layers a = decoder_layers a = dropout a = attention_dropout a = activation_dropout a = encoder_layerdrop a = decoder_layerdrop a = activation_function a = init_std a = use_cache # Informer a = attention_type a = sampling_factor a = distil super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Tuple ) ->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 )
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "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" ), }, } UpperCAmelCase__ = { "google/electra-small-generator": 512, "google/electra-base-generator": 512, "google/electra-large-generator": 512, "google/electra-small-discriminator": 512, "google/electra-base-discriminator": 512, "google/electra-large-discriminator": 512, } UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ElectraTokenizer def __init__( self : Dict , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Any="[SEP]" , __UpperCAmelCase : str="[PAD]" , __UpperCAmelCase : Optional[Any]="[CLS]" , __UpperCAmelCase : Union[str, Any]="[MASK]" , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] , ) ->str: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple=None ) ->str: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
0
1
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def _a ( a :List[str] ) -> str: a , a = image.size a , a = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a = np.array(a ).astype(np.floataa ) / 255.0 a = image[None].transpose(0 , 3 , 1 , 2 ) a = torch.from_numpy(a ) return 2.0 * image - 1.0 class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[Any] , __UpperCAmelCase : VQModel , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) ->Dict: """simple docstring""" super().__init__() self.register_modules(vqvae=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) @torch.no_grad() def __call__( self : str , __UpperCAmelCase : Union[torch.Tensor, PIL.Image.Image] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : Optional[int] = 100 , __UpperCAmelCase : Optional[float] = 0.0 , __UpperCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __UpperCAmelCase : Optional[str] = "pil" , __UpperCAmelCase : bool = True , ) ->Union[Tuple, ImagePipelineOutput]: """simple docstring""" if isinstance(__UpperCAmelCase , PIL.Image.Image ): a = 1 elif isinstance(__UpperCAmelCase , torch.Tensor ): a = image.shape[0] else: raise ValueError(F"""`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(__UpperCAmelCase )}""" ) if isinstance(__UpperCAmelCase , PIL.Image.Image ): a = preprocess(__UpperCAmelCase ) a , a = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a = (batch_size, self.unet.config.in_channels // 2, height, width) a = next(self.unet.parameters() ).dtype a = randn_tensor(__UpperCAmelCase , generator=__UpperCAmelCase , device=self.device , dtype=__UpperCAmelCase ) a = image.to(device=self.device , dtype=__UpperCAmelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(__UpperCAmelCase , device=self.device ) a = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a = {} if accepts_eta: a = eta for t in self.progress_bar(__UpperCAmelCase ): # concat latents and low resolution image in the channel dimension. a = torch.cat([latents, image] , dim=1 ) a = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase ) # predict the noise residual a = self.unet(__UpperCAmelCase , __UpperCAmelCase ).sample # compute the previous noisy sample x_t -> x_t-1 a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample # decode the image latents with the VQVAE a = self.vqvae.decode(__UpperCAmelCase ).sample a = torch.clamp(__UpperCAmelCase , -1.0 , 1.0 ) a = image / 2 + 0.5 a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a = self.numpy_to_pil(__UpperCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=__UpperCAmelCase )
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
from __future__ import annotations import math import random from typing import Any class lowercase_ : '''simple docstring''' def __init__( self : List[str] ) ->None: """simple docstring""" a = [] a = 0 a = 0 def __lowerCAmelCase ( self : str ) ->bool: """simple docstring""" return self.head == self.tail def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any ) ->None: """simple docstring""" self.data.append(__UpperCAmelCase ) a = self.tail + 1 def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.data[self.head] a = self.head + 1 return ret def __lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" return self.tail - self.head def __lowerCAmelCase ( self : Optional[int] ) ->None: """simple docstring""" print(self.data ) print('''**************''' ) print(self.data[self.head : self.tail] ) class lowercase_ : '''simple docstring''' def __init__( self : int , __UpperCAmelCase : Any ) ->None: """simple docstring""" a = data a = None a = None a = 1 def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" return self.data def __lowerCAmelCase ( self : List[Any] ) ->MyNode | None: """simple docstring""" return self.left def __lowerCAmelCase ( self : List[str] ) ->MyNode | None: """simple docstring""" return self.right def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" return self.height def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Any ) ->None: """simple docstring""" a = data def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : MyNode | None ) ->None: """simple docstring""" a = node def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : MyNode | None ) ->None: """simple docstring""" a = node def __lowerCAmelCase ( self : Any , __UpperCAmelCase : int ) ->None: """simple docstring""" a = height def _a ( a :MyNode | None ) -> int: if node is None: return 0 return node.get_height() def _a ( a :int , a :int ) -> int: if a > b: return a return b def _a ( a :MyNode ) -> MyNode: print('''left rotation node:''' , node.get_data() ) a = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(a ) a = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) a = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def _a ( a :MyNode ) -> MyNode: print('''right rotation node:''' , node.get_data() ) a = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(a ) a = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) a = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(a ) return ret def _a ( a :MyNode ) -> MyNode: a = node.get_left() assert left_child is not None node.set_left(left_rotation(a ) ) return right_rotation(a ) def _a ( a :MyNode ) -> MyNode: a = node.get_right() assert right_child is not None node.set_right(right_rotation(a ) ) return left_rotation(a ) def _a ( a :MyNode | None , a :Any ) -> MyNode | None: if node is None: return MyNode(a ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , a ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected a = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child a = right_rotation(a ) else: a = lr_rotation(a ) else: node.set_right(insert_node(node.get_right() , a ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: a = node.get_right() assert right_child is not None if data < right_child.get_data(): a = rl_rotation(a ) else: a = left_rotation(a ) a = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(a ) return node def _a ( a :MyNode ) -> Any: while True: a = root.get_right() if right_child is None: break a = right_child return root.get_data() def _a ( a :MyNode ) -> Any: while True: a = root.get_left() if left_child is None: break a = left_child return root.get_data() def _a ( a :MyNode , a :Any ) -> MyNode | None: a = root.get_left() a = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: a = get_left_most(a ) root.set_data(a ) root.set_right(del_node(a , a ) ) elif left_child is not None: a = left_child elif right_child is not None: a = right_child else: return None elif root.get_data() > data: if left_child is None: print('''No such data''' ) return root else: root.set_left(del_node(a , a ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(a , a ) ) if get_height(a ) - get_height(a ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): a = left_rotation(a ) else: a = rl_rotation(a ) elif get_height(a ) - get_height(a ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): a = right_rotation(a ) else: a = lr_rotation(a ) a = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(a ) return root class lowercase_ : '''simple docstring''' def __init__( self : int ) ->None: """simple docstring""" a = None def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" return get_height(self.root ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Any ) ->None: """simple docstring""" print('''insert:''' + str(__UpperCAmelCase ) ) a = insert_node(self.root , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Any ) ->None: """simple docstring""" print('''delete:''' + str(__UpperCAmelCase ) ) if self.root is None: print('''Tree is empty!''' ) return a = del_node(self.root , __UpperCAmelCase ) def __str__( self : List[Any] , ) ->str: # a level traversale, gives a more intuitive look on the tree """simple docstring""" a = '''''' a = MyQueue() q.push(self.root ) a = self.get_height() if layer == 0: return output a = 0 while not q.is_empty(): a = q.pop() a = ''' ''' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(__UpperCAmelCase ) q.push(__UpperCAmelCase ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space a = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , __UpperCAmelCase ) - 1: a = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def _a ( ) -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() UpperCAmelCase__ = AVLtree() UpperCAmelCase__ = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
1
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
1
import math def _a ( a :int ) -> bool: assert isinstance(a , a ) 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 a = range(3 , int(math.sqrt(a ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( a :int , a :Optional[int]=1 , **a :List[str] ) -> str: a = factor * value a = value while not is_prime(a ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **a ) return value
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {} class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''llama''' __snake_case = ['''past_key_values'''] def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]=32_000 , __UpperCAmelCase : str=4_096 , __UpperCAmelCase : int=11_008 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]="silu" , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Any=1e-6 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Tuple , ) ->str: """simple docstring""" a = vocab_size a = max_position_embeddings a = hidden_size a = intermediate_size a = num_hidden_layers a = num_attention_heads # for backward compatibility if num_key_value_heads is None: a = num_attention_heads a = num_key_value_heads a = hidden_act a = initializer_range a = rms_norm_eps a = pretraining_tp a = use_cache a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) 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}""" ) a = self.rope_scaling.get('''type''' , __UpperCAmelCase ) a = self.rope_scaling.get('''factor''' , __UpperCAmelCase ) 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(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
0
1
from __future__ import annotations UpperCAmelCase__ = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class lowercase_ : '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : dict[str, list[str]] , __UpperCAmelCase : str ) ->None: """simple docstring""" a = graph # mapping node to its parent in resulting breadth first tree a = {} a = source_vertex def __lowerCAmelCase ( self : Union[str, Any] ) ->None: """simple docstring""" a = {self.source_vertex} a = None a = [self.source_vertex] # first in first out queue while queue: a = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__UpperCAmelCase ) a = vertex queue.append(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : str ) ->str: """simple docstring""" if target_vertex == self.source_vertex: return self.source_vertex a = self.parent.get(__UpperCAmelCase ) if target_vertex_parent is None: a = ( F"""No path from vertex: {self.source_vertex} to vertex: {target_vertex}""" ) raise ValueError(__UpperCAmelCase ) return self.shortest_path(__UpperCAmelCase ) + F"""->{target_vertex}""" if __name__ == "__main__": UpperCAmelCase__ = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _a ( ) -> Any: a = ArgumentParser( description=( '''PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=a , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=a , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=a ) return parser.parse_args() def _a ( ) -> Tuple: a = parse_args() # Import training_script as a module. a = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) a = script_fpath.stem a = importlib.import_module(a ) # Patch sys.argv a = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1
import tempfile import unittest from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from transformers.testing_utils import ( is_torch_available, require_optimum, require_torch, slow, ) if is_torch_available(): import torch @require_torch @require_optimum @slow class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" a = '''hf-internal-testing/tiny-random-t5''' a = AutoTokenizer.from_pretrained(__UpperCAmelCase ) a = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) a = tokenizer('''This is me''' , return_tensors='''pt''' ) a = model.to_bettertransformer() self.assertTrue(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) a = model.generate(**__UpperCAmelCase ) a = model.reverse_bettertransformer() self.assertFalse(any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model.named_modules() ) ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__UpperCAmelCase ) a = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) self.assertFalse( any('''BetterTransformer''' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) ) a = model_reloaded.generate(**__UpperCAmelCase ) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" a = '''hf-internal-testing/tiny-random-t5''' a = AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase ) a = model.to_bettertransformer() with tempfile.TemporaryDirectory() as tmpdirname: with self.assertRaises(__UpperCAmelCase ): model.save_pretrained(__UpperCAmelCase ) a = model.reverse_bettertransformer() model.save_pretrained(__UpperCAmelCase )
0
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file UpperCAmelCase__ = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def _a ( a :int=None ) -> Optional[Any]: if subparsers is not None: a = subparsers.add_parser('''tpu-config''' , description=_description ) else: a = argparse.ArgumentParser('''Accelerate tpu-config command''' , description=_description ) # Core arguments a = parser.add_argument_group( '''Config Arguments''' , '''Arguments that can be configured through `accelerate config`.''' ) config_args.add_argument( '''--config_file''' , type=a , default=a , help='''Path to the config file to use for accelerate.''' , ) config_args.add_argument( '''--tpu_name''' , default=a , help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''' , ) config_args.add_argument( '''--tpu_zone''' , default=a , help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''' , ) a = parser.add_argument_group('''TPU Arguments''' , '''Arguments for options ran inside the TPU.''' ) pod_args.add_argument( '''--use_alpha''' , action='''store_true''' , help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''' , ) pod_args.add_argument( '''--command_file''' , default=a , help='''The path to the file containing the commands to run on the pod on startup.''' , ) pod_args.add_argument( '''--command''' , action='''append''' , nargs='''+''' , help='''A command to run on the pod. Can be passed multiple times.''' , ) pod_args.add_argument( '''--install_accelerate''' , action='''store_true''' , help='''Whether to install accelerate on the pod. Defaults to False.''' , ) pod_args.add_argument( '''--accelerate_version''' , default='''latest''' , help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''' , ) pod_args.add_argument( '''--debug''' , action='''store_true''' , help='''If set, will print the command that would be run instead of running it.''' ) if subparsers is not None: parser.set_defaults(func=a ) return parser def _a ( a :int ) -> str: a = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(a ): a = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: a = defaults.command_file if not args.command and defaults.commands is not None: a = defaults.commands if not args.tpu_name: a = defaults.tpu_name if not args.tpu_zone: a = defaults.tpu_zone if args.accelerate_version == "dev": a = '''git+https://github.com/huggingface/accelerate.git''' elif args.accelerate_version == "latest": a = '''accelerate -U''' elif isinstance(parse(args.accelerate_version ) , a ): a = F"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError('''You must specify either a command file or a command to run on the pod.''' ) if args.command_file: with open(args.command_file , '''r''' ) as f: a = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , a ): a = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate a = ['''cd /usr/share'''] if args.install_accelerate: new_cmd += [F"""pip install {args.accelerate_version}"""] new_cmd += args.command a = '''; '''.join(a ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess a = ['''gcloud'''] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F"""Running {' '.join(a )}""" ) return subprocess.run(a ) print('''Successfully setup pod.''' ) def _a ( ) -> Any: a = tpu_command_parser() a = parser.parse_args() tpu_command_launcher(a )
0
def _a ( a :float , a :float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
0
1
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
1
import torch from diffusers import DiffusionPipeline class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Union[str, Any] ) ->Optional[Any]: """simple docstring""" super().__init__() self.register_modules(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) def __call__( self : Tuple ) ->List[Any]: """simple docstring""" a = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) a = 1 a = self.unet(__UpperCAmelCase , __UpperCAmelCase ).sample a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample a = scheduler_output - scheduler_output + torch.ones_like(__UpperCAmelCase ) return result
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ProphetNetTokenizer __snake_case = False def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = '''UNwant\u00E9d,running''' a = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__UpperCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , 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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] a = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : Any ) ->List[str]: """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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _a ( a :int , a :List[Any] , a :Optional[Any] , a :Tuple , a :Dict ) -> List[str]: # Load configuration defined in the metadata file with open(a ) as metadata_file: a = json.load(a ) a = LukeConfig(use_entity_aware_attention=a , **metadata['''model_config'''] ) # Load in the weights from the checkpoint_path a = torch.load(a , map_location='''cpu''' ) # Load the entity vocab file a = load_entity_vocab(a ) a = RobertaTokenizer.from_pretrained(metadata['''model_config''']['''bert_model_name'''] ) # Add special tokens to the token vocabulary for downstream tasks a = AddedToken('''<ent>''' , lstrip=a , rstrip=a ) a = AddedToken('''<ent2>''' , lstrip=a , rstrip=a ) tokenizer.add_special_tokens({'''additional_special_tokens''': [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"""Saving tokenizer to {pytorch_dump_folder_path}""" ) tokenizer.save_pretrained(a ) with open(os.path.join(a , LukeTokenizer.vocab_files_names['''entity_vocab_file'''] ) , '''w''' ) as f: json.dump(a , a ) a = LukeTokenizer.from_pretrained(a ) # Initialize the embeddings of the special tokens a = state_dict['''embeddings.word_embeddings.weight'''] a = word_emb[tokenizer.convert_tokens_to_ids(['''@'''] )[0]].unsqueeze(0 ) a = word_emb[tokenizer.convert_tokens_to_ids(['''#'''] )[0]].unsqueeze(0 ) a = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: a = F"""encoder.layer.{layer_index}.attention.self.""" a = state_dict[prefix + matrix_name] a = state_dict[prefix + matrix_name] a = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks a = state_dict['''entity_embeddings.entity_embeddings.weight'''] a = entity_emb[entity_vocab['''[MASK]''']] a = LukeModel(config=a ).eval() a , a = model.load_state_dict(a , strict=a ) if not (len(a ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(F"""Missing keys {', '.join(a )}. Expected only missing embeddings.position_ids""" ) if not (all(key.startswith('''entity_predictions''' ) or key.startswith('''lm_head''' ) for key in unexpected_keys )): raise ValueError( '''Unexpected keys''' F""" {', '.join([key for key in unexpected_keys if not (key.startswith('entity_predictions' ) or key.startswith('lm_head' ))] )}""" ) # Check outputs a = LukeTokenizer.from_pretrained(a , task='''entity_classification''' ) a = ( '''Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the''' ''' new world number one avoid a humiliating second- round exit at Wimbledon .''' ) a = (39, 42) a = tokenizer(a , entity_spans=[span] , add_prefix_space=a , return_tensors='''pt''' ) a = model(**a ) # Verify word hidden states if model_size == "large": a = torch.Size((1, 42, 1_024) ) a = torch.tensor( [[0.0_133, 0.0_865, 0.0_095], [0.3_093, -0.2_576, -0.7_418], [-0.1_720, -0.2_117, -0.2_869]] ) else: # base a = torch.Size((1, 42, 768) ) a = torch.tensor([[0.0_037, 0.1_368, -0.0_091], [0.1_099, 0.3_329, -0.1_095], [0.0_765, 0.5_335, 0.1_179]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": a = torch.Size((1, 1, 1_024) ) a = torch.tensor([[0.0_466, -0.0_106, -0.0_179]] ) else: # base a = torch.Size((1, 1, 768) ) a = torch.tensor([[0.1_457, 0.1_044, 0.0_174]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( F"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is""" F""" {expected_shape}""" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , a , atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print('''Saving PyTorch model to {}'''.format(a ) ) model.save_pretrained(a ) def _a ( a :str ) -> List[Any]: a = {} with open(a , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(a ): a , a = line.rstrip().split('''\t''' ) a = index return entity_vocab if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) UpperCAmelCase__ = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
from math import pi def _a ( a :int , a :int ) -> float: return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(90, 10))
0
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
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() UpperCAmelCase__ = logging.get_logger(__name__) set_seed(770) UpperCAmelCase__ = { "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", } UpperCAmelCase__ = { "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", }, } UpperCAmelCase__ = os.path.dirname(os.path.abspath(__file__)) UpperCAmelCase__ = os.path.join(os.path.expanduser("~"), ".cache") UpperCAmelCase__ = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def _a ( a :List[str] , a :Union[str, Any]=False ) -> List[Any]: a = model_type if use_small: key += "_small" return os.path.join(a , REMOTE_MODEL_PATHS[key]['''file_name'''] ) def _a ( a :Any , a :Optional[Any] ) -> Tuple: os.makedirs(a , exist_ok=a ) hf_hub_download(repo_id=a , filename=a , local_dir=a ) def _a ( a :Union[str, Any] , a :Optional[Any] , a :Optional[Any]=False , a :Optional[Any]="text" ) -> List[str]: if model_type == "text": a = BarkSemanticModel a = BarkSemanticConfig a = BarkSemanticGenerationConfig elif model_type == "coarse": a = BarkCoarseModel a = BarkCoarseConfig a = BarkCoarseGenerationConfig elif model_type == "fine": a = BarkFineModel a = BarkFineConfig a = BarkFineGenerationConfig else: raise NotImplementedError() a = F"""{model_type}_small""" if use_small else model_type a = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a ): logger.info(F"""{model_type} model not found, downloading into `{CACHE_DIR}`.""" ) _download(model_info['''repo_id'''] , model_info['''file_name'''] ) a = torch.load(a , map_location=a ) # this is a hack a = checkpoint['''model_args'''] if "input_vocab_size" not in model_args: a = model_args['''vocab_size'''] a = model_args['''vocab_size'''] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments a = model_args.pop('''n_head''' ) a = model_args.pop('''n_embd''' ) a = model_args.pop('''n_layer''' ) a = ConfigClass(**checkpoint['''model_args'''] ) a = ModelClass(config=a ) a = GenerationConfigClass() a = model_generation_config a = checkpoint['''model'''] # fixup checkpoint a = '''_orig_mod.''' for k, v in list(state_dict.items() ): if k.startswith(a ): # replace part of the key with corresponding layer name in HF implementation a = k[len(a ) :] for old_layer_name in new_layer_name_dict: a = new_k.replace(a , new_layer_name_dict[old_layer_name] ) a = state_dict.pop(a ) a = set(state_dict.keys() ) - set(model.state_dict().keys() ) a = {k for k in extra_keys if not k.endswith('''.attn.bias''' )} a = set(model.state_dict().keys() ) - set(state_dict.keys() ) a = {k for k in missing_keys if not k.endswith('''.attn.bias''' )} if len(a ) != 0: raise ValueError(F"""extra keys found: {extra_keys}""" ) if len(a ) != 0: raise ValueError(F"""missing keys: {missing_keys}""" ) model.load_state_dict(a , strict=a ) a = model.num_parameters(exclude_embeddings=a ) a = checkpoint['''best_val_loss'''].item() logger.info(F"""model loaded: {round(n_params/1e6 , 1 )}M params, {round(a , 3 )} loss""" ) model.eval() model.to(a ) del checkpoint, state_dict return model def _a ( a :Any , a :List[str]=False , a :Dict="text" ) -> Any: if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() a = '''cpu''' # do conversion on cpu a = _get_ckpt_path(a , use_small=a ) a = _load_model(a , a , model_type=a , use_small=a ) # load bark initial model a = _bark_load_model(a , '''cpu''' , model_type=a , use_small=a ) if model_type == "text": a = bark_model['''model'''] if model.num_parameters(exclude_embeddings=a ) != 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 a = 5 a = 10 if model_type in ["text", "coarse"]: a = torch.randint(256 , (batch_size, sequence_length) , dtype=torch.int ) a = bark_model(a )[0] a = model(a ) # take last logits a = output_new_model_total.logits[:, [-1], :] else: a = 3 a = 8 a = torch.randint(256 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) a = model(a , a ) a = bark_model(a , a ) a = 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(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) def _a ( a :int , a :Optional[Any] , a :Dict , a :List[str] , a :Tuple , a :Optional[int] , ) -> Union[str, Any]: a = os.path.join(a , a ) a = BarkSemanticConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) a = BarkCoarseConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) a = BarkFineConfig.from_pretrained(os.path.join(a , '''config.json''' ) ) a = EncodecConfig.from_pretrained('''facebook/encodec_24khz''' ) a = BarkSemanticModel.from_pretrained(a ) a = BarkCoarseModel.from_pretrained(a ) a = BarkFineModel.from_pretrained(a ) a = EncodecModel.from_pretrained('''facebook/encodec_24khz''' ) a = BarkConfig.from_sub_model_configs( a , a , a , a ) a = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) a = BarkModel(a ) a = semantic a = coarseAcoustic a = fineAcoustic a = codec a = bark_generation_config Path(a ).mkdir(exist_ok=a ) bark.save_pretrained(a , repo_id=a , push_to_hub=a ) if __name__ == "__main__": UpperCAmelCase__ = 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.") UpperCAmelCase__ = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
0
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)] ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Any ) ->str: """simple docstring""" a = GenerationConfig( do_sample=__UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__UpperCAmelCase , config_name=__UpperCAmelCase ) a = GenerationConfig.from_pretrained(__UpperCAmelCase , config_name=__UpperCAmelCase ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , __UpperCAmelCase ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" a = AutoConfig.from_pretrained('''gpt2''' ) a = GenerationConfig.from_model_config(__UpperCAmelCase ) a = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(__UpperCAmelCase , __UpperCAmelCase ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def __lowerCAmelCase ( self : Optional[int] ) ->Optional[int]: """simple docstring""" a = GenerationConfig() a = { '''max_new_tokens''': 1_024, '''foo''': '''bar''', } a = copy.deepcopy(__UpperCAmelCase ) a = generation_config.update(**__UpperCAmelCase ) # update_kwargs was not modified (no side effects) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1_024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(__UpperCAmelCase , {'''foo''': '''bar'''} ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = GenerationConfig() a = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''' ) as tmp_dir: generation_config.save_pretrained(__UpperCAmelCase ) a = GenerationConfig.from_pretrained(__UpperCAmelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''' ) a = GenerationConfig.from_model_config(__UpperCAmelCase ) assert not hasattr(__UpperCAmelCase , '''foo''' ) # no new kwargs should be initialized if from config def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , __UpperCAmelCase ) self.assertEqual(default_config.num_beams , 1 ) a = GenerationConfig( do_sample=__UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , __UpperCAmelCase ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__UpperCAmelCase ) a = GenerationConfig.from_pretrained(__UpperCAmelCase , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , __UpperCAmelCase ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : List[Any] ) ->Dict: """simple docstring""" a = TOKEN HfFolder.save_token(__UpperCAmelCase ) @classmethod def __lowerCAmelCase ( cls : List[str] ) ->int: """simple docstring""" try: delete_repo(token=cls._token , repo_id='''test-generation-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''' ) except HTTPError: pass def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" a = GenerationConfig( do_sample=__UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token ) a = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__UpperCAmelCase , getattr(__UpperCAmelCase , __UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __UpperCAmelCase , repo_id='''test-generation-config''' , push_to_hub=__UpperCAmelCase , use_auth_token=self._token ) a = GenerationConfig.from_pretrained(F"""{USER}/test-generation-config""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__UpperCAmelCase , getattr(__UpperCAmelCase , __UpperCAmelCase ) ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = GenerationConfig( do_sample=__UpperCAmelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token ) a = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__UpperCAmelCase , getattr(__UpperCAmelCase , __UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __UpperCAmelCase , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=__UpperCAmelCase , use_auth_token=self._token ) a = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__UpperCAmelCase , getattr(__UpperCAmelCase , __UpperCAmelCase ) )
0
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''markuplm''' def __init__( self : Union[str, Any] , __UpperCAmelCase : int=30_522 , __UpperCAmelCase : Optional[Any]=768 , __UpperCAmelCase : List[str]=12 , __UpperCAmelCase : Dict=12 , __UpperCAmelCase : Tuple=3_072 , __UpperCAmelCase : Optional[Any]="gelu" , __UpperCAmelCase : List[Any]=0.1 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : str=512 , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : Tuple=0.02 , __UpperCAmelCase : Dict=1e-1_2 , __UpperCAmelCase : int=0 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : Optional[Any]=2 , __UpperCAmelCase : List[Any]=256 , __UpperCAmelCase : Dict=1_024 , __UpperCAmelCase : Optional[int]=216 , __UpperCAmelCase : str=1_001 , __UpperCAmelCase : int=32 , __UpperCAmelCase : Union[str, Any]=50 , __UpperCAmelCase : Any="absolute" , __UpperCAmelCase : Any=True , __UpperCAmelCase : List[str]=None , **__UpperCAmelCase : Union[str, Any] , ) ->str: """simple docstring""" super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase , ) a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = position_embedding_type a = use_cache a = classifier_dropout # additional properties a = max_depth a = max_xpath_tag_unit_embeddings a = max_xpath_subs_unit_embeddings a = tag_pad_id a = subs_pad_id a = xpath_unit_hidden_size
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
1
from typing import List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "huggingface/autoformer-tourism-monthly": "https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''autoformer''' __snake_case = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', '''num_hidden_layers''': '''encoder_layers''', } def __init__( self : Optional[int] , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : str = "student_t" , __UpperCAmelCase : str = "nll" , __UpperCAmelCase : int = 1 , __UpperCAmelCase : List[int] = [1, 2, 3, 4, 5, 6, 7] , __UpperCAmelCase : bool = True , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : int = 0 , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : Optional[List[int]] = None , __UpperCAmelCase : int = 64 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : str = "gelu" , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : float = 0.1 , __UpperCAmelCase : int = 100 , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : bool = True , __UpperCAmelCase : Dict=True , __UpperCAmelCase : int = 10 , __UpperCAmelCase : int = 25 , __UpperCAmelCase : int = 3 , **__UpperCAmelCase : int , ) ->str: """simple docstring""" a = prediction_length a = context_length if context_length is not None else prediction_length a = distribution_output a = loss a = input_size a = num_time_features a = lags_sequence a = scaling a = num_dynamic_real_features a = num_static_real_features a = num_static_categorical_features if cardinality is not None and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The cardinality should be a list of the same length as `num_static_categorical_features`''' ) a = cardinality else: a = [0] if embedding_dimension is not None and num_static_categorical_features > 0: if len(__UpperCAmelCase ) != num_static_categorical_features: raise ValueError( '''The embedding dimension should be a list of the same length as `num_static_categorical_features`''' ) a = embedding_dimension else: a = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] a = num_parallel_samples # Transformer architecture configuration a = input_size * len(self.lags_sequence ) + self._number_of_features a = d_model a = encoder_attention_heads a = decoder_attention_heads a = encoder_ffn_dim a = decoder_ffn_dim a = encoder_layers a = decoder_layers a = dropout a = attention_dropout a = activation_dropout a = encoder_layerdrop a = decoder_layerdrop a = activation_function a = init_std a = use_cache # Autoformer a = label_length a = moving_average a = autocorrelation_factor super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Union[str, 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 )
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaPriorPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt''', '''negative_prompt'''] __snake_case = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" return 100 @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 12, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a = PriorTransformer(**__UpperCAmelCase ) # 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 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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 , ) a = CLIPVisionModelWithProjection(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__UpperCAmelCase , clip_sample_range=10.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str=0 ) ->int: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) 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 __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = torch_device == '''cpu''' a = True a = False self._test_inference_batch_single_identical( test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , ) @skip_mps def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = torch_device == '''cpu''' a = False self._test_attention_slicing_forward_pass( test_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , )
0
1
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
1
def _a ( a :int ) -> bool: if not isinstance(a , a ): a = F"""Input value of [number={number}] must be an integer""" raise TypeError(a ) if number < 0: return False a = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore UpperCAmelCase__ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" UpperCAmelCase__ = [file for file in filepaths if file != file.lower()] if upper_files: print(f"""{len(upper_files)} files contain uppercase characters:""") print("\n".join(upper_files) + "\n") UpperCAmelCase__ = [file for file in filepaths if " " in file] if space_files: print(f"""{len(space_files)} files contain space characters:""") print("\n".join(space_files) + "\n") UpperCAmelCase__ = [file for file in filepaths if "-" in file] if hyphen_files: print(f"""{len(hyphen_files)} files contain hyphen characters:""") print("\n".join(hyphen_files) + "\n") UpperCAmelCase__ = [file for file in filepaths if os.sep not in file] if nodir_files: print(f"""{len(nodir_files)} files are not in a directory:""") print("\n".join(nodir_files) + "\n") UpperCAmelCase__ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
import contextlib import csv import json import os import sqlitea import tarfile import textwrap import zipfile import pyarrow as pa import pyarrow.parquet as pq import pytest import datasets import datasets.config @pytest.fixture(scope='''session''' ) def _a ( ) -> int: a = 10 a = datasets.Features( { '''tokens''': datasets.Sequence(datasets.Value('''string''' ) ), '''labels''': datasets.Sequence(datasets.ClassLabel(names=['''negative''', '''positive'''] ) ), '''answers''': datasets.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), '''id''': datasets.Value('''int64''' ), } ) a = datasets.Dataset.from_dict( { '''tokens''': [['''foo'''] * 5] * n, '''labels''': [[1] * 5] * n, '''answers''': [{'''answer_start''': [97], '''text''': ['''1976''']}] * 10, '''id''': list(range(a ) ), } , features=a , ) return dataset @pytest.fixture(scope='''session''' ) def _a ( a :Optional[Any] , a :Tuple ) -> str: a = str(tmp_path_factory.mktemp('''data''' ) / '''file.arrow''' ) dataset.map(cache_file_name=a ) return filename # FILE_CONTENT + files UpperCAmelCase__ = "\\n Text data.\n Second line of data." @pytest.fixture(scope='''session''' ) def _a ( a :int ) -> Tuple: a = tmp_path_factory.mktemp('''data''' ) / '''file.txt''' a = FILE_CONTENT with open(a , '''w''' ) as f: f.write(a ) return filename @pytest.fixture(scope='''session''' ) def _a ( a :Dict ) -> List[str]: import bza a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.bz2''' a = bytes(a , '''utf-8''' ) with bza.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Tuple ) -> str: import gzip a = str(tmp_path_factory.mktemp('''data''' ) / '''file.txt.gz''' ) a = bytes(a , '''utf-8''' ) with gzip.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :str ) -> Tuple: if datasets.config.LZ4_AVAILABLE: import lza.frame a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.lz4''' a = bytes(a , '''utf-8''' ) with lza.frame.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[str] , a :Any ) -> Dict: if datasets.config.PY7ZR_AVAILABLE: import pyazr a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.7z''' with pyazr.SevenZipFile(a , '''w''' ) as archive: archive.write(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] , a :Dict ) -> Tuple: import tarfile a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.tar''' with tarfile.TarFile(a , '''w''' ) as f: f.add(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> str: import lzma a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.xz''' a = bytes(a , '''utf-8''' ) with lzma.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] , a :Union[str, Any] ) -> Tuple: import zipfile a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] ) -> Any: if datasets.config.ZSTANDARD_AVAILABLE: import zstandard as zstd a = tmp_path_factory.mktemp('''data''' ) / '''file.txt.zst''' a = bytes(a , '''utf-8''' ) with zstd.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :str ) -> Union[str, Any]: a = tmp_path_factory.mktemp('''data''' ) / '''file.xml''' a = textwrap.dedent( '''\ <?xml version="1.0" encoding="UTF-8" ?> <tmx version="1.4"> <header segtype="sentence" srclang="ca" /> <body> <tu> <tuv xml:lang="ca"><seg>Contingut 1</seg></tuv> <tuv xml:lang="en"><seg>Content 1</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 2</seg></tuv> <tuv xml:lang="en"><seg>Content 2</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 3</seg></tuv> <tuv xml:lang="en"><seg>Content 3</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 4</seg></tuv> <tuv xml:lang="en"><seg>Content 4</seg></tuv> </tu> <tu> <tuv xml:lang="ca"><seg>Contingut 5</seg></tuv> <tuv xml:lang="en"><seg>Content 5</seg></tuv> </tu> </body> </tmx>''' ) with open(a , '''w''' ) as f: f.write(a ) return filename UpperCAmelCase__ = [ {"col_1": "0", "col_2": 0, "col_3": 0.0}, {"col_1": "1", "col_2": 1, "col_3": 1.0}, {"col_1": "2", "col_2": 2, "col_3": 2.0}, {"col_1": "3", "col_2": 3, "col_3": 3.0}, ] UpperCAmelCase__ = [ {"col_1": "4", "col_2": 4, "col_3": 4.0}, {"col_1": "5", "col_2": 5, "col_3": 5.0}, ] UpperCAmelCase__ = { "col_1": ["0", "1", "2", "3"], "col_2": [0, 1, 2, 3], "col_3": [0.0, 1.0, 2.0, 3.0], } UpperCAmelCase__ = [ {"col_3": 0.0, "col_1": "0", "col_2": 0}, {"col_3": 1.0, "col_1": "1", "col_2": 1}, ] UpperCAmelCase__ = [ {"col_1": "s0", "col_2": 0, "col_3": 0.0}, {"col_1": "s1", "col_2": 1, "col_3": 1.0}, {"col_1": "s2", "col_2": 2, "col_3": 2.0}, {"col_1": "s3", "col_2": 3, "col_3": 3.0}, ] @pytest.fixture(scope='''session''' ) def _a ( ) -> Tuple: return DATA_DICT_OF_LISTS @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> Optional[Any]: a = datasets.Dataset.from_dict(a ) a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.arrow''' ) dataset.map(cache_file_name=a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Tuple ) -> Optional[Any]: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.sqlite''' ) with contextlib.closing(sqlitea.connect(a ) ) as con: a = con.cursor() cur.execute('''CREATE TABLE dataset(col_1 text, col_2 int, col_3 real)''' ) for item in DATA: cur.execute('''INSERT INTO dataset(col_1, col_2, col_3) VALUES (?, ?, ?)''' , tuple(item.values() ) ) con.commit() return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> Union[str, Any]: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.csv''' ) with open(a , '''w''' , newline='''''' ) as f: a = csv.DictWriter(a , fieldnames=['''col_1''', '''col_2''', '''col_3'''] ) writer.writeheader() for item in DATA: writer.writerow(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> str: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.csv''' ) with open(a , '''w''' , newline='''''' ) as f: a = csv.DictWriter(a , fieldnames=['''col_1''', '''col_2''', '''col_3'''] ) writer.writeheader() for item in DATA: writer.writerow(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Optional[int] , a :Union[str, Any] ) -> List[Any]: import bza a = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.bz2''' with open(a , '''rb''' ) as f: a = f.read() # data = bytes(FILE_CONTENT, "utf-8") with bza.open(a , '''wb''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Dict , a :Optional[Any] , a :Optional[int] ) -> int: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(a ) ) f.write(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] , a :List[str] , a :List[str] ) -> Tuple: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.csv.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(csv_path.replace('''.csv''' , '''.CSV''' ) ) ) f.write(a , arcname=os.path.basename(csva_path.replace('''.csv''' , '''.CSV''' ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any , a :Union[str, Any] , a :str ) -> List[Any]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.csv.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any ) -> Any: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.parquet''' ) a = pa.schema( { '''col_1''': pa.string(), '''col_2''': pa.intaa(), '''col_3''': pa.floataa(), } ) with open(a , '''wb''' ) as f: a = pq.ParquetWriter(a , schema=a ) a = pa.Table.from_pydict({k: [DATA[i][k] for i in range(len(a ) )] for k in DATA[0]} , schema=a ) writer.write_table(a ) writer.close() return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] ) -> Any: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.json''' ) a = {'''data''': DATA} with open(a , '''w''' ) as f: json.dump(a , a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Optional[Any] ) -> List[Any]: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.json''' ) a = {'''data''': DATA_DICT_OF_LISTS} with open(a , '''w''' ) as f: json.dump(a , a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] ) -> int: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl''' ) with open(a , '''w''' ) as f: for item in DATA: f.write(json.dumps(a ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Optional[int] ) -> Optional[Any]: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.jsonl''' ) with open(a , '''w''' ) as f: for item in DATA: f.write(json.dumps(a ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any ) -> Dict: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset_312.jsonl''' ) with open(a , '''w''' ) as f: for item in DATA_312: f.write(json.dumps(a ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any ) -> List[str]: a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset-str.jsonl''' ) with open(a , '''w''' ) as f: for item in DATA_STR: f.write(json.dumps(a ) + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] , a :int ) -> str: import gzip a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.txt.gz''' ) with open(a , '''rb''' ) as orig_file: with gzip.open(a , '''wb''' ) as zipped_file: zipped_file.writelines(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any , a :Union[str, Any] ) -> List[Any]: import gzip a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.gz''' ) with open(a , '''rb''' ) as orig_file: with gzip.open(a , '''wb''' ) as zipped_file: zipped_file.writelines(a ) return path @pytest.fixture(scope='''session''' ) def _a ( a :int , a :Optional[Any] , a :List[Any] ) -> Union[str, Any]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(a ) ) f.write(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any , a :Dict , a :str , a :Optional[Any] ) -> str: a = tmp_path_factory.mktemp('''data''' ) / '''dataset_nested.jsonl.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.join('''nested''' , os.path.basename(a ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[str] , a :Optional[int] , a :Tuple ) -> int: a = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.jsonl.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Optional[int] , a :int , a :Optional[Any] ) -> int: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.jsonl.tar''' with tarfile.TarFile(a , '''w''' ) as f: f.add(a , arcname=os.path.basename(a ) ) f.add(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[str] , a :List[str] , a :str , a :Tuple ) -> Union[str, Any]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset_nested.jsonl.tar''' with tarfile.TarFile(a , '''w''' ) as f: f.add(a , arcname=os.path.join('''nested''' , os.path.basename(a ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[Any] ) -> Tuple: a = ['''0''', '''1''', '''2''', '''3'''] a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset.txt''' ) with open(a , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any ) -> List[Any]: a = ['''0''', '''1''', '''2''', '''3'''] a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset2.txt''' ) with open(a , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> List[str]: a = ['''0''', '''1''', '''2''', '''3'''] a = tmp_path_factory.mktemp('''data''' ) / '''dataset.abc''' with open(a , '''w''' ) as f: for item in data: f.write(item + '''\n''' ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Optional[Any] , a :List[str] , a :int ) -> List[Any]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.text.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(a ) ) f.write(a , arcname=os.path.basename(a ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :List[str] , a :int , a :Dict ) -> int: a = tmp_path_factory.mktemp('''data''' ) / '''dataset_with_dir.text.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) f.write(a , arcname=os.path.join('''main_dir''' , os.path.basename(a ) ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Any , a :Tuple , a :List[str] ) -> Optional[Any]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.ext.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename('''unsupported.ext''' ) ) f.write(a , arcname=os.path.basename('''unsupported_2.ext''' ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Union[str, Any] ) -> Dict: a = '''\n'''.join(['''First''', '''Second\u2029with Unicode new line''', '''Third'''] ) a = str(tmp_path_factory.mktemp('''data''' ) / '''dataset_with_unicode_new_lines.txt''' ) with open(a , '''w''' , encoding='''utf-8''' ) as f: f.write(a ) return path @pytest.fixture(scope='''session''' ) def _a ( ) -> str: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_image_rgb.jpg''' ) @pytest.fixture(scope='''session''' ) def _a ( ) -> Dict: return os.path.join('''tests''' , '''features''' , '''data''' , '''test_audio_44100.wav''' ) @pytest.fixture(scope='''session''' ) def _a ( a :int , a :int ) -> Optional[int]: a = tmp_path_factory.mktemp('''data''' ) / '''dataset.img.zip''' with zipfile.ZipFile(a , '''w''' ) as f: f.write(a , arcname=os.path.basename(a ) ) f.write(a , arcname=os.path.basename(a ).replace('''.jpg''' , '''2.jpg''' ) ) return path @pytest.fixture(scope='''session''' ) def _a ( a :Dict ) -> Dict: a = tmp_path_factory.mktemp('''data_dir''' ) (data_dir / "subdir").mkdir() with open(data_dir / '''subdir''' / '''train.txt''' , '''w''' ) as f: f.write('''foo\n''' * 10 ) with open(data_dir / '''subdir''' / '''test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) # hidden file with open(data_dir / '''subdir''' / '''.test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) # hidden directory (data_dir / ".subdir").mkdir() with open(data_dir / '''.subdir''' / '''train.txt''' , '''w''' ) as f: f.write('''foo\n''' * 10 ) with open(data_dir / '''.subdir''' / '''test.txt''' , '''w''' ) as f: f.write('''bar\n''' * 10 ) return data_dir
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
def _a ( a :str ) -> str: return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
from math import sqrt def _a ( a :int ) -> bool: assert isinstance(a , a ) and ( number >= 0 ), "'number' must been an int and positive" a = True # 0 and 1 are none primes. if number <= 1: a = False for divisor in range(2 , int(round(sqrt(a ) ) ) + 1 ): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: a = False break # precondition assert isinstance(a , a ), "'status' must been from type bool" return status def _a ( a :Tuple ) -> str: assert isinstance(a , a ) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N a = list(range(2 , n + 1 ) ) a = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(a ) ): for j in range(i + 1 , len(a ) ): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): a = 0 # filters actual prime numbers. a = [x for x in begin_list if x != 0] # precondition assert isinstance(a , a ), "'ans' must been from type list" return ans def _a ( a :Optional[Any] ) -> Optional[Any]: assert isinstance(a , a ) and (n > 2), "'N' must been an int and > 2" a = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2 , n + 1 ): if is_prime(a ): ans.append(a ) # precondition assert isinstance(a , a ), "'ans' must been from type list" return ans def _a ( a :Dict ) -> str: assert isinstance(a , a ) and number >= 0, "'number' must been an int and >= 0" a = [] # this list will be returns of the function. # potential prime number factors. a = 2 a = number if number == 0 or number == 1: ans.append(a ) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(a ): while quotient != 1: if is_prime(a ) and (quotient % factor == 0): ans.append(a ) quotient /= factor else: factor += 1 else: ans.append(a ) # precondition assert isinstance(a , a ), "'ans' must been from type list" return ans def _a ( a :List[str] ) -> Union[str, Any]: assert isinstance(a , a ) and ( number >= 0 ), "'number' bust been an int and >= 0" a = 0 # prime factorization of 'number' a = prime_factorization(a ) a = max(a ) # precondition assert isinstance(a , a ), "'ans' must been from type int" return ans def _a ( a :Optional[int] ) -> List[str]: assert isinstance(a , a ) and ( number >= 0 ), "'number' bust been an int and >= 0" a = 0 # prime factorization of 'number' a = prime_factorization(a ) a = min(a ) # precondition assert isinstance(a , a ), "'ans' must been from type int" return ans def _a ( a :Any ) -> Any: assert isinstance(a , a ), "'number' must been an int" assert isinstance(number % 2 == 0 , a ), "compare bust been from type bool" return number % 2 == 0 def _a ( a :Any ) -> int: assert isinstance(a , a ), "'number' must been an int" assert isinstance(number % 2 != 0 , a ), "compare bust been from type bool" return number % 2 != 0 def _a ( a :Union[str, Any] ) -> Tuple: assert ( isinstance(a , a ) and (number > 2) and is_even(a ) ), "'number' must been an int, even and > 2" a = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' a = get_prime_numbers(a ) a = len(a ) # run variable for while-loops. a = 0 a = None # exit variable. for break up the loops a = True while i < len_pn and loop: a = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: a = False ans.append(prime_numbers[i] ) ans.append(prime_numbers[j] ) j += 1 i += 1 # precondition assert ( isinstance(a , a ) and (len(a ) == 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 ( a :Dict , a :int ) -> Dict: assert ( isinstance(a , a ) and isinstance(a , a ) and (numbera >= 0) and (numbera >= 0) ), "'number1' and 'number2' must been positive integer." a = 0 while numbera != 0: a = numbera % numbera a = numbera a = rest # precondition assert isinstance(a , a ) and ( numbera >= 0 ), "'number' must been from type int and positive" return numbera def _a ( a :str , a :str ) -> str: assert ( isinstance(a , a ) and isinstance(a , a ) and (numbera >= 1) and (numbera >= 1) ), "'number1' and 'number2' must been positive integer." a = 1 # actual answer that will be return. # for kgV (x,1) if numbera > 1 and numbera > 1: # builds the prime factorization of 'number1' and 'number2' a = prime_factorization(a ) a = prime_factorization(a ) elif numbera == 1 or numbera == 1: a = [] a = [] a = max(a , a ) a = 0 a = 0 a = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_a: if n not in done: if n in prime_fac_a: a = prime_fac_a.count(a ) a = prime_fac_a.count(a ) for _ in range(max(a , a ) ): ans *= n else: a = prime_fac_a.count(a ) for _ in range(a ): ans *= n done.append(a ) # iterates through primeFac2 for n in prime_fac_a: if n not in done: a = prime_fac_a.count(a ) for _ in range(a ): ans *= n done.append(a ) # precondition assert isinstance(a , a ) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans def _a ( a :int ) -> Any: assert isinstance(a , a ) and (n >= 0), "'number' must been a positive int" a = 0 a = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(a ): ans += 1 # precondition assert isinstance(a , a ) and is_prime( a ), "'ans' must been a prime number and from type int" return ans def _a ( a :Optional[Any] , a :Optional[int] ) -> List[Any]: assert ( is_prime(a ) and is_prime(a ) and (p_number_a < p_number_a) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" a = p_number_a + 1 # jump to the next number a = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(a ): number += 1 while number < p_number_a: ans.append(a ) number += 1 # fetch the next prime number. while not is_prime(a ): number += 1 # precondition assert ( isinstance(a , a ) and ans[0] != p_number_a and ans[len(a ) - 1] != p_number_a ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans def _a ( a :Optional[Any] ) -> Optional[Any]: assert isinstance(a , a ) and (n >= 1), "'n' must been int and >= 1" a = [] # will be returned. for divisor in range(1 , n + 1 ): if n % divisor == 0: ans.append(a ) # precondition assert ans[0] == 1 and ans[len(a ) - 1] == n, "Error in function getDivisiors(...)" return ans def _a ( a :List[Any] ) -> Optional[Any]: assert isinstance(a , a ) and ( number > 1 ), "'number' must been an int and >= 1" a = get_divisors(a ) # precondition assert ( isinstance(a , a ) and (divisors[0] == 1) and (divisors[len(a ) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1] ) == number def _a ( a :Optional[int] , a :Optional[int] ) -> Dict: assert ( isinstance(a , a ) and isinstance(a , a ) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. a = gcd(abs(a ) , abs(a ) ) # precondition assert ( isinstance(a , a ) 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 ( a :str ) -> str: assert isinstance(a , a ) and (n >= 0), "'n' must been a int and >= 0" a = 1 # this will be return. for factor in range(1 , n + 1 ): ans *= factor return ans def _a ( a :List[str] ) -> Optional[Any]: assert isinstance(a , a ) and (n >= 0), "'n' must been an int and >= 0" a = 0 a = 1 a = 1 # this will be return for _ in range(n - 1 ): a = ans ans += fiba a = tmp return ans
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "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" ), }, } UpperCAmelCase__ = { "google/electra-small-generator": 512, "google/electra-base-generator": 512, "google/electra-large-generator": 512, "google/electra-small-discriminator": 512, "google/electra-base-discriminator": 512, "google/electra-large-discriminator": 512, } UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ElectraTokenizer def __init__( self : Dict , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Any="[SEP]" , __UpperCAmelCase : str="[PAD]" , __UpperCAmelCase : Optional[Any]="[CLS]" , __UpperCAmelCase : Union[str, Any]="[MASK]" , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] , ) ->str: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple=None ) ->str: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
0
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
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
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
1
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
1
from __future__ import annotations def _a ( a :list , a :int | None = None , a :int | None = None ) -> None: if start is None: a = 0 if end is None: a = len(a ) - 1 if start >= end: return a = (start + end) // 2 slowsort(a , a , a ) slowsort(a , mid + 1 , a ) if sequence[end] < sequence[mid]: a , a = sequence[mid], sequence[end] slowsort(a , a , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {} class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''llama''' __snake_case = ['''past_key_values'''] def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]=32_000 , __UpperCAmelCase : str=4_096 , __UpperCAmelCase : int=11_008 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]="silu" , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Any=1e-6 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Tuple , ) ->str: """simple docstring""" a = vocab_size a = max_position_embeddings a = hidden_size a = intermediate_size a = num_hidden_layers a = num_attention_heads # for backward compatibility if num_key_value_heads is None: a = num_attention_heads a = num_key_value_heads a = hidden_act a = initializer_range a = rms_norm_eps a = pretraining_tp a = use_cache a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) 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}""" ) a = self.rope_scaling.get('''type''' , __UpperCAmelCase ) a = self.rope_scaling.get('''factor''' , __UpperCAmelCase ) 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(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
0
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "openai/whisper-base": "https://huggingface.co/openai/whisper-base/resolve/main/config.json", } # fmt: off UpperCAmelCase__ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] UpperCAmelCase__ = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''whisper''' __snake_case = ['''past_key_values'''] __snake_case = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self : Any , __UpperCAmelCase : Union[str, Any]=51_865 , __UpperCAmelCase : str=80 , __UpperCAmelCase : Any=6 , __UpperCAmelCase : Optional[Any]=4 , __UpperCAmelCase : Any=6 , __UpperCAmelCase : Any=4 , __UpperCAmelCase : Any=1_536 , __UpperCAmelCase : Any=1_536 , __UpperCAmelCase : str=0.0 , __UpperCAmelCase : Union[str, Any]=0.0 , __UpperCAmelCase : Optional[int]=50_257 , __UpperCAmelCase : Any=True , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : List[Any]=256 , __UpperCAmelCase : Tuple=0.0 , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : List[Any]=0.0 , __UpperCAmelCase : str=0.02 , __UpperCAmelCase : List[Any]=False , __UpperCAmelCase : str=1_500 , __UpperCAmelCase : str=448 , __UpperCAmelCase : Tuple=50_256 , __UpperCAmelCase : Dict=50_256 , __UpperCAmelCase : Tuple=50_256 , __UpperCAmelCase : int=None , __UpperCAmelCase : int=[220, 50_256] , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : Tuple=256 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Union[str, Any]=0.05 , __UpperCAmelCase : Dict=10 , __UpperCAmelCase : List[Any]=2 , __UpperCAmelCase : Union[str, Any]=0.0 , __UpperCAmelCase : List[Any]=10 , __UpperCAmelCase : Optional[Any]=0 , __UpperCAmelCase : Union[str, Any]=7 , **__UpperCAmelCase : Optional[Any] , ) ->Optional[int]: """simple docstring""" a = vocab_size a = num_mel_bins a = d_model a = encoder_layers a = encoder_attention_heads a = decoder_layers a = decoder_attention_heads a = decoder_ffn_dim a = encoder_ffn_dim a = dropout a = attention_dropout a = activation_dropout a = activation_function a = init_std a = encoder_layerdrop a = decoder_layerdrop a = use_cache a = encoder_layers a = scale_embedding # scale factor will be sqrt(d_model) if True a = max_source_positions a = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. a = classifier_proj_size a = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a = apply_spec_augment a = mask_time_prob a = mask_time_length a = mask_time_min_masks a = mask_feature_prob a = mask_feature_length a = mask_feature_min_masks a = median_filter_width super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , decoder_start_token_id=__UpperCAmelCase , suppress_tokens=__UpperCAmelCase , begin_suppress_tokens=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[int] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = OrderedDict( [ ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}), ] ) if self.use_past: a = {0: '''batch'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __UpperCAmelCase : int = -1 , __UpperCAmelCase : int = -1 , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional["TensorType"] = None , __UpperCAmelCase : int = 22_050 , __UpperCAmelCase : float = 5.0 , __UpperCAmelCase : int = 220 , ) ->Mapping[str, Any]: """simple docstring""" a = OrderedDict() a = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=__UpperCAmelCase , framework=__UpperCAmelCase , sampling_rate=__UpperCAmelCase , time_duration=__UpperCAmelCase , frequency=__UpperCAmelCase , ) a = encoder_inputs['''input_features'''].shape[2] a = encoder_sequence_length // 2 if self.use_past else seq_length a = super().generate_dummy_inputs( preprocessor.tokenizer , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = encoder_inputs.pop('''input_features''' ) a = decoder_inputs.pop('''decoder_input_ids''' ) if "past_key_values" in decoder_inputs: a = decoder_inputs.pop('''past_key_values''' ) return dummy_inputs @property def __lowerCAmelCase ( self : Optional[int] ) ->float: """simple docstring""" return 1e-3
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset UpperCAmelCase__ = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) UpperCAmelCase__ = dataset.iloc[:, 1:2].values UpperCAmelCase__ = dataset.iloc[:, 2].values UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = train_test_split(X, y, test_size=0.2, random_state=0) UpperCAmelCase__ = PolynomialFeatures(degree=4) UpperCAmelCase__ = poly_reg.fit_transform(X) UpperCAmelCase__ = LinearRegression() pol_reg.fit(X_poly, y) def _a ( ) -> Optional[Any]: plt.scatter(a , a , color='''red''' ) plt.plot(a , pol_reg.predict(poly_reg.fit_transform(a ) ) , color='''blue''' ) plt.title('''Truth or Bluff (Linear Regression)''' ) plt.xlabel('''Position level''' ) plt.ylabel('''Salary''' ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1
from ..utils import DummyObject, requires_backends class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Dict , *__UpperCAmelCase : Optional[int] , **__UpperCAmelCase : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *__UpperCAmelCase : Tuple , **__UpperCAmelCase : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *__UpperCAmelCase : Any , **__UpperCAmelCase : int ) ->Tuple: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[str] , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : List[Any] ) ->Optional[int]: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : List[Any] , *__UpperCAmelCase : Tuple , **__UpperCAmelCase : Optional[int] ) ->Any: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *__UpperCAmelCase : List[Any] , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : str , *__UpperCAmelCase : str , **__UpperCAmelCase : Any ) ->Optional[Any]: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , *__UpperCAmelCase : Optional[int] , **__UpperCAmelCase : int ) ->Tuple: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : List[str] , *__UpperCAmelCase : List[Any] , **__UpperCAmelCase : List[str] ) ->List[str]: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : List[Any] , *__UpperCAmelCase : Optional[int] , **__UpperCAmelCase : Dict ) ->Tuple: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : int , *__UpperCAmelCase : List[Any] , **__UpperCAmelCase : int ) ->Dict: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Optional[int] , *__UpperCAmelCase : Any , **__UpperCAmelCase : List[Any] ) ->Union[str, Any]: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : Union[str, Any] , *__UpperCAmelCase : Any , **__UpperCAmelCase : Tuple ) ->Dict: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , *__UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Any ) ->str: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : str , *__UpperCAmelCase : Tuple , **__UpperCAmelCase : Dict ) ->Union[str, Any]: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) class lowercase_ ( metaclass=lowercase ): '''simple docstring''' __snake_case = ['''torch''', '''transformers''', '''onnx'''] def __init__( self : int , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->Any: """simple docstring""" requires_backends(self , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Optional[Any] , *__UpperCAmelCase : Tuple , **__UpperCAmelCase : Dict ) ->Any: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] ) @classmethod def __lowerCAmelCase ( cls : Tuple , *__UpperCAmelCase : str , **__UpperCAmelCase : Union[str, Any] ) ->Optional[Any]: """simple docstring""" requires_backends(cls , ['''torch''', '''transformers''', '''onnx'''] )
0
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import BaseOutput, is_torch_available, is_transformers_available @dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 if is_transformers_available() and is_torch_available(): from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline
0
def _a ( a :float , a :float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
0
1
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :Union[tf.Tensor, np.ndarray] ) -> List[int]: if isinstance(a , np.ndarray ): return list(tensor.shape ) a = tf.shape(a ) if tensor.shape == tf.TensorShape(a ): return dynamic a = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(a )] def _a ( a :tf.Tensor , a :Optional[int] = None , a :Optional[str] = None ) -> tf.Tensor: return tf.nn.softmax(logits=logits + 1e-9 , axis=a , name=a ) def _a ( a :Tuple , a :str , a :List[str] , a :str=1e-5 , a :List[str]=-1 ) -> Any: # This is a very simplified functional layernorm, designed to duplicate # the functionality of PyTorch nn.functional.layer_norm when this is needed to port # models in Transformers. if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(a , a ): raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.''' ) # Get mean and variance on the axis to be normalized a , a = tf.nn.moments(a , axes=[axis] , keepdims=a ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis a = [1] * inputs.shape.rank a = shape_list(a )[axis] a = tf.reshape(a , a ) a = tf.reshape(a , a ) # Compute layer normalization using the batch_normalization # function. a = tf.nn.batch_normalization( a , a , a , offset=a , scale=a , variance_epsilon=a , ) return outputs def _a ( a :Optional[Any] , a :Dict=0 , a :Any=-1 ) -> List[Any]: # Replicates the behavior of torch.flatten in TF # If end_dim or start_dim is negative, count them from the end if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input a = tf.shape(a ) a = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) a = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(a , a ) def _a ( a :tf.Tensor ) -> tf.Tensor: if not isinstance(a , tf.Tensor ): a = tf.convert_to_tensor(a ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: a = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: a = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) a = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _a ( a :tf.Tensor , a :int , a :str = "input_ids" ) -> None: tf.debugging.assert_less( a , tf.cast(a , dtype=tensor.dtype ) , message=( F"""The maximum value of {tensor_name} ({tf.math.reduce_max(a )}) must be smaller than the embedding """ F"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time.""" ) , ) def _a ( a :Any , a :Optional[Any] , a :List[str] ) -> str: a = 64_512 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. a = [x for x in data if len(a ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( '''The following attributes cannot be saved to HDF5 file because ''' F"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """ F"""bytes: {bad_attributes}""" ) a = np.asarray(a ) a = 1 a = np.array_split(a , a ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 a = np.array_split(a , a ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(a ): a = chunk_data else: a = data def _a ( a :Optional[Any] , a :Dict ) -> Optional[int]: if name in group.attrs: a = [n.decode('''utf8''' ) if hasattr(a , '''decode''' ) else n for n in group.attrs[name]] else: a = [] a = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('''utf8''' ) if hasattr(a , '''decode''' ) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]] ) chunk_id += 1 return data def _a ( a :Any ) -> str: def _expand_single_ad_tensor(a :Optional[int] ): if isinstance(a , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(a , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , a )
0
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
1
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ProphetNetTokenizer __snake_case = False def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = '''UNwant\u00E9d,running''' a = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__UpperCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , 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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] a = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : Any ) ->List[str]: """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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "tokenizer_file": { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json", }, } UpperCAmelCase__ = { "gpt-neox-20b": 2048, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''attention_mask'''] def __init__( self : Optional[int] , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Dict="<|endoftext|>" , __UpperCAmelCase : Optional[int]="<|endoftext|>" , __UpperCAmelCase : Optional[Any]="<|endoftext|>" , __UpperCAmelCase : Union[str, Any]=False , **__UpperCAmelCase : Dict , ) ->Any: """simple docstring""" super().__init__( __UpperCAmelCase , __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , unk_token=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __UpperCAmelCase ) != add_prefix_space: a = getattr(__UpperCAmelCase , pre_tok_state.pop('''type''' ) ) a = add_prefix_space a = pre_tok_class(**__UpperCAmelCase ) a = add_prefix_space def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : "Conversation" ) ->List[int]: """simple docstring""" a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) + [self.eos_token_id] ) if len(__UpperCAmelCase ) > self.model_max_length: a = input_ids[-self.model_max_length :] return input_ids
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = mock.Mock() a = 500 a = {} a = HTTPError a = {} # Download this model to make sure it's in the cache. a = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__UpperCAmelCase ) as mock_head: a = BertTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" a = mock.Mock() a = 500 a = {} a = HTTPError a = {} # Download this model to make sure it's in the cache. a = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__UpperCAmelCase ) as mock_head: a = GPTaTokenizerFast.from_pretrained('''gpt2''' ) # This check we did call the fake head request mock_head.assert_called() def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" try: a = tempfile.mktemp() with open(__UpperCAmelCase , '''wb''' ) as f: http_get('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' , __UpperCAmelCase ) a = AlbertTokenizer.from_pretrained(__UpperCAmelCase ) finally: os.remove(__UpperCAmelCase ) # 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''' , __UpperCAmelCase ) a = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-gpt2''' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size , 1_000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('''tokenizer.json''' ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = AlbertTokenizer.from_pretrained('''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''' ) @is_staging_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' __snake_case = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou'''] @classmethod def __lowerCAmelCase ( cls : Optional[Any] ) ->Dict: """simple docstring""" a = TOKEN HfFolder.save_token(__UpperCAmelCase ) @classmethod def __lowerCAmelCase ( cls : str ) ->Optional[Any]: """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 __lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__UpperCAmelCase , '''vocab.txt''' ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) a = BertTokenizer(__UpperCAmelCase ) tokenizer.push_to_hub('''test-tokenizer''' , use_auth_token=self._token ) a = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''test-tokenizer''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(__UpperCAmelCase , repo_id='''test-tokenizer''' , push_to_hub=__UpperCAmelCase , use_auth_token=self._token ) a = BertTokenizer.from_pretrained(F"""{USER}/test-tokenizer""" ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) def __lowerCAmelCase ( self : Optional[int] ) ->Tuple: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__UpperCAmelCase , '''vocab.txt''' ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) a = BertTokenizer(__UpperCAmelCase ) tokenizer.push_to_hub('''valid_org/test-tokenizer-org''' , use_auth_token=self._token ) a = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-tokenizer-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( __UpperCAmelCase , repo_id='''valid_org/test-tokenizer-org''' , push_to_hub=__UpperCAmelCase , use_auth_token=self._token ) a = BertTokenizer.from_pretrained('''valid_org/test-tokenizer-org''' ) self.assertDictEqual(new_tokenizer.vocab , tokenizer.vocab ) @require_tokenizers def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__UpperCAmelCase , '''vocab.txt''' ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) a = CustomTokenizer(__UpperCAmelCase ) # No fast custom tokenizer tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) a = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=__UpperCAmelCase ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizer''' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__UpperCAmelCase , '''vocab.txt''' ) with open(__UpperCAmelCase , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens] ) ) a = BertTokenizerFast.from_pretrained(__UpperCAmelCase ) bert_tokenizer.save_pretrained(__UpperCAmelCase ) a = CustomTokenizerFast.from_pretrained(__UpperCAmelCase ) tokenizer.push_to_hub('''test-dynamic-tokenizer''' , use_auth_token=self._token ) a = AutoTokenizer.from_pretrained(F"""{USER}/test-dynamic-tokenizer""" , trust_remote_code=__UpperCAmelCase ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ , '''CustomTokenizerFast''' ) a = AutoTokenizer.from_pretrained( F"""{USER}/test-dynamic-tokenizer""" , use_fast=__UpperCAmelCase , trust_remote_code=__UpperCAmelCase ) # 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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = Trie() trie.add('''Hello 友達''' ) self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) trie.add('''Hello''' ) trie.data self.assertEqual(trie.data , {'''H''': {'''e''': {'''l''': {'''l''': {'''o''': {'''''': 1, ''' ''': {'''友''': {'''達''': {'''''': 1}}}}}}}}} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Optional[int]: """simple docstring""" a = Trie() self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS] This is a extra_id_100'''] ) trie.add('''[CLS]''' ) trie.add('''extra_id_1''' ) trie.add('''extra_id_100''' ) self.assertEqual(trie.split('''[CLS] This is a extra_id_100''' ) , ['''[CLS]''', ''' This is a ''', '''extra_id_100'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = Trie() trie.add('''A''' ) self.assertEqual(trie.split('''ABC''' ) , ['''A''', '''BC'''] ) self.assertEqual(trie.split('''BCA''' ) , ['''BC''', '''A'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" a = Trie() trie.add('''TOKEN]''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = Trie() trie.add('''A''' ) trie.add('''P''' ) trie.add('''[SPECIAL_TOKEN]''' ) self.assertEqual(trie.split('''This is something [SPECIAL_TOKEN]''' ) , ['''This is something ''', '''[SPECIAL_TOKEN]'''] ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = Trie() trie.add('''AB''' ) trie.add('''B''' ) trie.add('''C''' ) self.assertEqual(trie.split('''ABC''' ) , ['''AB''', '''C'''] ) def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" a = Trie() trie.add('''ABC''' ) trie.add('''B''' ) trie.add('''CD''' ) self.assertEqual(trie.split('''ABCD''' ) , ['''ABC''', '''D'''] ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = Trie() a = trie.cut_text('''ABC''' , [0, 0, 2, 1, 2, 3] ) self.assertEqual(__UpperCAmelCase , ['''AB''', '''C'''] )
0
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from 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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''Salesforce/blip-image-captioning-base''' __snake_case = ( '''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.''' ) __snake_case = '''image_captioner''' __snake_case = AutoModelForVisionaSeq __snake_case = ['''image'''] __snake_case = ['''text'''] def __init__( self : Optional[int] , *__UpperCAmelCase : List[Any] , **__UpperCAmelCase : List[str] ) ->Optional[Any]: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : "Image" ) ->Union[str, Any]: """simple docstring""" return self.pre_processor(images=__UpperCAmelCase , return_tensors='''pt''' ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : str ) ->List[str]: """simple docstring""" return self.model.generate(**__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return self.pre_processor.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase )[0].strip()
0
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _a ( a :int ) -> List[str]: if "cls_token" in name: a = name.replace('''cls_token''' , '''vit.embeddings.cls_token''' ) if "mask_token" in name: a = name.replace('''mask_token''' , '''decoder.mask_token''' ) if "decoder_pos_embed" in name: a = name.replace('''decoder_pos_embed''' , '''decoder.decoder_pos_embed''' ) if "pos_embed" in name and "decoder" not in name: a = name.replace('''pos_embed''' , '''vit.embeddings.position_embeddings''' ) if "patch_embed.proj" in name: a = name.replace('''patch_embed.proj''' , '''vit.embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a = name.replace('''patch_embed.norm''' , '''vit.embeddings.norm''' ) if "decoder_blocks" in name: a = name.replace('''decoder_blocks''' , '''decoder.decoder_layers''' ) if "blocks" in name: a = name.replace('''blocks''' , '''vit.encoder.layer''' ) if "attn.proj" in name: a = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a = name.replace('''mlp.fc2''' , '''output.dense''' ) if "decoder_embed" in name: a = name.replace('''decoder_embed''' , '''decoder.decoder_embed''' ) if "decoder_norm" in name: a = name.replace('''decoder_norm''' , '''decoder.decoder_norm''' ) if "decoder_pred" in name: a = name.replace('''decoder_pred''' , '''decoder.decoder_pred''' ) if "norm.weight" in name and "decoder" not in name: a = name.replace('''norm.weight''' , '''vit.layernorm.weight''' ) if "norm.bias" in name and "decoder" not in name: a = name.replace('''norm.bias''' , '''vit.layernorm.bias''' ) return name def _a ( a :Union[str, Any] , a :Dict ) -> str: for key in orig_state_dict.copy().keys(): a = orig_state_dict.pop(a ) if "qkv" in key: a = key.split('''.''' ) a = int(key_split[1] ) if "decoder_blocks" in key: a = config.decoder_hidden_size a = '''decoder.decoder_layers.''' if "weight" in key: a = val[:dim, :] a = val[dim : dim * 2, :] a = val[-dim:, :] elif "bias" in key: a = val[:dim] a = val[dim : dim * 2] a = val[-dim:] else: a = config.hidden_size a = '''vit.encoder.layer.''' if "weight" in key: a = val[:dim, :] a = val[dim : dim * 2, :] a = val[-dim:, :] elif "bias" in key: a = val[:dim] a = val[dim : dim * 2] a = val[-dim:] else: a = val return orig_state_dict def _a ( a :Any , a :int ) -> List[str]: a = ViTMAEConfig() if "large" in checkpoint_url: a = 1_024 a = 4_096 a = 24 a = 16 elif "huge" in checkpoint_url: a = 14 a = 1_280 a = 5_120 a = 32 a = 16 a = ViTMAEForPreTraining(a ) a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' )['''model'''] a = ViTMAEImageProcessor(size=config.image_size ) a = convert_state_dict(a , a ) model.load_state_dict(a ) model.eval() a = '''https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) a = ViTMAEImageProcessor(size=config.image_size ) a = image_processor(images=a , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) a = model(**a ) a = outputs.logits if "large" in checkpoint_url: a = torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: a = torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: a = torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , a , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
0
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
from math import ceil, sqrt def _a ( a :int = 1_000_000 ) -> int: a = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: a = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: a = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"""{solution() = }""")
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
1
def _a ( a :int = 1_000 ) -> int: a , a = 1, 1 a = [] for i in range(1 , n + 1 ): a = prev_numerator + 2 * prev_denominator a = prev_numerator + prev_denominator if len(str(a ) ) > len(str(a ) ): result.append(a ) a = numerator a = denominator return len(a ) if __name__ == "__main__": print(f"""{solution() = }""")
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaPriorPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt''', '''negative_prompt'''] __snake_case = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" return 100 @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 12, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a = PriorTransformer(**__UpperCAmelCase ) # 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 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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 , ) a = CLIPVisionModelWithProjection(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__UpperCAmelCase , clip_sample_range=10.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str=0 ) ->int: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) 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 __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = torch_device == '''cpu''' a = True a = False self._test_inference_batch_single_identical( test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , ) @skip_mps def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = torch_device == '''cpu''' a = False self._test_attention_slicing_forward_pass( test_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , )
0
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) UpperCAmelCase__ = { "configuration_mobilevit": ["MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileViTConfig", "MobileViTOnnxConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["MobileViTFeatureExtractor"] UpperCAmelCase__ = ["MobileViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileViTForImageClassification", "MobileViTForSemanticSegmentation", "MobileViTModel", "MobileViTPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
1
import unittest from transformers import PegasusConfig, PegasusTokenizer, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html UpperCAmelCase__ = "platform" import jax import jax.numpy as jnp import numpy as np from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel @require_flax class lowercase_ : '''simple docstring''' __snake_case = PegasusConfig __snake_case = {} __snake_case = '''gelu''' def __init__( self : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict=13 , __UpperCAmelCase : Any=7 , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Optional[int]=99 , __UpperCAmelCase : str=32 , __UpperCAmelCase : str=5 , __UpperCAmelCase : List[str]=4 , __UpperCAmelCase : List[Any]=37 , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Tuple=0.1 , __UpperCAmelCase : str=20 , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : List[Any]=1 , __UpperCAmelCase : List[Any]=0 , ) ->Union[str, Any]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = eos_token_id a = pad_token_id a = bos_token_id def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ).clip(3 , self.vocab_size ) a = np.expand_dims(np.array([self.eos_token_id] * self.batch_size ) , 1 ) a = np.concatenate([input_ids, eos_tensor] , axis=1 ) a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) a = prepare_pegasus_inputs_dict(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return config, inputs_dict def __lowerCAmelCase ( self : Any , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) ->List[Any]: """simple docstring""" a = 20 a = model_class_name(__UpperCAmelCase ) a = model.encode(inputs_dict['''input_ids'''] ) a , a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) a = model.init_cache(decoder_input_ids.shape[0] , __UpperCAmelCase , __UpperCAmelCase ) a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) a = model.decode( decoder_input_ids[:, :-1] , __UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , decoder_position_ids=__UpperCAmelCase , ) a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) a = model.decode( decoder_input_ids[:, -1:] , __UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__UpperCAmelCase , ) a = model.decode(__UpperCAmelCase , __UpperCAmelCase ) a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple ) ->str: """simple docstring""" a = 20 a = model_class_name(__UpperCAmelCase ) a = model.encode(inputs_dict['''input_ids'''] ) a , a = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) a = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) a = model.init_cache(decoder_input_ids.shape[0] , __UpperCAmelCase , __UpperCAmelCase ) a = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) a = model.decode( decoder_input_ids[:, :-1] , __UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase , past_key_values=__UpperCAmelCase , decoder_position_ids=__UpperCAmelCase , ) a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) a = model.decode( decoder_input_ids[:, -1:] , __UpperCAmelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__UpperCAmelCase , decoder_position_ids=__UpperCAmelCase , ) a = model.decode(__UpperCAmelCase , __UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase ) a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def _a ( a :List[Any] , a :Optional[int] , a :int , a :str=None , a :int=None , ) -> int: if attention_mask is None: a = np.not_equal(a , config.pad_token_id ).astype(np.inta ) if decoder_attention_mask is None: a = np.concatenate( [ np.ones(decoder_input_ids[:, :1].shape , dtype=np.inta ), np.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ).astype(np.inta ), ] , axis=-1 , ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, } @require_flax class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( FlaxPegasusForConditionalGeneration, FlaxPegasusModel, ) if is_flax_available() else () ) __snake_case = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else () __snake_case = True __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : str ) ->List[Any]: """simple docstring""" a = FlaxPegasusModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) a = model_class(__UpperCAmelCase ) @jax.jit def encode_jitted(__UpperCAmelCase : List[str] , __UpperCAmelCase : str=None , **__UpperCAmelCase : List[Any] ): return model.encode(input_ids=__UpperCAmelCase , attention_mask=__UpperCAmelCase ) with self.subTest('''JIT Enabled''' ): a = encode_jitted(**__UpperCAmelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): a = encode_jitted(**__UpperCAmelCase ).to_tuple() self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) ) for jitted_output, output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = model_class(__UpperCAmelCase ) a = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) a = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(__UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple ): return model.decode( decoder_input_ids=__UpperCAmelCase , decoder_attention_mask=__UpperCAmelCase , encoder_outputs=__UpperCAmelCase , ) with self.subTest('''JIT Enabled''' ): a = decode_jitted(**__UpperCAmelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): a = decode_jitted(**__UpperCAmelCase ).to_tuple() self.assertEqual(len(__UpperCAmelCase ) , len(__UpperCAmelCase ) ) for jitted_output, output in zip(__UpperCAmelCase , __UpperCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def __lowerCAmelCase ( self : str ) ->List[str]: """simple docstring""" for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained('''google/pegasus-large''' , from_pt=__UpperCAmelCase ) a = np.ones((1, 1) ) a = model(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : str ) ->Optional[Any]: """simple docstring""" a = FlaxPegasusForConditionalGeneration.from_pretrained('''google/pegasus-xsum''' ) a = PegasusTokenizer.from_pretrained('''google/pegasus-xsum''' ) 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 turned off power to hundreds of thousands of customers.''', '''Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.''', ] a = tokenizer(__UpperCAmelCase , return_tensors='''np''' , truncation=__UpperCAmelCase , max_length=512 , padding=__UpperCAmelCase ) a = model.generate(**__UpperCAmelCase , num_beams=2 ).sequences a = tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) assert tgt_text == decoded
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
from __future__ import annotations from scipy.special import comb # type: ignore class lowercase_ : '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : list[tuple[float, float]] ) ->Optional[Any]: """simple docstring""" a = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. a = len(__UpperCAmelCase ) - 1 def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : float ) ->list[float]: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." a = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , __UpperCAmelCase ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(__UpperCAmelCase ) , 5 ) == 1 return output_values def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : float ) ->tuple[float, float]: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." a = self.basis_function(__UpperCAmelCase ) a = 0.0 a = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def __lowerCAmelCase ( self : int , __UpperCAmelCase : float = 0.01 ) ->Optional[int]: """simple docstring""" from matplotlib import pyplot as plt # type: ignore a = [] # x coordinates of points to plot a = [] # y coordinates of points to plot a = 0.0 while t <= 1: a = self.bezier_curve_function(__UpperCAmelCase ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size a = [i[0] for i in self.list_of_points] a = [i[1] for i in self.list_of_points] plt.plot( __UpperCAmelCase , __UpperCAmelCase , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(__UpperCAmelCase , __UpperCAmelCase , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''glpn''' def __init__( self : List[str] , __UpperCAmelCase : str=3 , __UpperCAmelCase : str=4 , __UpperCAmelCase : Dict=[2, 2, 2, 2] , __UpperCAmelCase : Optional[Any]=[8, 4, 2, 1] , __UpperCAmelCase : Dict=[32, 64, 160, 256] , __UpperCAmelCase : Any=[7, 3, 3, 3] , __UpperCAmelCase : Union[str, Any]=[4, 2, 2, 2] , __UpperCAmelCase : Optional[Any]=[1, 2, 5, 8] , __UpperCAmelCase : int=[4, 4, 4, 4] , __UpperCAmelCase : str="gelu" , __UpperCAmelCase : int=0.0 , __UpperCAmelCase : Optional[int]=0.0 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : List[Any]=1e-6 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Union[str, Any]=10 , __UpperCAmelCase : List[Any]=-1 , **__UpperCAmelCase : Optional[int] , ) ->Dict: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = num_channels a = num_encoder_blocks a = depths a = sr_ratios a = hidden_sizes a = patch_sizes a = strides a = mlp_ratios a = num_attention_heads a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = drop_path_rate a = layer_norm_eps a = decoder_hidden_size a = max_depth a = head_in_index
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
import math from typing import Callable, List, Optional, Union import numpy as np import PIL import torch from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler def _a ( a :Optional[Any] , a :Optional[Any] , a :Any=[] ) -> Optional[int]: a = size[0] - overlap_pixels * 2 a = 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 a = np.ones((size_y, size_x) , dtype=np.uinta ) * 255 a = np.pad(a , mode='''linear_ramp''' , pad_width=a , end_values=0 ) if "l" in remove_borders: a = mask[:, overlap_pixels : mask.shape[1]] if "r" in remove_borders: a = mask[:, 0 : mask.shape[1] - overlap_pixels] if "t" in remove_borders: a = mask[overlap_pixels : mask.shape[0], :] if "b" in remove_borders: a = mask[0 : mask.shape[0] - overlap_pixels, :] return mask def _a ( a :Optional[Any] , a :Optional[int] , a :Union[str, Any] ) -> Any: return max(a , min(a , a ) ) def _a ( a :[int] , a :[int] , a :[int] ) -> int: 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 ( a :[int] , a :int , a :[int] ) -> Optional[int]: a = list(a ) rect[0] -= overlap rect[1] -= overlap rect[2] += overlap rect[3] += overlap a = clamp_rect(a , [0, 0] , [image_size[0], image_size[1]] ) return rect def _a ( a :List[str] , a :str , a :Optional[int] , a :List[Any] ) -> Dict: a = 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(a , (original_slice, 0) ) return result def _a ( a :Union[str, Any] , a :List[Any] ) -> Dict: a = (original_image_slice * 4, 0, tile.size[0], tile.size[1]) a = tile.crop(a ) return tile def _a ( a :List[str] , a :Optional[Any] ) -> int: a = n % d return n - divisor class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Any , __UpperCAmelCase : AutoencoderKL , __UpperCAmelCase : CLIPTextModel , __UpperCAmelCase : CLIPTokenizer , __UpperCAmelCase : UNetaDConditionModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __UpperCAmelCase : int = 350 , ) ->int: """simple docstring""" super().__init__( vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , unet=__UpperCAmelCase , low_res_scheduler=__UpperCAmelCase , scheduler=__UpperCAmelCase , max_noise_level=__UpperCAmelCase , ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] , **__UpperCAmelCase : Dict ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = ( 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 ), ) a = add_overlap_rect(__UpperCAmelCase , __UpperCAmelCase , image.size ) a = image.crop(__UpperCAmelCase ) a = ((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0] a = translated_slice_x - (original_image_slice / 2) a = max(0 , __UpperCAmelCase ) a = squeeze_tile(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = to_input.size a = to_input.resize((tile_size, tile_size) , Image.BICUBIC ) a = super(__UpperCAmelCase , self ).__call__(image=__UpperCAmelCase , **__UpperCAmelCase ).images[0] a = upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4) , Image.BICUBIC ) a = unsqueeze_tile(__UpperCAmelCase , __UpperCAmelCase ) a = upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4) , Image.BICUBIC ) a = [] 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''' ) a = Image.fromarray( make_transparency_mask( (upscaled_tile.size[0], upscaled_tile.size[1]) , tile_border * 4 , remove_borders=__UpperCAmelCase ) , mode='''L''' , ) final_image.paste( __UpperCAmelCase , (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4) , __UpperCAmelCase ) @torch.no_grad() def __call__( self : Any , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , __UpperCAmelCase : int = 75 , __UpperCAmelCase : float = 9.0 , __UpperCAmelCase : int = 50 , __UpperCAmelCase : Optional[Union[str, List[str]]] = None , __UpperCAmelCase : Optional[int] = 1 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : Optional[torch.Generator] = None , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __UpperCAmelCase : int = 1 , __UpperCAmelCase : int = 128 , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 32 , ) ->Optional[int]: """simple docstring""" a = Image.new('''RGB''' , (image.size[0] * 4, image.size[1] * 4) ) a = math.ceil(image.size[0] / tile_size ) a = math.ceil(image.size[1] / tile_size ) a = tcx * tcy a = 0 for y in range(__UpperCAmelCase ): for x in range(__UpperCAmelCase ): self._process_tile( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , prompt=__UpperCAmelCase , num_inference_steps=__UpperCAmelCase , guidance_scale=__UpperCAmelCase , noise_level=__UpperCAmelCase , negative_prompt=__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase , eta=__UpperCAmelCase , generator=__UpperCAmelCase , latents=__UpperCAmelCase , ) current_count += 1 if callback is not None: callback({'''progress''': current_count / total_tile_count, '''image''': final_image} ) return final_image def _a ( ) -> Dict: # Run a demo a = '''stabilityai/stable-diffusion-x4-upscaler''' a = StableDiffusionTiledUpscalePipeline.from_pretrained(a , revision='''fp16''' , torch_dtype=torch.floataa ) a = pipe.to('''cuda''' ) a = Image.open('''../../docs/source/imgs/diffusers_library.jpg''' ) def callback(a :str ): print(F"""progress: {obj['progress']:.4f}""" ) obj["image"].save('''diffusers_library_progress.jpg''' ) a = pipe(image=a , prompt='''Black font, white background, vector''' , noise_level=40 , callback=a ) final_image.save('''diffusers_library.jpg''' ) if __name__ == "__main__": main()
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "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" ), }, } UpperCAmelCase__ = { "google/electra-small-generator": 512, "google/electra-base-generator": 512, "google/electra-large-generator": 512, "google/electra-small-discriminator": 512, "google/electra-base-discriminator": 512, "google/electra-large-discriminator": 512, } UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ElectraTokenizer def __init__( self : Dict , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Any="[SEP]" , __UpperCAmelCase : str="[PAD]" , __UpperCAmelCase : Optional[Any]="[CLS]" , __UpperCAmelCase : Union[str, Any]="[MASK]" , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] , ) ->str: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple=None ) ->str: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
0
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' __snake_case = ViTImageProcessor if is_vision_available() else None @property def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" a = (3, 32, 128) a = tempfile.mkdtemp() # fmt: off a = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on a = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + '''\n''' ) a = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : List[Any] ) ->List[Any]: """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) a = Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) return image_input def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''test''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''test''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''labels'''] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] a = processor.char_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) a = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = None a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = MgpstrProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = torch.randn(1 , 27 , 38 ) a = torch.randn(1 , 27 , 50_257 ) a = torch.randn(1 , 27 , 30_522 ) a = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
1
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 lowercase_ ( lowercase ): '''simple docstring''' def __get__( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : List[Any]=None ) ->str: """simple docstring""" if obj is None: return self if self.fget is None: raise AttributeError('''unreadable attribute''' ) a = '''__cached_''' + self.fget.__name__ a = getattr(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if cached is None: a = self.fget(__UpperCAmelCase ) setattr(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) return cached def _a ( a :int ) -> Any: a = 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 ( a :str ) -> Any: if is_torch_fx_proxy(a ): return True if is_torch_available(): import torch if isinstance(a , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(a , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(a , (jnp.ndarray, Tracer) ): return True return isinstance(a , np.ndarray ) def _a ( a :Optional[Any] ) -> List[Any]: return isinstance(a , np.ndarray ) def _a ( a :Tuple ) -> Tuple: return _is_numpy(a ) def _a ( a :Dict ) -> Any: import torch return isinstance(a , torch.Tensor ) def _a ( a :Tuple ) -> Tuple: return False if not is_torch_available() else _is_torch(a ) def _a ( a :List[str] ) -> Optional[Any]: import torch return isinstance(a , torch.device ) def _a ( a :str ) -> List[Any]: return False if not is_torch_available() else _is_torch_device(a ) def _a ( a :Any ) -> List[str]: import torch if isinstance(a , a ): if hasattr(a , a ): a = getattr(a , a ) else: return False return isinstance(a , torch.dtype ) def _a ( a :Union[str, Any] ) -> str: return False if not is_torch_available() else _is_torch_dtype(a ) def _a ( a :str ) -> List[Any]: import tensorflow as tf return isinstance(a , tf.Tensor ) def _a ( a :Optional[Any] ) -> Optional[Any]: return False if not is_tf_available() else _is_tensorflow(a ) def _a ( a :Optional[int] ) -> str: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(a , '''is_symbolic_tensor''' ): return tf.is_symbolic_tensor(a ) return type(a ) == tf.Tensor def _a ( a :str ) -> Dict: return False if not is_tf_available() else _is_tf_symbolic_tensor(a ) def _a ( a :Union[str, Any] ) -> Optional[Any]: import jax.numpy as jnp # noqa: F811 return isinstance(a , jnp.ndarray ) def _a ( a :List[str] ) -> Dict: return False if not is_flax_available() else _is_jax(a ) def _a ( a :Tuple ) -> Dict: if isinstance(a , (dict, UserDict) ): return {k: to_py_obj(a ) for k, v in obj.items()} elif isinstance(a , (list, tuple) ): return [to_py_obj(a ) for o in obj] elif is_tf_tensor(a ): return obj.numpy().tolist() elif is_torch_tensor(a ): return obj.detach().cpu().tolist() elif is_jax_tensor(a ): return np.asarray(a ).tolist() elif isinstance(a , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def _a ( a :Dict ) -> Union[str, Any]: if isinstance(a , (dict, UserDict) ): return {k: to_numpy(a ) for k, v in obj.items()} elif isinstance(a , (list, tuple) ): return np.array(a ) elif is_tf_tensor(a ): return obj.numpy() elif is_torch_tensor(a ): return obj.detach().cpu().numpy() elif is_jax_tensor(a ): return np.asarray(a ) else: return obj class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Dict ) ->List[Any]: """simple docstring""" a = fields(self ) # Safety and consistency checks if not len(__UpperCAmelCase ): 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.""" ) a = getattr(self , class_fields[0].name ) a = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__UpperCAmelCase ): if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = first_field.items() a = True else: try: a = iter(__UpperCAmelCase ) a = True except TypeError: a = 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(__UpperCAmelCase ): if ( not isinstance(__UpperCAmelCase , (list, tuple) ) or not len(__UpperCAmelCase ) == 2 or not isinstance(element[0] , __UpperCAmelCase ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute a = 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: a = element[1] elif first_field is not None: a = first_field else: for field in class_fields: a = getattr(self , field.name ) if v is not None: a = v def __delitem__( self : List[str] , *__UpperCAmelCase : str , **__UpperCAmelCase : Union[str, Any] ) ->Optional[int]: """simple docstring""" raise Exception(F"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.""" ) def __lowerCAmelCase ( self : str , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : int ) ->Optional[Any]: """simple docstring""" raise Exception(F"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance.""" ) def __lowerCAmelCase ( self : List[str] , *__UpperCAmelCase : Any , **__UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" raise Exception(F"""You cannot use ``pop`` on a {self.__class__.__name__} instance.""" ) def __lowerCAmelCase ( self : Optional[int] , *__UpperCAmelCase : Dict , **__UpperCAmelCase : List[str] ) ->List[Any]: """simple docstring""" raise Exception(F"""You cannot use ``update`` on a {self.__class__.__name__} instance.""" ) def __getitem__( self : Optional[Any] , __UpperCAmelCase : int ) ->Union[str, Any]: """simple docstring""" if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] ) ->Any: """simple docstring""" if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__UpperCAmelCase , __UpperCAmelCase ) super().__setattr__(__UpperCAmelCase , __UpperCAmelCase ) def __setitem__( self : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any] ) ->Optional[Any]: """simple docstring""" super().__setitem__(__UpperCAmelCase , __UpperCAmelCase ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple[Any]: """simple docstring""" return tuple(self[k] for k in self.keys() ) class lowercase_ ( lowercase , lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : Optional[Any] , __UpperCAmelCase : Dict ) ->List[str]: """simple docstring""" raise ValueError( F"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}""" ) class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''longest''' __snake_case = '''max_length''' __snake_case = '''do_not_pad''' class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''pt''' __snake_case = '''tf''' __snake_case = '''np''' __snake_case = '''jax''' class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : List[ContextManager] ) ->Optional[Any]: """simple docstring""" a = context_managers a = ExitStack() def __enter__( self : str ) ->Dict: """simple docstring""" for context_manager in self.context_managers: self.stack.enter_context(__UpperCAmelCase ) def __exit__( self : int , *__UpperCAmelCase : Optional[int] , **__UpperCAmelCase : Optional[int] ) ->Optional[int]: """simple docstring""" self.stack.__exit__(*__UpperCAmelCase , **__UpperCAmelCase ) def _a ( a :List[Any] ) -> Optional[Any]: a = infer_framework(a ) if framework == "tf": a = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": a = inspect.signature(model_class.forward ) # PyTorch models else: a = 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 ( a :Union[str, Any] ) -> Any: a = model_class.__name__ a = infer_framework(a ) if framework == "tf": a = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": a = inspect.signature(model_class.forward ) # PyTorch models else: a = 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 ( a :MutableMapping , a :str = "" , a :str = "." ) -> Tuple: def _flatten_dict(a :Optional[Any] , a :int="" , a :List[str]="." ): for k, v in d.items(): a = str(a ) + delimiter + str(a ) if parent_key else k if v and isinstance(a , a ): yield from flatten_dict(a , a , delimiter=a ).items() else: yield key, v return dict(_flatten_dict(a , a , a ) ) @contextmanager def _a ( a :Any , a :bool = False ) -> List[str]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def _a ( a :List[Any] , a :List[str]=None ) -> List[str]: if is_numpy_array(a ): return np.transpose(a , axes=a ) elif is_torch_tensor(a ): return array.T if axes is None else array.permute(*a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.transpose(a , perm=a ) elif is_jax_tensor(a ): return jnp.transpose(a , axes=a ) else: raise ValueError(F"""Type not supported for transpose: {type(a )}.""" ) def _a ( a :int , a :Optional[int] ) -> Dict: if is_numpy_array(a ): return np.reshape(a , a ) elif is_torch_tensor(a ): return array.reshape(*a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.reshape(a , a ) elif is_jax_tensor(a ): return jnp.reshape(a , a ) else: raise ValueError(F"""Type not supported for reshape: {type(a )}.""" ) def _a ( a :Dict , a :int=None ) -> List[Any]: if is_numpy_array(a ): return np.squeeze(a , axis=a ) elif is_torch_tensor(a ): return array.squeeze() if axis is None else array.squeeze(dim=a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.squeeze(a , axis=a ) elif is_jax_tensor(a ): return jnp.squeeze(a , axis=a ) else: raise ValueError(F"""Type not supported for squeeze: {type(a )}.""" ) def _a ( a :Dict , a :Optional[int] ) -> Dict: if is_numpy_array(a ): return np.expand_dims(a , a ) elif is_torch_tensor(a ): return array.unsqueeze(dim=a ) elif is_tf_tensor(a ): import tensorflow as tf return tf.expand_dims(a , axis=a ) elif is_jax_tensor(a ): return jnp.expand_dims(a , axis=a ) else: raise ValueError(F"""Type not supported for expand_dims: {type(a )}.""" ) def _a ( a :List[Any] ) -> Tuple: if is_numpy_array(a ): return np.size(a ) elif is_torch_tensor(a ): return array.numel() elif is_tf_tensor(a ): import tensorflow as tf return tf.size(a ) elif is_jax_tensor(a ): return array.size else: raise ValueError(F"""Type not supported for expand_dims: {type(a )}.""" ) def _a ( a :List[Any] , a :int ) -> List[Any]: for key, value in auto_map.items(): if isinstance(a , (tuple, list) ): a = [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: a = F"""{repo_id}--{value}""" return auto_map def _a ( a :str ) -> Union[str, Any]: for base_class in inspect.getmro(a ): a = base_class.__module__ a = 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}.""" )
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
1
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING UpperCAmelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowercase ) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : str , **__UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" super().__init__(**__UpperCAmelCase ) if self.framework == "tf": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) requires_backends(self , '''vision''' ) self.check_model_type(__UpperCAmelCase ) def __call__( self : Optional[Any] , __UpperCAmelCase : Union[str, "Image.Image", List[Dict[str, Any]]] , __UpperCAmelCase : Union[str, List[str]] = None , **__UpperCAmelCase : Dict , ) ->Optional[int]: """simple docstring""" if "text_queries" in kwargs: a = kwargs.pop('''text_queries''' ) if isinstance(__UpperCAmelCase , (str, Image.Image) ): a = {'''image''': image, '''candidate_labels''': candidate_labels} else: a = image a = super().__call__(__UpperCAmelCase , **__UpperCAmelCase ) return results def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Dict: """simple docstring""" a = {} if "threshold" in kwargs: a = kwargs['''threshold'''] if "top_k" in kwargs: a = kwargs['''top_k'''] return {}, {}, postprocess_params def __lowerCAmelCase ( self : str , __UpperCAmelCase : int ) ->Optional[Any]: """simple docstring""" a = load_image(inputs['''image'''] ) a = inputs['''candidate_labels'''] if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = candidate_labels.split(''',''' ) a = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(__UpperCAmelCase ): a = self.tokenizer(__UpperCAmelCase , return_tensors=self.framework ) a = self.image_processor(__UpperCAmelCase , return_tensors=self.framework ) yield { "is_last": i == len(__UpperCAmelCase ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : int ) ->str: """simple docstring""" a = model_inputs.pop('''target_size''' ) a = model_inputs.pop('''candidate_label''' ) a = model_inputs.pop('''is_last''' ) a = self.model(**__UpperCAmelCase ) a = {'''target_size''': target_size, '''candidate_label''': candidate_label, '''is_last''': is_last, **outputs} return model_outputs def __lowerCAmelCase ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : List[str]=None ) ->List[Any]: """simple docstring""" a = [] for model_output in model_outputs: a = model_output['''candidate_label'''] a = BaseModelOutput(__UpperCAmelCase ) a = self.image_processor.post_process_object_detection( outputs=__UpperCAmelCase , threshold=__UpperCAmelCase , target_sizes=model_output['''target_size'''] )[0] for index in outputs["scores"].nonzero(): a = outputs['''scores'''][index].item() a = self._get_bounding_box(outputs['''boxes'''][index][0] ) a = {'''score''': score, '''label''': label, '''box''': box} results.append(__UpperCAmelCase ) a = sorted(__UpperCAmelCase , key=lambda __UpperCAmelCase : x["score"] , reverse=__UpperCAmelCase ) if top_k: a = results[:top_k] return results def __lowerCAmelCase ( self : Any , __UpperCAmelCase : "torch.Tensor" ) ->Dict[str, int]: """simple docstring""" if self.framework != "pt": raise ValueError('''The ZeroShotObjectDetectionPipeline is only available in PyTorch.''' ) a , a , a , a = box.int().tolist() a = { '''xmin''': xmin, '''ymin''': ymin, '''xmax''': xmax, '''ymax''': ymax, } return bbox
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {} class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''llama''' __snake_case = ['''past_key_values'''] def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]=32_000 , __UpperCAmelCase : str=4_096 , __UpperCAmelCase : int=11_008 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]="silu" , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Any=1e-6 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Tuple , ) ->str: """simple docstring""" a = vocab_size a = max_position_embeddings a = hidden_size a = intermediate_size a = num_hidden_layers a = num_attention_heads # for backward compatibility if num_key_value_heads is None: a = num_attention_heads a = num_key_value_heads a = hidden_act a = initializer_range a = rms_norm_eps a = pretraining_tp a = use_cache a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) 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}""" ) a = self.rope_scaling.get('''type''' , __UpperCAmelCase ) a = self.rope_scaling.get('''factor''' , __UpperCAmelCase ) 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(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
0
1
UpperCAmelCase__ = tuple[float, float, float] UpperCAmelCase__ = tuple[float, float, float] def _a ( a :Pointad , a :Pointad ) -> Vectorad: a = end_pointa[0] - end_pointa[0] a = end_pointa[1] - end_pointa[1] a = end_pointa[2] - end_pointa[2] return (x, y, z) def _a ( a :Vectorad , a :Vectorad ) -> Vectorad: a = ab[1] * ac[2] - ab[2] * ac[1] # *i a = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j a = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def _a ( a :Vectorad , a :int ) -> bool: return tuple(round(a , a ) for x in vector ) == (0, 0, 0) def _a ( a :Pointad , a :Pointad , a :Pointad , a :int = 10 ) -> bool: a = create_vector(a , a ) a = create_vector(a , a ) return is_zero_vector(get_ad_vectors_cross(a , a ) , a )
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
import math import tensorflow as tf from packaging import version def _a ( a :Any ) -> Union[str, Any]: a = tf.convert_to_tensor(a ) a = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def _a ( a :Union[str, Any] ) -> Union[str, Any]: a = tf.convert_to_tensor(a ) a = tf.cast(math.pi , x.dtype ) a = tf.cast(0.044_715 , x.dtype ) a = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(a , 3 )) )) return x * cdf def _a ( a :List[Any] ) -> Optional[int]: a = tf.convert_to_tensor(a ) return x * tf.tanh(tf.math.softplus(a ) ) def _a ( a :Union[str, Any] ) -> Tuple: a = tf.convert_to_tensor(a ) a = tf.cast(0.044_715 , x.dtype ) a = tf.cast(0.7_978_845_608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def _a ( a :Union[str, Any] ) -> Optional[Any]: a = tf.convert_to_tensor(a ) a = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def _a ( a :List[str] ) -> List[str]: return tf.clip_by_value(_gelu(a ) , -10 , 10 ) def _a ( a :Dict , a :Optional[Any]=-1 ) -> Union[str, Any]: a , a = tf.split(a , 2 , axis=a ) return a * tf.math.sigmoid(a ) if version.parse(tf.version.VERSION) >= version.parse("2.4"): def _a ( a :int ) -> List[str]: return tf.keras.activations.gelu(a , approximate=a ) UpperCAmelCase__ = tf.keras.activations.gelu UpperCAmelCase__ = approximate_gelu_wrap else: UpperCAmelCase__ = _gelu UpperCAmelCase__ = _gelu_new UpperCAmelCase__ = { "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 ( a :Dict ) -> List[Any]: if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ = { "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"], "processing_speech_to_text": ["Speech2TextProcessor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["Speech2TextTokenizer"] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["Speech2TextFeatureExtractor"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
import os from datetime import datetime as dt from github import Github UpperCAmelCase__ = [ "good first issue", "feature request", "wip", ] def _a ( ) -> List[str]: a = Github(os.environ['''GITHUB_TOKEN'''] ) a = g.get_repo('''huggingface/accelerate''' ) a = repo.get_issues(state='''open''' ) for issue in open_issues: a = sorted([comment for comment in issue.get_comments()] , key=lambda a : i.created_at , reverse=a ) a = comments[0] if len(a ) > 0 else None a = dt.utcnow() a = (current_time - issue.updated_at).days a = (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()
0
def _a ( a :float , a :float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
0
1
import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :str ) -> Dict: a = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: a = 128 elif "12-12" in model_name: a = 12 a = 12 elif "14-14" in model_name: a = 14 a = 14 elif "16-16" in model_name: a = 16 a = 16 else: raise ValueError('''Model not supported''' ) a = '''huggingface/label-files''' if "speech-commands" in model_name: a = 35 a = '''speech-commands-v2-id2label.json''' else: a = 527 a = '''audioset-id2label.json''' a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} return config def _a ( a :Optional[Any] ) -> Union[str, Any]: if "module.v" in name: a = name.replace('''module.v''' , '''audio_spectrogram_transformer''' ) if "cls_token" in name: a = name.replace('''cls_token''' , '''embeddings.cls_token''' ) if "dist_token" in name: a = name.replace('''dist_token''' , '''embeddings.distillation_token''' ) if "pos_embed" in name: a = name.replace('''pos_embed''' , '''embeddings.position_embeddings''' ) if "patch_embed.proj" in name: a = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) # transformer blocks if "blocks" in name: a = name.replace('''blocks''' , '''encoder.layer''' ) if "attn.proj" in name: a = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: a = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: a = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: a = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: a = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: a = name.replace('''mlp.fc2''' , '''output.dense''' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: a = name.replace('''audio_spectrogram_transformer.norm''' , '''audio_spectrogram_transformer.layernorm''' ) # classifier head if "module.mlp_head.0" in name: a = name.replace('''module.mlp_head.0''' , '''classifier.layernorm''' ) if "module.mlp_head.1" in name: a = name.replace('''module.mlp_head.1''' , '''classifier.dense''' ) return name def _a ( a :Optional[int] , a :List[str] ) -> Any: for key in orig_state_dict.copy().keys(): a = orig_state_dict.pop(a ) if "qkv" in key: a = key.split('''.''' ) a = int(key_split[3] ) a = config.hidden_size if "weight" in key: a = val[:dim, :] a = val[dim : dim * 2, :] a = val[-dim:, :] else: a = val[:dim] a = val[dim : dim * 2] a = val[-dim:] else: a = val return orig_state_dict def _a ( a :Union[str, Any] ) -> Optional[Any]: a = [ '''module.v.head.weight''', '''module.v.head.bias''', '''module.v.head_dist.weight''', '''module.v.head_dist.bias''', ] for k in ignore_keys: state_dict.pop(a , a ) @torch.no_grad() def _a ( a :Union[str, Any] , a :Optional[int] , a :str=False ) -> Union[str, Any]: a = get_audio_spectrogram_transformer_config(a ) a = { '''ast-finetuned-audioset-10-10-0.4593''': ( '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.450''': ( '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448''': ( '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1''' ), '''ast-finetuned-audioset-10-10-0.448-v2''': ( '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1''' ), '''ast-finetuned-audioset-12-12-0.447''': ( '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1''' ), '''ast-finetuned-audioset-14-14-0.443''': ( '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1''' ), '''ast-finetuned-audioset-16-16-0.442''': ( '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1''' ), '''ast-finetuned-speech-commands-v2''': ( '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1''' ), } # load original state_dict a = model_name_to_url[model_name] a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' ) # remove some keys remove_keys(a ) # rename some keys a = convert_state_dict(a , a ) # load 🤗 model a = ASTForAudioClassification(a ) model.eval() model.load_state_dict(a ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 a = -4.2_677_393 if '''speech-commands''' not in model_name else -6.845_978 a = 4.5_689_974 if '''speech-commands''' not in model_name else 5.5_654_526 a = 1_024 if '''speech-commands''' not in model_name else 128 a = ASTFeatureExtractor(mean=a , std=a , max_length=a ) if "speech-commands" in model_name: a = load_dataset('''speech_commands''' , '''v0.02''' , split='''validation''' ) a = dataset[0]['''audio''']['''array'''] else: a = hf_hub_download( repo_id='''nielsr/audio-spectogram-transformer-checkpoint''' , filename='''sample_audio.flac''' , repo_type='''dataset''' , ) a , a = torchaudio.load(a ) a = waveform.squeeze().numpy() a = feature_extractor(a , sampling_rate=16_000 , return_tensors='''pt''' ) # forward pass a = model(**a ) a = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": a = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": a = torch.tensor([-1.1_986, -7.0_903, -8.2_718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": a = torch.tensor([-2.6_128, -8.0_080, -9.4_344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": a = torch.tensor([-1.5_080, -7.4_534, -8.8_917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": a = torch.tensor([-0.5_050, -6.5_833, -8.0_843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": a = torch.tensor([-0.3_826, -7.0_336, -8.2_413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": a = torch.tensor([-1.2_113, -6.9_101, -8.3_470] ) elif model_name == "ast-finetuned-speech-commands-v2": a = torch.tensor([6.1_589, -8.0_566, -8.7_984] ) else: raise ValueError('''Unknown model name''' ) if not torch.allclose(logits[0, :3] , a , atol=1e-4 ): raise ValueError('''Logits don\'t match''' ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(a ).mkdir(exist_ok=a ) print(F"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(a ) print(F"""Saving feature extractor to {pytorch_dump_folder_path}""" ) feature_extractor.save_pretrained(a ) if push_to_hub: print('''Pushing model and feature extractor to the hub...''' ) model.push_to_hub(F"""MIT/{model_name}""" ) feature_extractor.push_to_hub(F"""MIT/{model_name}""" ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="ast-finetuned-audioset-10-10-0.4593", type=str, help="Name of the Audio Spectrogram Transformer model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) UpperCAmelCase__ = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
0
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
1
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 ViTImageProcessor class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Dict , __UpperCAmelCase : Any , __UpperCAmelCase : List[str]=13 , __UpperCAmelCase : List[Any]=3 , __UpperCAmelCase : Tuple=224 , __UpperCAmelCase : Dict=30 , __UpperCAmelCase : Any=400 , __UpperCAmelCase : Any=True , __UpperCAmelCase : Any=None , __UpperCAmelCase : str=True , __UpperCAmelCase : Optional[int]=[0.5, 0.5, 0.5] , __UpperCAmelCase : Optional[Any]=[0.5, 0.5, 0.5] , ) ->Optional[int]: """simple docstring""" a = size if size is not None else {'''height''': 18, '''width''': 18} a = parent a = batch_size a = num_channels a = image_size a = min_resolution a = max_resolution a = do_resize a = size a = do_normalize a = image_mean a = image_std def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ViTImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = EfficientFormerImageProcessorTester(self ) @property def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Dict ) ->Tuple: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_mean''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''image_std''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__UpperCAmelCase , '''size''' ) ) def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" pass def __lowerCAmelCase ( self : List[str] ) ->Optional[int]: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_proc_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input a = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched a = image_processor(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_proc_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input a = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched a = image_processor(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_proc_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input a = image_processor(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , ) # Test batched a = image_processor(__UpperCAmelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['''height'''], self.image_proc_tester.size['''width'''], ) , )
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ProphetNetTokenizer __snake_case = False def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = '''UNwant\u00E9d,running''' a = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__UpperCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , 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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] a = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : Any ) ->List[str]: """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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
def _a ( a :int = 1_000 ) -> int: a = 2**power a = str(a ) a = list(a ) a = 0 for i in list_num: sum_of_num += int(a ) return sum_of_num if __name__ == "__main__": UpperCAmelCase__ = int(input("Enter the power of 2: ").strip()) print("2 ^ ", power, " = ", 2**power) UpperCAmelCase__ = solution(power) print("Sum of the digits is: ", result)
0
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''van''' def __init__( self : List[str] , __UpperCAmelCase : int=224 , __UpperCAmelCase : Tuple=3 , __UpperCAmelCase : Optional[Any]=[7, 3, 3, 3] , __UpperCAmelCase : Tuple=[4, 2, 2, 2] , __UpperCAmelCase : Optional[Any]=[64, 128, 320, 512] , __UpperCAmelCase : List[str]=[3, 3, 12, 3] , __UpperCAmelCase : Optional[int]=[8, 8, 4, 4] , __UpperCAmelCase : Optional[int]="gelu" , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Optional[Any]=1e-6 , __UpperCAmelCase : str=1e-2 , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : Optional[Any]=0.0 , **__UpperCAmelCase : List[Any] , ) ->Union[str, Any]: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = image_size a = num_channels a = patch_sizes a = strides a = hidden_sizes a = depths a = mlp_ratios a = hidden_act a = initializer_range a = layer_norm_eps a = layer_scale_init_value a = drop_path_rate a = dropout_rate
0
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
from __future__ import annotations from math import pow, sqrt def _a ( a :float , a :float , a :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(a , 2 ) - pow(a , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(a , 2 ) - pow(a , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(a , 2 ) + pow(a , 2 ) )} else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
1
import argparse from pathlib import Path import torch from packaging import version from torch.onnx import export from diffusers import AutoencoderKL UpperCAmelCase__ = version.parse(version.parse(torch.__version__).base_version) < version.parse("1.11") def _a ( a :Optional[int] , a :tuple , a :Path , a :int , a :Optional[Any] , a :Any , a :Union[str, Any] , a :int=False , ) -> Union[str, Any]: output_path.parent.mkdir(parents=a , exist_ok=a ) # 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( a , a , f=output_path.as_posix() , input_names=a , output_names=a , dynamic_axes=a , do_constant_folding=a , use_external_data_format=a , enable_onnx_checker=a , opset_version=a , ) else: export( a , a , f=output_path.as_posix() , input_names=a , output_names=a , dynamic_axes=a , do_constant_folding=a , opset_version=a , ) @torch.no_grad() def _a ( a :str , a :str , a :int , a :bool = False ) -> List[Any]: a = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): a = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: a = '''cpu''' a = Path(a ) # VAE DECODER a = AutoencoderKL.from_pretrained(model_path + '''/vae''' ) a = vae_decoder.config.latent_channels # forward only through the decoder part a = vae_decoder.decode onnx_export( a , model_args=( torch.randn(1 , a , 25 , 25 ).to(device=a , dtype=a ), 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=a , ) del vae_decoder if __name__ == "__main__": UpperCAmelCase__ = 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=14, 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") UpperCAmelCase__ = parser.parse_args() print(args.output_path) convert_models(args.model_path, args.output_path, args.opset, args.fpaa) print("SD: Done: ONNX")
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaPriorPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt''', '''negative_prompt'''] __snake_case = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" return 100 @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 12, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a = PriorTransformer(**__UpperCAmelCase ) # 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 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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 , ) a = CLIPVisionModelWithProjection(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__UpperCAmelCase , clip_sample_range=10.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str=0 ) ->int: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) 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 __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = torch_device == '''cpu''' a = True a = False self._test_inference_batch_single_identical( test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , ) @skip_mps def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = torch_device == '''cpu''' a = False self._test_attention_slicing_forward_pass( test_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , )
0
1
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 lowercase_ : '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple=13 , __UpperCAmelCase : List[str]=7 , __UpperCAmelCase : str=True , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : List[Any]=True , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : int=False , __UpperCAmelCase : str=False , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : List[str]=2 , __UpperCAmelCase : int=99 , __UpperCAmelCase : str=0 , __UpperCAmelCase : Dict=32 , __UpperCAmelCase : str=5 , __UpperCAmelCase : Any=4 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : Union[str, Any]=512 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : str=4 , __UpperCAmelCase : Any="last" , __UpperCAmelCase : str=True , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Tuple=0 , ) ->List[str]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_input_lengths a = use_token_type_ids a = use_labels a = gelu_activation a = sinusoidal_embeddings a = causal a = asm a = n_langs a = vocab_size a = n_special a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_sequence_label_size a = initializer_range a = num_labels a = num_choices a = summary_type a = use_proj a = scope a = bos_token_id def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_input_lengths: a = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) a = None a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a = ids_tensor([self.batch_size] , 2 ).float() a = ids_tensor([self.batch_size] , self.num_choices ) a = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def __lowerCAmelCase ( self : List[Any] ) ->Optional[int]: """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 __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] , ) ->List[str]: """simple docstring""" a = XLMModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , lengths=__UpperCAmelCase , langs=__UpperCAmelCase ) a = model(__UpperCAmelCase , langs=__UpperCAmelCase ) a = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[Any] , ) ->Any: """simple docstring""" a = XLMWithLMHeadModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : str , __UpperCAmelCase : List[str] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Dict , ) ->Optional[Any]: """simple docstring""" a = XLMForQuestionAnsweringSimple(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase ) a = model(__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase ) a = 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 __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] , ) ->List[Any]: """simple docstring""" a = XLMForQuestionAnswering(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase ) a = model( __UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , cls_index=__UpperCAmelCase , is_impossible=__UpperCAmelCase , p_mask=__UpperCAmelCase , ) a = model( __UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase , cls_index=__UpperCAmelCase , is_impossible=__UpperCAmelCase , ) ((a) , ) = result_with_labels.to_tuple() a = model(__UpperCAmelCase , start_positions=__UpperCAmelCase , end_positions=__UpperCAmelCase ) ((a) , ) = 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 __lowerCAmelCase ( self : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , ) ->Dict: """simple docstring""" a = XLMForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase ) a = model(__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = self.num_labels a = XLMForTokenClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int , __UpperCAmelCase : Dict , __UpperCAmelCase : List[str] , ) ->str: """simple docstring""" a = self.num_choices a = XLMForMultipleChoice(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths} return config, inputs_dict @require_torch class lowercase_ ( lowercase , lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) __snake_case = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable __snake_case = ( { '''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 __lowerCAmelCase ( self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : int , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] ) ->int: """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 __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str]=False ) ->int: """simple docstring""" a = super()._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__UpperCAmelCase ) a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__UpperCAmelCase ) return inputs_dict def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = XLMModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , emb_dim=37 ) def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*__UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : int=False , __UpperCAmelCase : int=1 ) ->Dict: """simple docstring""" self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual( [isinstance(__UpperCAmelCase , __UpperCAmelCase ) for iter_attentions in attentions] , [True] * len(__UpperCAmelCase ) ) self.assertEqual(len(__UpperCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(__UpperCAmelCase ): # adds PAD dummy token a = min_length + idx + 1 a = min_length + idx + 1 a = ( 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(__UpperCAmelCase ) ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : int=1 ) ->Dict: """simple docstring""" self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertListEqual( [isinstance(__UpperCAmelCase , __UpperCAmelCase ) for iter_hidden_states in hidden_states] , [True] * len(__UpperCAmelCase ) , ) self.assertEqual(len(__UpperCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(__UpperCAmelCase ): # adds PAD dummy token a = min_length + idx + 1 a = (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(__UpperCAmelCase ) , ) pass @slow def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = XLMModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''' ) model.to(__UpperCAmelCase ) a = torch.tensor([[14, 447]] , dtype=torch.long , device=__UpperCAmelCase ) # the president a = [ 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 a = model.generate(__UpperCAmelCase , do_sample=__UpperCAmelCase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __UpperCAmelCase )
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
1
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase_ : '''simple docstring''' def __init__( self : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str]=3 , __UpperCAmelCase : Dict=32 , __UpperCAmelCase : int=3 , __UpperCAmelCase : Optional[Any]=10 , __UpperCAmelCase : str=[10, 20, 30, 40] , __UpperCAmelCase : Optional[int]=[1, 1, 2, 1] , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : int="relu" , __UpperCAmelCase : Dict=3 , __UpperCAmelCase : str=None , ) ->List[Any]: """simple docstring""" a = parent a = batch_size a = image_size a = num_channels a = embeddings_size a = hidden_sizes a = depths a = is_training a = use_labels a = hidden_act a = num_labels a = scope a = len(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.num_labels ) a = self.get_config() return config, pixel_values, labels def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[Any] , __UpperCAmelCase : Any ) ->List[Any]: """simple docstring""" a = TFRegNetModel(config=__UpperCAmelCase ) a = model(__UpperCAmelCase , training=__UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : int ) ->Union[str, Any]: """simple docstring""" a = self.num_labels a = TFRegNetForImageClassification(__UpperCAmelCase ) a = model(__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" a = self.prepare_config_and_inputs() a , a , a = config_and_inputs a = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowercase_ ( lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __snake_case = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False __snake_case = False __snake_case = False def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = TFRegNetModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __lowerCAmelCase ( self : str ) ->Any: """simple docstring""" pass def __lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) a = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a = [*signature.parameters.keys()] a = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->str: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" def check_hidden_states_output(__UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any] ): a = model_class(__UpperCAmelCase ) a = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) , training=__UpperCAmelCase ) a = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a = self.model_tester.num_stages self.assertEqual(len(__UpperCAmelCase ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) a , a = self.model_tester.prepare_config_and_inputs_for_common() a = ['''basic''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: a = layer_type a = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a = True check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a , a = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(__UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str]={} ): a = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ) a = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ).to_tuple() def recursive_check(__UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int ): if isinstance(__UpperCAmelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(__UpperCAmelCase , __UpperCAmelCase ): recursive_check(__UpperCAmelCase , __UpperCAmelCase ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(__UpperCAmelCase , __UpperCAmelCase ) ) , msg=( '''Tuple and dict output are not equal. Difference:''' F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}""" ) , ) recursive_check(__UpperCAmelCase , __UpperCAmelCase ) for model_class in self.all_model_classes: a = model_class(__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'''output_hidden_states''': True} ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) a = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase ) check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {'''output_hidden_states''': True} ) def __lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = TFRegNetModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def _a ( ) -> Tuple: a = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowercase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" a = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) a = self.default_image_processor a = prepare_img() a = image_processor(images=__UpperCAmelCase , return_tensors='''tf''' ) # forward pass a = model(**__UpperCAmelCase , training=__UpperCAmelCase ) # verify the logits a = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , __UpperCAmelCase ) a = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , __UpperCAmelCase , atol=1e-4 )
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
import numpy as np def _a ( a :np.ndarray , a :np.ndarray , a :float = 1e-12 , a :int = 100 , ) -> tuple[float, np.ndarray]: assert np.shape(a )[0] == np.shape(a )[1] # Ensure proper dimensionality. assert np.shape(a )[0] == np.shape(a )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a ) == np.iscomplexobj(a ) a = np.iscomplexobj(a ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. a = False a = 0 a = 0 a = 1e12 while not convergence: # Multiple matrix by the vector. a = np.dot(a , a ) # Normalize the resulting output vector. a = w / np.linalg.norm(a ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) a = vector.conj().T if is_complex else vector.T a = np.dot(a , np.dot(a , a ) ) # Check convergence. a = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: a = True a = lambda_ if is_complex: a = np.real(lambda_ ) return lambda_, vector def _a ( ) -> None: a = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) a = np.array([41, 4, 20] ) a = real_input_matrix.astype(np.complexaaa ) a = np.triu(1j * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T a = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": a = real_input_matrix a = real_vector elif problem_type == "complex": a = complex_input_matrix a = complex_vector # Our implementation. a , a = power_iteration(a , a ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). a , a = np.linalg.eigh(a ) # Last eigenvalue is the maximum one. a = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. a = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a ) - np.abs(a ) ) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
import fire from utils import calculate_rouge, save_json def _a ( a :Optional[int] , a :Tuple , a :Tuple=None , **a :Union[str, Any] ) -> Any: a = [x.strip() for x in open(a ).readlines()] a = [x.strip() for x in open(a ).readlines()][: len(a )] a = calculate_rouge(a , a , **a ) if save_path is not None: save_json(a , a , indent=a ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
def _a ( a :int , a :int ) -> int: return int((input_a, input_a).count(0 ) != 0 ) def _a ( ) -> None: assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
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, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 __snake_case = 42 class lowercase_ ( nn.Module ): '''simple docstring''' __snake_case = 42 __snake_case = (16, 32, 96, 2_56) __snake_case = jnp.floataa def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" a = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a = [] for i in range(len(self.block_out_channels ) - 1 ): a = self.block_out_channels[i] a = self.block_out_channels[i + 1] a = nn.Conv( __UpperCAmelCase , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__UpperCAmelCase ) a = nn.Conv( __UpperCAmelCase , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__UpperCAmelCase ) a = blocks a = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : List[Any] , __UpperCAmelCase : Any ) ->Dict: """simple docstring""" a = self.conv_in(__UpperCAmelCase ) a = nn.silu(__UpperCAmelCase ) for block in self.blocks: a = block(__UpperCAmelCase ) a = nn.silu(__UpperCAmelCase ) a = self.conv_out(__UpperCAmelCase ) return embedding @flax_register_to_config class lowercase_ ( nn.Module , lowercase , lowercase ): '''simple docstring''' __snake_case = 32 __snake_case = 4 __snake_case = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) __snake_case = False __snake_case = (3_20, 6_40, 12_80, 12_80) __snake_case = 2 __snake_case = 8 __snake_case = None __snake_case = 12_80 __snake_case = 0.0 __snake_case = False __snake_case = jnp.floataa __snake_case = True __snake_case = 0 __snake_case = "rgb" __snake_case = (16, 32, 96, 2_56) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : jax.random.KeyArray ) ->FrozenDict: """simple docstring""" a = (1, self.in_channels, self.sample_size, self.sample_size) a = jnp.zeros(__UpperCAmelCase , dtype=jnp.floataa ) a = jnp.ones((1,) , dtype=jnp.intaa ) a = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) a = (1, 3, self.sample_size * 8, self.sample_size * 8) a = jnp.zeros(__UpperCAmelCase , dtype=jnp.floataa ) a , a = jax.random.split(__UpperCAmelCase ) a = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )["params"] def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = self.block_out_channels a = block_out_channels[0] * 4 # 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. a = self.num_attention_heads or self.attention_head_dim # input a = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time a = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) a = FlaxTimestepEmbedding(__UpperCAmelCase , dtype=self.dtype ) a = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) a = self.only_cross_attention if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = (num_attention_heads,) * len(self.down_block_types ) # down a = [] a = [] a = block_out_channels[0] a = nn.Conv( __UpperCAmelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__UpperCAmelCase ) for i, down_block_type in enumerate(self.down_block_types ): a = output_channel a = block_out_channels[i] a = i == len(__UpperCAmelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": a = FlaxCrossAttnDownBlockaD( in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , 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] , dtype=self.dtype , ) else: a = FlaxDownBlockaD( in_channels=__UpperCAmelCase , out_channels=__UpperCAmelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__UpperCAmelCase ) for _ in range(self.layers_per_block ): a = nn.Conv( __UpperCAmelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__UpperCAmelCase ) if not is_final_block: a = nn.Conv( __UpperCAmelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__UpperCAmelCase ) a = down_blocks a = controlnet_down_blocks # mid a = block_out_channels[-1] a = FlaxUNetMidBlockaDCrossAttn( in_channels=__UpperCAmelCase , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) a = nn.Conv( __UpperCAmelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : Tuple , __UpperCAmelCase : float = 1.0 , __UpperCAmelCase : bool = True , __UpperCAmelCase : bool = False , ) ->Union[FlaxControlNetOutput, Tuple]: """simple docstring""" a = self.controlnet_conditioning_channel_order if channel_order == "bgr": a = jnp.flip(__UpperCAmelCase , axis=1 ) # 1. time if not isinstance(__UpperCAmelCase , jnp.ndarray ): a = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__UpperCAmelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: a = timesteps.astype(dtype=jnp.floataa ) a = jnp.expand_dims(__UpperCAmelCase , 0 ) a = self.time_proj(__UpperCAmelCase ) a = self.time_embedding(__UpperCAmelCase ) # 2. pre-process a = jnp.transpose(__UpperCAmelCase , (0, 2, 3, 1) ) a = self.conv_in(__UpperCAmelCase ) a = jnp.transpose(__UpperCAmelCase , (0, 2, 3, 1) ) a = self.controlnet_cond_embedding(__UpperCAmelCase ) sample += controlnet_cond # 3. down a = (sample,) for down_block in self.down_blocks: if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a , a = down_block(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , deterministic=not train ) else: a , a = down_block(__UpperCAmelCase , __UpperCAmelCase , deterministic=not train ) down_block_res_samples += res_samples # 4. mid a = self.mid_block(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , deterministic=not train ) # 5. contronet blocks a = () for down_block_res_sample, controlnet_block in zip(__UpperCAmelCase , self.controlnet_down_blocks ): a = controlnet_block(__UpperCAmelCase ) controlnet_down_block_res_samples += (down_block_res_sample,) a = controlnet_down_block_res_samples a = self.controlnet_mid_block(__UpperCAmelCase ) # 6. scaling a = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=__UpperCAmelCase , mid_block_res_sample=__UpperCAmelCase )
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "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" ), }, } UpperCAmelCase__ = { "google/electra-small-generator": 512, "google/electra-base-generator": 512, "google/electra-large-generator": 512, "google/electra-small-discriminator": 512, "google/electra-base-discriminator": 512, "google/electra-large-discriminator": 512, } UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ElectraTokenizer def __init__( self : Dict , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Any="[SEP]" , __UpperCAmelCase : str="[PAD]" , __UpperCAmelCase : Optional[Any]="[CLS]" , __UpperCAmelCase : Union[str, Any]="[MASK]" , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] , ) ->str: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple=None ) ->str: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
0
1
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
from ...configuration_utils import PretrainedConfig UpperCAmelCase__ = { "google/tapas-base-finetuned-sqa": ( "https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json" ), "google/tapas-base-finetuned-wtq": ( "https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json" ), "google/tapas-base-finetuned-wikisql-supervised": ( "https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json" ), "google/tapas-base-finetuned-tabfact": ( "https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json" ), } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''tapas''' def __init__( self : Union[str, Any] , __UpperCAmelCase : Optional[Any]=30_522 , __UpperCAmelCase : Optional[Any]=768 , __UpperCAmelCase : List[str]=12 , __UpperCAmelCase : Dict=12 , __UpperCAmelCase : Dict=3_072 , __UpperCAmelCase : Optional[int]="gelu" , __UpperCAmelCase : List[Any]=0.1 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : Optional[int]=1_024 , __UpperCAmelCase : List[str]=[3, 256, 256, 2, 256, 256, 10] , __UpperCAmelCase : Union[str, Any]=0.02 , __UpperCAmelCase : List[str]=1e-1_2 , __UpperCAmelCase : List[str]=0 , __UpperCAmelCase : Optional[int]=10.0 , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : Optional[int]=1.0 , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=1.0 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : List[str]=1.0 , __UpperCAmelCase : Dict=1.0 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Union[str, Any]="ratio" , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : List[Any]=None , __UpperCAmelCase : Any=64 , __UpperCAmelCase : List[Any]=32 , __UpperCAmelCase : int=False , __UpperCAmelCase : Dict=True , __UpperCAmelCase : Tuple=False , __UpperCAmelCase : Any=False , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : str=False , __UpperCAmelCase : int=None , __UpperCAmelCase : Dict=None , **__UpperCAmelCase : Union[str, Any] , ) ->Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=__UpperCAmelCase , **__UpperCAmelCase ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_sizes a = initializer_range a = layer_norm_eps # Fine-tuning task hyperparameters a = positive_label_weight a = num_aggregation_labels a = aggregation_loss_weight a = use_answer_as_supervision a = answer_loss_importance a = use_normalized_answer_loss a = huber_loss_delta a = temperature a = aggregation_temperature a = use_gumbel_for_cells a = use_gumbel_for_aggregation a = average_approximation_function a = cell_selection_preference a = answer_loss_cutoff a = max_num_rows a = max_num_columns a = average_logits_per_cell a = select_one_column a = allow_empty_column_selection a = init_cell_selection_weights_to_zero a = reset_position_index_per_cell a = disable_per_token_loss # Aggregation hyperparameters a = aggregation_labels a = no_aggregation_label_index if isinstance(self.aggregation_labels , __UpperCAmelCase ): a = {int(__UpperCAmelCase ): v for k, v in aggregation_labels.items()}
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
1
def _a ( a :int ) -> bool: if num < 0: return False a = num a = 0 while num > 0: a = rev_num * 10 + (num % 10) num //= 10 return num_copy == rev_num if __name__ == "__main__": import doctest doctest.testmod()
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
1
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {} class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''llama''' __snake_case = ['''past_key_values'''] def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]=32_000 , __UpperCAmelCase : str=4_096 , __UpperCAmelCase : int=11_008 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]="silu" , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Any=1e-6 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Tuple , ) ->str: """simple docstring""" a = vocab_size a = max_position_embeddings a = hidden_size a = intermediate_size a = num_hidden_layers a = num_attention_heads # for backward compatibility if num_key_value_heads is None: a = num_attention_heads a = num_key_value_heads a = hidden_act a = initializer_range a = rms_norm_eps a = pretraining_tp a = use_cache a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) 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}""" ) a = self.rope_scaling.get('''type''' , __UpperCAmelCase ) a = self.rope_scaling.get('''factor''' , __UpperCAmelCase ) 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(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
0
1
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "spiece.model"} UpperCAmelCase__ = { "vocab_file": { "AI-Sweden/gpt-sw3-126m": "https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-350m": "https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-1.6b": "https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-6.7b": "https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model", "AI-Sweden/gpt-sw3-20b": "https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model", } } UpperCAmelCase__ = { "AI-Sweden/gpt-sw3-126m": 2048, "AI-Sweden/gpt-sw3-350m": 2048, "AI-Sweden/gpt-sw3-1.6b": 2048, "AI-Sweden/gpt-sw3-6.7b": 2048, "AI-Sweden/gpt-sw3-20b": 2048, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''attention_mask'''] def __init__( self : List[Any] , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int]=False , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Dict=False , __UpperCAmelCase : Dict=None , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Optional[Dict[str, Any]] = None , **__UpperCAmelCase : List[Any] , ) ->None: """simple docstring""" a = {} if sp_model_kwargs is None else sp_model_kwargs a = kwargs.get('''name_or_path''' ) if name_or_path is None: logger.warning( '''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,''' ''' you are testing the model, this can safely be ignored''' ) a = '''None''' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing a = '''<|endoftext|>''' if eos_token is None else eos_token a = '''<unk>''' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: a = unk_token if pad_token is None else pad_token a = eos_token if bos_token is None else bos_token else: a = '''<pad>''' if pad_token is None else pad_token a = '''<s>''' if bos_token is None else bos_token super().__init__( do_lower_case=__UpperCAmelCase , remove_space=__UpperCAmelCase , keep_accents=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , ) a = do_lower_case a = remove_space a = keep_accents a = vocab_file a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) # Used for whitespace normalization in input texts # fmt : off a = {''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', ''' ''', '''''', '''„'''} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing a = re.compile( F"""[{''.join(map(__UpperCAmelCase , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8_203] ) )}]""" ) def __getstate__( self : int ) ->Any: """simple docstring""" a = self.__dict__.copy() a = None return state def __setstate__( self : int , __UpperCAmelCase : List[Any] ) ->Optional[int]: """simple docstring""" a = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a = {} a = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __lowerCAmelCase ( self : Optional[Any] ) ->int: """simple docstring""" return len(self.sp_model ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : str ) ->str: """simple docstring""" a = self.non_printing_characters_re.sub('''''' , __UpperCAmelCase ) # Normalize whitespaces a = ''''''.join([char if char not in self.whitespaces else ''' ''' for char in text] ) # NFC Unicode normalization a = unicodedata.normalize('''NFC''' , __UpperCAmelCase ) return text def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : str , **__UpperCAmelCase : Tuple ) ->List[str]: """simple docstring""" a = self.preprocess_text(__UpperCAmelCase ) return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : str ) ->int: """simple docstring""" return self.sp_model.PieceToId(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : int ) ->str: """simple docstring""" return self.sp_model.IdToPiece(__UpperCAmelCase ) @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : str ) ->str: """simple docstring""" return out_string def __lowerCAmelCase ( self : str , __UpperCAmelCase : List[str] ) ->str: """simple docstring""" a = [] a = '''''' a = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__UpperCAmelCase ) + token a = True a = [] else: current_sub_tokens.append(__UpperCAmelCase ) a = False out_string += self.sp_model.decode(__UpperCAmelCase ) return out_string def __lowerCAmelCase ( self : List[str] ) ->Dict[str, int]: """simple docstring""" a = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a = os.path.join( __UpperCAmelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase , '''wb''' ) as fi: a = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def __lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Union[str, List[str]] , __UpperCAmelCase : Union[str, bool] = False ) ->Union[List[int], List[List[int]], "torch.Tensor"]: """simple docstring""" if isinstance(__UpperCAmelCase , __UpperCAmelCase ): a = self.preprocess_text(__UpperCAmelCase ) a = self.sp_model.encode(__UpperCAmelCase ) else: a = [self.preprocess_text(__UpperCAmelCase ) for t in text] a = self.sp_model.encode(__UpperCAmelCase ) if return_tensors is True or return_tensors == "pt": a = torch.tensor(__UpperCAmelCase ) return token_ids def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Union[int, List[int]] ) ->str: """simple docstring""" return self.sp_model.decode(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : "Conversation" ) ->List[int]: """simple docstring""" a = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] a = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(__UpperCAmelCase ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=__UpperCAmelCase )
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
class lowercase_ : '''simple docstring''' def __init__( self : Dict ) ->List[str]: """simple docstring""" a = {} def __lowerCAmelCase ( self : str ) ->None: """simple docstring""" print(self.vertex ) for i in self.vertex: print(__UpperCAmelCase , ''' -> ''' , ''' -> '''.join([str(__UpperCAmelCase ) for j in self.vertex[i]] ) ) def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : int ) ->None: """simple docstring""" if from_vertex in self.vertex: self.vertex[from_vertex].append(__UpperCAmelCase ) else: # else make a new vertex a = [to_vertex] def __lowerCAmelCase ( self : Optional[Any] ) ->None: """simple docstring""" a = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : int , __UpperCAmelCase : list ) ->None: """simple docstring""" a = True print(__UpperCAmelCase , end=''' ''' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(__UpperCAmelCase , __UpperCAmelCase ) if __name__ == "__main__": UpperCAmelCase__ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("DFS:") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor UpperCAmelCase__ = logging.get_logger(__name__) class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Optional[int] , *__UpperCAmelCase : Union[str, Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" warnings.warn( '''The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use PerceiverImageProcessor instead.''' , __UpperCAmelCase , ) super().__init__(*__UpperCAmelCase , **__UpperCAmelCase )
0
import math def _a ( a :int ) -> list: a = [True] * n a = False a = False a = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a = i * 2 while index < n: a = False a = index + i a = [2] for i in range(3 , a , 2 ): if is_prime[i]: primes.append(a ) return primes def _a ( a :int = 999_966_663_333 ) -> int: a = math.floor(math.sqrt(a ) ) + 100 a = prime_sieve(a ) a = 0 a = 0 a = primes[prime_index] while (last_prime**2) <= limit: a = primes[prime_index + 1] a = last_prime**2 a = next_prime**2 # Get numbers divisible by lps(current) a = 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) a = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a = 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 a = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
0
1
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, ) if is_sentencepiece_available(): from ..ta.tokenization_ta import TaTokenizer else: from ...utils.dummy_sentencepiece_objects import TaTokenizer UpperCAmelCase__ = TaTokenizer if is_tokenizers_available(): from ..ta.tokenization_ta_fast import TaTokenizerFast else: from ...utils.dummy_tokenizers_objects import TaTokenizerFast UpperCAmelCase__ = TaTokenizerFast UpperCAmelCase__ = {"configuration_mt5": ["MT5Config", "MT5OnnxConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "MT5EncoderModel", "MT5ForConditionalGeneration", "MT5ForQuestionAnswering", "MT5Model", "MT5PreTrainedModel", "MT5Stack", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["TFMT5EncoderModel", "TFMT5ForConditionalGeneration", "TFMT5Model"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ["FlaxMT5EncoderModel", "FlaxMT5ForConditionalGeneration", "FlaxMT5Model"] if TYPE_CHECKING: from .configuration_mta import MTaConfig, MTaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mta import ( MTaEncoderModel, MTaForConditionalGeneration, MTaForQuestionAnswering, MTaModel, MTaPreTrainedModel, MTaStack, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mta import TFMTaEncoderModel, TFMTaForConditionalGeneration, TFMTaModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mta import FlaxMTaEncoderModel, FlaxMTaForConditionalGeneration, FlaxMTaModel else: import sys UpperCAmelCase__ = _LazyModule( __name__, globals()["__file__"], _import_structure, extra_objects={"MT5Tokenizer": MTaTokenizer, "MT5TokenizerFast": MTaTokenizerFast}, module_spec=__spec__, )
0
def _a ( a :float , a :float ) -> float: return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
0
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _a ( *a :Optional[Any] , a :Optional[Union[Dict, Any]] = None , a :List[str]=True , a :List[str]=2 ) -> int: from .. import __version__ a = take_from a = () if not isinstance(args[0] , a ): a = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a ).base_version ) >= version.parse(a ): raise ValueError( F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" F""" version {__version__} is >= {version_name}""" ) a = None if isinstance(a , a ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a ),) a = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(a , a ): values += (getattr(a , a ),) a = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: a = F"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: a = warning + ''' ''' if standard_warn else '''''' warnings.warn(warning + message , a , stacklevel=a ) if isinstance(a , a ) and len(a ) > 0: a = inspect.getouterframes(inspect.currentframe() )[1] a = call_frame.filename a = call_frame.lineno a = call_frame.function a , a = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(a ) == 0: return elif len(a ) == 1: return values[0] return values
0
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 lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" a = SMALL_MODEL_IDENTIFIER a = '''pt''' a = '''tf''' def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str ) ->Union[str, Any]: """simple docstring""" a = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[str, Any] ) ->List[str]: """simple docstring""" a = TFAutoModel.from_pretrained(self.test_model , from_pt=__UpperCAmelCase ) model_tf.save_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = '''mock_framework''' # Framework provided - return whatever the user provides a = FeaturesManager.determine_framework(self.test_model , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : str ) ->int: """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__UpperCAmelCase ) a = FeaturesManager.determine_framework(__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__UpperCAmelCase , self.framework_pt ) # Both not in environment -> raise error a = MagicMock(return_value=__UpperCAmelCase ) a = MagicMock(return_value=__UpperCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __UpperCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __UpperCAmelCase ): with self.assertRaises(__UpperCAmelCase ): a = FeaturesManager.determine_framework(self.test_model )
0
1
import gc import unittest from transformers import CTRLConfig, 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 ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class lowercase_ : '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Union[str, Any]=14 , __UpperCAmelCase : Any=7 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : int=99 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : int=5 , __UpperCAmelCase : str=4 , __UpperCAmelCase : Optional[int]=37 , __UpperCAmelCase : Tuple="gelu" , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : Tuple=0.1 , __UpperCAmelCase : str=512 , __UpperCAmelCase : int=16 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : Any=0.02 , __UpperCAmelCase : Tuple=3 , __UpperCAmelCase : Tuple=4 , __UpperCAmelCase : Optional[int]=None , ) ->Union[str, Any]: """simple docstring""" a = parent a = batch_size a = seq_length a = is_training a = use_token_type_ids a = use_input_mask a = use_labels a = use_mc_token_ids a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_labels a = num_choices a = scope a = self.vocab_size - 1 def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_input_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = None if self.use_mc_token_ids: a = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) a = None a = None a = None if self.use_labels: a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a = ids_tensor([self.batch_size] , self.num_choices ) a = self.get_config() a = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def __lowerCAmelCase ( self : Tuple ) ->Union[str, Any]: """simple docstring""" return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , __UpperCAmelCase : List[str] , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] , *__UpperCAmelCase : List[str] ) ->Union[str, Any]: """simple docstring""" a = CTRLModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase , head_mask=__UpperCAmelCase ) model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase ) a = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : Dict , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : List[str] , __UpperCAmelCase : List[str] , *__UpperCAmelCase : Tuple ) ->Optional[int]: """simple docstring""" a = CTRLLMHeadModel(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" a = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) = config_and_inputs a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask} return config, inputs_dict def __lowerCAmelCase ( self : Any , __UpperCAmelCase : int , __UpperCAmelCase : Any , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : Any , *__UpperCAmelCase : Dict ) ->Optional[int]: """simple docstring""" a = self.num_labels a = CTRLForSequenceClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a = model(__UpperCAmelCase , token_type_ids=__UpperCAmelCase , labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class lowercase_ ( lowercase , lowercase , lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () __snake_case = (CTRLLMHeadModel,) if is_torch_available() else () __snake_case = ( { '''feature-extraction''': CTRLModel, '''text-classification''': CTRLForSequenceClassification, '''text-generation''': CTRLLMHeadModel, '''zero-shot''': CTRLForSequenceClassification, } if is_torch_available() else {} ) __snake_case = True __snake_case = False __snake_case = False def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any] ) ->Any: """simple docstring""" if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CTRLModelTester(self ) a = ConfigTester(self , config_class=__UpperCAmelCase , n_embd=37 ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__UpperCAmelCase ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" pass @slow def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a = CTRLModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" pass @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def __lowerCAmelCase ( self : str ) ->Union[str, Any]: """simple docstring""" a = CTRLLMHeadModel.from_pretrained('''ctrl''' ) model.to(__UpperCAmelCase ) a = torch.tensor( [[11_859, 0, 1_611, 8]] , dtype=torch.long , device=__UpperCAmelCase ) # Legal the president is a = [ 11_859, 0, 1_611, 8, 5, 150, 26_449, 2, 19, 348, 469, 3, 2_595, 48, 20_740, 246_533, 246_533, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a a = model.generate(__UpperCAmelCase , do_sample=__UpperCAmelCase ) self.assertListEqual(output_ids[0].tolist() , __UpperCAmelCase )
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ProphetNetTokenizer __snake_case = False def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str ) ->Dict: """simple docstring""" a = '''UNwant\u00E9d,running''' a = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__UpperCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [9, 6, 7, 12, 10, 11] ) def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" a = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Any ) ->Dict: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , strip_accents=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = BasicTokenizer(do_lower_case=__UpperCAmelCase , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , 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 __lowerCAmelCase ( self : int ) ->int: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a = [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102] a = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : Any ) ->List[str]: """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 __lowerCAmelCase ( self : List[Any] ) ->List[str]: """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 __lowerCAmelCase ( self : List[str] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a = tokenizer.encode('''sequence builders''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
0
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "vocab_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/vocab.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/vocab.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/vocab.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/vocab.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/vocab.json", }, "merges_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/merges.txt", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/merges.txt", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/merges.txt", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/merges.txt", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/merges.txt", }, "tokenizer_file": { "gpt2": "https://huggingface.co/gpt2/resolve/main/tokenizer.json", "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json", "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/tokenizer.json", "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json", "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/tokenizer.json", }, } UpperCAmelCase__ = { "gpt2": 1024, "gpt2-medium": 1024, "gpt2-large": 1024, "gpt2-xl": 1024, "distilgpt2": 1024, } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ['''input_ids''', '''attention_mask'''] __snake_case = GPTaTokenizer def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=None , __UpperCAmelCase : int=None , __UpperCAmelCase : Dict=None , __UpperCAmelCase : List[Any]="<|endoftext|>" , __UpperCAmelCase : Optional[Any]="<|endoftext|>" , __UpperCAmelCase : Optional[int]="<|endoftext|>" , __UpperCAmelCase : List[Any]=False , **__UpperCAmelCase : Optional[Any] , ) ->List[str]: """simple docstring""" super().__init__( __UpperCAmelCase , __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , unk_token=__UpperCAmelCase , bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , add_prefix_space=__UpperCAmelCase , **__UpperCAmelCase , ) a = kwargs.pop('''add_bos_token''' , __UpperCAmelCase ) a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , __UpperCAmelCase ) != add_prefix_space: a = getattr(__UpperCAmelCase , pre_tok_state.pop('''type''' ) ) a = add_prefix_space a = pre_tok_class(**__UpperCAmelCase ) a = add_prefix_space def __lowerCAmelCase ( self : Dict , *__UpperCAmelCase : Optional[int] , **__UpperCAmelCase : Dict ) ->BatchEncoding: """simple docstring""" a = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : int , *__UpperCAmelCase : Any , **__UpperCAmelCase : Any ) ->BatchEncoding: """simple docstring""" a = kwargs.get('''is_split_into_words''' , __UpperCAmelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : "Conversation" ) ->List[int]: """simple docstring""" a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) + [self.eos_token_id] ) if len(__UpperCAmelCase ) > self.model_max_length: a = input_ids[-self.model_max_length :] return input_ids
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "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 UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "facebook/timesformer": "https://huggingface.co/facebook/timesformer/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''timesformer''' def __init__( self : Optional[int] , __UpperCAmelCase : int=224 , __UpperCAmelCase : Tuple=16 , __UpperCAmelCase : List[str]=3 , __UpperCAmelCase : Union[str, Any]=8 , __UpperCAmelCase : List[str]=768 , __UpperCAmelCase : List[Any]=12 , __UpperCAmelCase : Optional[Any]=12 , __UpperCAmelCase : Union[str, Any]=3_072 , __UpperCAmelCase : int="gelu" , __UpperCAmelCase : Dict=0.0 , __UpperCAmelCase : str=0.0 , __UpperCAmelCase : Any=0.02 , __UpperCAmelCase : List[str]=1e-6 , __UpperCAmelCase : int=True , __UpperCAmelCase : Tuple="divided_space_time" , __UpperCAmelCase : Any=0 , **__UpperCAmelCase : List[str] , ) ->str: """simple docstring""" super().__init__(**__UpperCAmelCase ) a = image_size a = patch_size a = num_channels a = num_frames a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = initializer_range a = layer_norm_eps a = qkv_bias a = attention_type a = drop_path_rate
0
def _a ( a :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 a = gray_code_sequence_string(a ) # # convert them to integers for i in range(len(a ) ): a = int(sequence[i] , 2 ) return sequence def _a ( a :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"] a = 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 a = gray_code_sequence_string(bit_count - 1 ) a = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): a = '''0''' + smaller_sequence[i] sequence.append(a ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): a = '''1''' + smaller_sequence[i] sequence.append(a ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
0
1
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py UpperCAmelCase__ = "." if __name__ == "__main__": UpperCAmelCase__ = os.path.join(REPO_PATH, "utils/documentation_tests.txt") UpperCAmelCase__ = [] UpperCAmelCase__ = [] with open(doctest_file_path) as fp: for line in fp: UpperCAmelCase__ = line.strip() UpperCAmelCase__ = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: UpperCAmelCase__ = "\n".join(non_existent_paths) raise ValueError(f"""`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}""") if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
0
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 lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() # fmt: off a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on a = 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] ) ) a = { '''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], } a = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , **__UpperCAmelCase : List[Any] ) ->int: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **__UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : str ) ->Dict: """simple docstring""" a = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] a = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" a = self.get_tokenizer() a = self.get_image_processor() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor.save_pretrained(self.tmpdirname ) a = 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" a = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) a = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) a = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) a = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__UpperCAmelCase , 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 , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = self.prepare_image_inputs() a = image_processor(__UpperCAmelCase , return_tensors='''np''' ) a = processor(images=__UpperCAmelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : List[str] ) ->str: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = processor(text=__UpperCAmelCase ) a = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(__UpperCAmelCase ): processor() def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] a = processor.batch_decode(__UpperCAmelCase ) a = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.get_image_processor() a = self.get_tokenizer() a = VisionTextDualEncoderProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) a = '''lower newer''' a = self.prepare_image_inputs() a = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
0
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :int , a :Dict=False ) -> Optional[Any]: a = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('''head''' ): a = '''segformer.encoder.''' + key if key.startswith('''backbone''' ): a = key.replace('''backbone''' , '''segformer.encoder''' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 a = key[key.find('''patch_embed''' ) + len('''patch_embed''' )] a = key.replace(F"""patch_embed{idx}""" , F"""patch_embeddings.{int(a )-1}""" ) if "norm" in key: a = key.replace('''norm''' , '''layer_norm''' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 a = key[key.find('''segformer.encoder.layer_norm''' ) + len('''segformer.encoder.layer_norm''' )] a = key.replace(F"""layer_norm{idx}""" , F"""layer_norm.{int(a )-1}""" ) if "layer_norm1" in key: a = key.replace('''layer_norm1''' , '''layer_norm_1''' ) if "layer_norm2" in key: a = key.replace('''layer_norm2''' , '''layer_norm_2''' ) if "block" in key: # replace for example block1 by block.0 a = key[key.find('''block''' ) + len('''block''' )] a = key.replace(F"""block{idx}""" , F"""block.{int(a )-1}""" ) if "attn.q" in key: a = key.replace('''attn.q''' , '''attention.self.query''' ) if "attn.proj" in key: a = key.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in key: a = key.replace('''attn''' , '''attention.self''' ) if "fc1" in key: a = key.replace('''fc1''' , '''dense1''' ) if "fc2" in key: a = key.replace('''fc2''' , '''dense2''' ) if "linear_pred" in key: a = key.replace('''linear_pred''' , '''classifier''' ) if "linear_fuse" in key: a = key.replace('''linear_fuse.conv''' , '''linear_fuse''' ) a = key.replace('''linear_fuse.bn''' , '''batch_norm''' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 a = key[key.find('''linear_c''' ) + len('''linear_c''' )] a = key.replace(F"""linear_c{idx}""" , F"""linear_c.{int(a )-1}""" ) if key.startswith('''head''' ): a = key.replace('''head''' , '''classifier''' ) a = value return new_state_dict def _a ( a :List[str] , a :Union[str, Any] ) -> Tuple: # 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) a = state_dict.pop(F"""segformer.encoder.block.{i}.{j}.attention.self.kv.weight""" ) a = state_dict.pop(F"""segformer.encoder.block.{i}.{j}.attention.self.kv.bias""" ) # next, add keys and values (in that order) to the state dict a = kv_weight[ : config.hidden_sizes[i], : ] a = kv_bias[: config.hidden_sizes[i]] a = kv_weight[ config.hidden_sizes[i] :, : ] a = kv_bias[ config.hidden_sizes[i] : ] def _a ( ) -> Optional[Any]: a = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a = Image.open(requests.get(a , stream=a ).raw ) return image @torch.no_grad() def _a ( a :Tuple , a :Any , a :int ) -> Any: a = SegformerConfig() a = False # set attributes based on model_name a = '''huggingface/label-files''' if "segformer" in model_name: a = model_name[len('''segformer.''' ) : len('''segformer.''' ) + 2] if "ade" in model_name: a = 150 a = '''ade20k-id2label.json''' a = (1, 150, 128, 128) elif "city" in model_name: a = 19 a = '''cityscapes-id2label.json''' a = (1, 19, 128, 128) else: raise ValueError(F"""Model {model_name} not supported""" ) elif "mit" in model_name: a = True a = model_name[4:6] a = 1_000 a = '''imagenet-1k-id2label.json''' a = (1, 1_000) else: raise ValueError(F"""Model {model_name} not supported""" ) # set config attributes a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": a = [64, 128, 320, 512] a = 256 elif size == "b2": a = [64, 128, 320, 512] a = 768 a = [3, 4, 6, 3] elif size == "b3": a = [64, 128, 320, 512] a = 768 a = [3, 4, 18, 3] elif size == "b4": a = [64, 128, 320, 512] a = 768 a = [3, 8, 27, 3] elif size == "b5": a = [64, 128, 320, 512] a = 768 a = [3, 6, 40, 3] else: raise ValueError(F"""Size {size} not supported""" ) # load image processor (only resize + normalize) a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=a , align=a , do_random_crop=a ) # prepare image a = prepare_img() a = image_processor(images=a , return_tensors='''pt''' ).pixel_values logger.info(F"""Converting model {model_name}...""" ) # load original state dict if encoder_only: a = torch.load(a , map_location=torch.device('''cpu''' ) ) else: a = torch.load(a , map_location=torch.device('''cpu''' ) )['''state_dict'''] # rename keys a = rename_keys(a , encoder_only=a ) 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(a , a ) # create HuggingFace model and load state dict if encoder_only: a = False a = SegformerForImageClassification(a ) else: a = SegformerForSemanticSegmentation(a ) model.load_state_dict(a ) model.eval() # forward pass a = model(a ) a = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": a = torch.tensor( [ [[-4.6_310, -5.5_232, -6.2_356], [-5.1_921, -6.1_444, -6.5_996], [-5.4_424, -6.2_790, -6.7_574]], [[-12.1_391, -13.3_122, -13.9_554], [-12.8_732, -13.9_352, -14.3_563], [-12.9_438, -13.8_226, -14.2_513]], [[-12.5_134, -13.4_686, -14.4_915], [-12.8_669, -14.4_343, -14.7_758], [-13.2_523, -14.5_819, -15.0_694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": a = torch.tensor( [ [[-7.5_820, -8.7_231, -8.3_215], [-8.0_600, -10.3_529, -10.0_304], [-7.5_208, -9.4_103, -9.6_239]], [[-12.6_918, -13.8_994, -13.7_137], [-13.3_196, -15.7_523, -15.4_789], [-12.9_343, -14.8_757, -14.9_689]], [[-11.1_911, -11.9_421, -11.3_243], [-11.3_342, -13.6_839, -13.3_581], [-10.3_909, -12.1_832, -12.4_858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": a = torch.tensor( [ [[-11.8_173, -14.3_850, -16.3_128], [-14.5_648, -16.5_804, -18.6_568], [-14.7_223, -15.7_387, -18.4_218]], [[-15.7_290, -17.9_171, -19.4_423], [-18.3_105, -19.9_448, -21.4_661], [-17.9_296, -18.6_497, -20.7_910]], [[-15.0_783, -17.0_336, -18.2_789], [-16.8_771, -18.6_870, -20.1_612], [-16.2_454, -17.1_426, -19.5_055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": a = torch.tensor( [ [[-9.0_878, -10.2_081, -10.1_891], [-9.3_144, -10.7_941, -10.9_843], [-9.2_294, -10.3_855, -10.5_704]], [[-12.2_316, -13.9_068, -13.6_102], [-12.9_161, -14.3_702, -14.3_235], [-12.5_233, -13.7_174, -13.7_932]], [[-14.6_275, -15.2_490, -14.9_727], [-14.3_400, -15.9_687, -16.2_827], [-14.1_484, -15.4_033, -15.8_937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": a = torch.tensor( [ [[-12.3_144, -13.2_447, -14.0_802], [-13.3_614, -14.5_816, -15.6_117], [-13.3_340, -14.4_433, -16.2_219]], [[-19.2_781, -20.4_128, -20.7_506], [-20.6_153, -21.6_566, -22.0_998], [-19.9_800, -21.0_430, -22.1_494]], [[-18.8_739, -19.7_804, -21.1_834], [-20.1_233, -21.6_765, -23.2_944], [-20.0_315, -21.2_641, -23.6_944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": a = torch.tensor( [ [[-9.5_524, -12.0_835, -11.7_348], [-10.5_229, -13.6_446, -14.5_662], [-9.5_842, -12.8_851, -13.9_414]], [[-15.3_432, -17.5_323, -17.0_818], [-16.3_330, -18.9_255, -19.2_101], [-15.1_340, -17.7_848, -18.3_971]], [[-12.6_072, -14.9_486, -14.6_631], [-13.7_629, -17.0_907, -17.7_745], [-12.7_899, -16.1_695, -17.1_671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": a = torch.tensor( [ [[-11.9_295, -13.4_057, -14.8_106], [-13.3_431, -14.8_179, -15.3_781], [-14.2_836, -15.5_942, -16.1_588]], [[-11.4_906, -12.8_067, -13.6_564], [-13.1_189, -14.0_500, -14.1_543], [-13.8_748, -14.5_136, -14.8_789]], [[0.5_374, 0.1_067, -0.4_742], [0.1_141, -0.2_255, -0.7_099], [-0.3_000, -0.5_924, -1.3_105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": a = torch.tensor( [ [[-7.8_217, -9.8_767, -10.1_717], [-9.4_438, -10.9_058, -11.4_047], [-9.7_939, -12.3_495, -12.1_079]], [[-7.1_514, -9.5_336, -10.0_860], [-9.7_776, -11.6_822, -11.8_439], [-10.1_411, -12.7_655, -12.8_972]], [[0.3_021, 0.0_805, -0.2_310], [-0.0_328, -0.1_605, -0.2_714], [-0.1_408, -0.5_477, -0.6_976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": a = 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": a = torch.tensor( [ [[-9.4_959, -11.3_087, -11.7_479], [-11.0_025, -12.6_540, -12.3_319], [-11.4_064, -13.0_487, -12.9_905]], [[-9.8_905, -11.3_084, -12.0_854], [-11.1_726, -12.7_698, -12.9_583], [-11.5_985, -13.3_278, -14.1_774]], [[0.2_213, 0.0_192, -0.2_466], [-0.1_731, -0.4_213, -0.4_874], [-0.3_126, -0.6_541, -1.1_389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": a = torch.tensor( [ [[-13.5_748, -13.9_111, -12.6_500], [-14.3_500, -15.3_683, -14.2_328], [-14.7_532, -16.0_424, -15.6_087]], [[-17.1_651, -15.8_725, -12.9_653], [-17.2_580, -17.3_718, -14.8_223], [-16.6_058, -16.8_783, -16.7_452]], [[-3.6_456, -3.0_209, -1.4_203], [-3.0_797, -3.1_959, -2.0_000], [-1.8_757, -1.9_217, -1.6_997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": a = torch.tensor( [ [[-16.0_976, -16.4_856, -17.3_962], [-16.6_234, -19.0_342, -19.7_685], [-16.0_900, -18.0_661, -19.1_180]], [[-18.4_750, -18.8_488, -19.5_074], [-19.4_030, -22.1_570, -22.5_977], [-19.1_191, -20.8_486, -22.3_783]], [[-4.5_178, -5.5_037, -6.5_109], [-5.0_884, -7.2_174, -8.0_334], [-4.4_156, -5.8_117, -7.2_970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": a = torch.tensor( [ [[-14.2_081, -14.4_732, -14.1_977], [-14.5_867, -16.4_423, -16.6_356], [-13.4_441, -14.9_685, -16.8_696]], [[-14.4_576, -14.7_073, -15.0_451], [-15.0_816, -17.6_237, -17.9_873], [-14.4_213, -16.0_199, -18.5_992]], [[-4.7_349, -4.9_588, -5.0_966], [-4.3_210, -6.9_325, -7.2_591], [-3.4_312, -4.7_484, -7.1_917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": a = torch.tensor( [ [[-11.7_737, -11.9_526, -11.3_273], [-13.6_692, -14.4_574, -13.8_878], [-13.8_937, -14.6_924, -15.9_345]], [[-14.6_706, -14.5_330, -14.1_306], [-16.1_502, -16.8_180, -16.4_269], [-16.8_338, -17.8_939, -20.1_746]], [[1.0_491, 0.8_289, 1.0_310], [1.1_044, 0.5_219, 0.8_055], [1.0_899, 0.6_926, 0.5_590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": a = torch.tensor( [ [[-12.5_641, -13.4_777, -13.0_684], [-13.9_587, -15.8_983, -16.6_557], [-13.3_109, -15.7_350, -16.3_141]], [[-14.7_074, -15.4_352, -14.5_944], [-16.6_353, -18.1_663, -18.6_120], [-15.1_702, -18.0_329, -18.1_547]], [[-1.7_990, -2.0_951, -1.7_784], [-2.6_397, -3.8_245, -3.9_686], [-1.5_264, -2.8_126, -2.9_316]], ] ) else: a = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , a , atol=1e-2 ) # finally, save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--model_name", default="segformer.b0.512x512.ade.160k", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) UpperCAmelCase__ = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
0
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 ( a :List[Any] ) -> Optional[int]: a = [] 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 ( a :List[Any] , a :Optional[int] ) -> Dict: a = [] 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 ( a :Any ) -> List[Any]: a = [] token.append((F"""cvt.encoder.stages.{idx}.cls_token""", '''stage2.cls_token''') ) return token def _a ( ) -> Optional[int]: a = [] 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 ( a :Tuple , a :Optional[int] , a :List[Any] , a :Union[str, Any] ) -> Optional[int]: a = '''imagenet-1k-id2label.json''' a = 1_000 a = '''huggingface/label-files''' a = num_labels a = json.load(open(cached_download(hf_hub_url(a , a , repo_type='''dataset''' ) ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = idalabel a = {v: k for k, v in idalabel.items()} a = a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": a = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": a = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: a = [2, 2, 20] a = [3, 12, 16] a = [192, 768, 1_024] a = CvtForImageClassification(a ) a = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) a = image_size a = torch.load(a , map_location=torch.device('''cpu''' ) ) a = OrderedDict() a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: a = list_of_state_dict + cls_token(a ) a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): a = list_of_state_dict + attention(a , a ) a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=R"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) UpperCAmelCase__ = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
0
1
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
from __future__ import annotations UpperCAmelCase__ = list[list[int]] # assigning initial values to the grid UpperCAmelCase__ = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution UpperCAmelCase__ = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( a :Matrix , a :int , a :int , a :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 ( a :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 ( a :Matrix ) -> Matrix | None: if location := find_empty_location(a ): a , a = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(a , a , a , a ): a = digit if sudoku(a ) is not None: return grid a = 0 return None def _a ( a :Matrix ) -> None: for row in grid: for cell in row: print(a , end=''' ''' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") UpperCAmelCase__ = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
0
1
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = (PNDMScheduler,) __snake_case = (('''num_inference_steps''', 50),) def __lowerCAmelCase ( self : int , **__UpperCAmelCase : Optional[int] ) ->int: """simple docstring""" a = { '''num_train_timesteps''': 1_000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**__UpperCAmelCase ) return config def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[str]=0 , **__UpperCAmelCase : Tuple ) ->Tuple: """simple docstring""" a = dict(self.forward_default_kwargs ) a = kwargs.pop('''num_inference_steps''' , __UpperCAmelCase ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config(**__UpperCAmelCase ) a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals a = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__UpperCAmelCase ) a = scheduler_class.from_pretrained(__UpperCAmelCase ) new_scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals a = dummy_past_residuals[:] a = scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = new_scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" a = scheduler.step_plms(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = new_scheduler.step_plms(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" pass def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : List[str]=0 , **__UpperCAmelCase : Optional[Any] ) ->Tuple: """simple docstring""" a = dict(self.forward_default_kwargs ) a = kwargs.pop('''num_inference_steps''' , __UpperCAmelCase ) a = self.dummy_sample a = 0.1 * sample a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residuals (must be after setting timesteps) a = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__UpperCAmelCase ) a = scheduler_class.from_pretrained(__UpperCAmelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(__UpperCAmelCase ) # copy over dummy past residual (must be after setting timesteps) a = dummy_past_residuals[:] a = scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = new_scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" a = scheduler.step_plms(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = new_scheduler.step_plms(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def __lowerCAmelCase ( self : int , **__UpperCAmelCase : Optional[int] ) ->str: """simple docstring""" a = self.scheduler_classes[0] a = self.get_scheduler_config(**__UpperCAmelCase ) a = scheduler_class(**__UpperCAmelCase ) a = 10 a = self.dummy_model() a = self.dummy_sample_deter scheduler.set_timesteps(__UpperCAmelCase ) for i, t in enumerate(scheduler.prk_timesteps ): a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): a = model(__UpperCAmelCase , __UpperCAmelCase ) a = scheduler.step_plms(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample return sample def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" a = dict(self.forward_default_kwargs ) a = kwargs.pop('''num_inference_steps''' , __UpperCAmelCase ) for scheduler_class in self.scheduler_classes: a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) a = self.dummy_sample a = 0.1 * sample if num_inference_steps is not None and hasattr(__UpperCAmelCase , '''set_timesteps''' ): scheduler.set_timesteps(__UpperCAmelCase ) elif num_inference_steps is not None and not hasattr(__UpperCAmelCase , '''set_timesteps''' ): a = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) a = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] a = dummy_past_residuals[:] a = scheduler.step_prk(__UpperCAmelCase , 0 , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = scheduler.step_prk(__UpperCAmelCase , 1 , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) a = scheduler.step_plms(__UpperCAmelCase , 0 , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample a = scheduler.step_plms(__UpperCAmelCase , 1 , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def __lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" for timesteps in [100, 1_000]: self.check_over_configs(num_train_timesteps=__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->int: """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__UpperCAmelCase ) a = self.scheduler_classes[0] a = self.get_scheduler_config(steps_offset=1 ) a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def __lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" for beta_start, beta_end in zip([0.0001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=__UpperCAmelCase , beta_end=__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->Dict: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" for t in [1, 5, 10]: self.check_over_forward(time_step=__UpperCAmelCase ) def __lowerCAmelCase ( self : int ) ->Union[str, Any]: """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = 27 for scheduler_class in self.scheduler_classes: a = self.dummy_sample a = 0.1 * sample a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) scheduler.set_timesteps(__UpperCAmelCase ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): a = scheduler.step_prk(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ).prev_sample def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[int]: """simple docstring""" with self.assertRaises(__UpperCAmelCase ): a = self.scheduler_classes[0] a = self.get_scheduler_config() a = scheduler_class(**__UpperCAmelCase ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def __lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" a = self.full_loop() a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 198.1318 ) < 1e-2 assert abs(result_mean.item() - 0.2580 ) < 1e-3 def __lowerCAmelCase ( self : Dict ) ->str: """simple docstring""" a = self.full_loop(prediction_type='''v_prediction''' ) a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 67.3986 ) < 1e-2 assert abs(result_mean.item() - 0.0878 ) < 1e-3 def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = self.full_loop(set_alpha_to_one=__UpperCAmelCase , beta_start=0.01 ) a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 230.0399 ) < 1e-2 assert abs(result_mean.item() - 0.2995 ) < 1e-3 def __lowerCAmelCase ( self : Optional[int] ) ->Any: """simple docstring""" a = self.full_loop(set_alpha_to_one=__UpperCAmelCase , beta_start=0.01 ) a = torch.sum(torch.abs(__UpperCAmelCase ) ) a = torch.mean(torch.abs(__UpperCAmelCase ) ) assert abs(result_sum.item() - 186.9482 ) < 1e-2 assert abs(result_mean.item() - 0.2434 ) < 1e-3
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaPriorPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt''', '''negative_prompt'''] __snake_case = [ '''num_images_per_prompt''', '''generator''', '''num_inference_steps''', '''latents''', '''negative_prompt''', '''guidance_scale''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Optional[Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" return self.time_input_dim @property def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" return 100 @property def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''num_attention_heads''': 2, '''attention_head_dim''': 12, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a = PriorTransformer(**__UpperCAmelCase ) # 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 a = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : Optional[int] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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 , ) a = CLIPVisionModelWithProjection(__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" a = CLIPImageProcessor( crop_size=224 , do_center_crop=__UpperCAmelCase , do_normalize=__UpperCAmelCase , do_resize=__UpperCAmelCase , image_mean=[0.48145466, 0.4578275, 0.40821073] , image_std=[0.26862954, 0.26130258, 0.27577711] , resample=3 , size=224 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = self.dummy_prior a = self.dummy_image_encoder a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_image_processor a = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_000 , clip_sample=__UpperCAmelCase , clip_sample_range=10.0 , ) a = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : str=0 ) ->int: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.image_embeds a = pipe( **self.get_dummy_inputs(__UpperCAmelCase ) , return_dict=__UpperCAmelCase , )[0] a = image[0, -10:] a = image_from_tuple[0, -10:] assert image.shape == (1, 32) a = np.array( [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] ) 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 __lowerCAmelCase ( self : List[Any] ) ->Optional[Any]: """simple docstring""" a = torch_device == '''cpu''' a = True a = False self._test_inference_batch_single_identical( test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , ) @skip_mps def __lowerCAmelCase ( self : List[str] ) ->Union[str, Any]: """simple docstring""" a = torch_device == '''cpu''' a = False self._test_attention_slicing_forward_pass( test_max_difference=__UpperCAmelCase , test_mean_pixel_difference=__UpperCAmelCase , )
0
1
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. UpperCAmelCase__ = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class lowercase_ ( unittest.TestCase ): '''simple docstring''' __snake_case = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __snake_case = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __snake_case = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __snake_case = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def __lowerCAmelCase ( self : int , __UpperCAmelCase : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] ) ->Optional[int]: """simple docstring""" a = ZeroShotClassificationPipeline( model=__UpperCAmelCase , tokenizer=__UpperCAmelCase , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] ) ->int: """simple docstring""" a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(__UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase )]} ) # No kwarg a = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(__UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase )]} ) a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(__UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase )]} ) a = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( __UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) a = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( __UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) a = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(__UpperCAmelCase , {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase )]} ) # https://github.com/huggingface/transformers/issues/13846 a = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( __UpperCAmelCase , [ {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )]} for i in range(1 ) ] , ) a = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( __UpperCAmelCase , [ {'''sequence''': ANY(__UpperCAmelCase ), '''labels''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )], '''scores''': [ANY(__UpperCAmelCase ), ANY(__UpperCAmelCase )]} for i in range(2 ) ] , ) with self.assertRaises(__UpperCAmelCase ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(__UpperCAmelCase ): classifier(__UpperCAmelCase , candidate_labels='''politics''' ) with self.assertRaises(__UpperCAmelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(__UpperCAmelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels=__UpperCAmelCase ) with self.assertRaises(__UpperCAmelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(__UpperCAmelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=__UpperCAmelCase , ) self.run_entailment_id(__UpperCAmelCase ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : Pipeline ) ->int: """simple docstring""" a = zero_shot_classifier.model.config a = config.labelaid a = zero_shot_classifier.entailment_id a = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) a = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) a = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) a = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) a = original_labelaid self.assertEqual(__UpperCAmelCase , zero_shot_classifier.entailment_id ) @require_torch def __lowerCAmelCase ( self : Optional[Any] ) ->str: """simple docstring""" a = 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 __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @require_tf def __lowerCAmelCase ( self : Optional[int] ) ->Union[str, Any]: """simple docstring""" a = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.333, 0.333, 0.333], } , ) @slow @require_torch def __lowerCAmelCase ( self : int ) ->List[Any]: """simple docstring""" a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) a = 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=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''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.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def __lowerCAmelCase ( self : Optional[int] ) ->Optional[Any]: """simple docstring""" a = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) a = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.976, 0.015, 0.009], } , ) a = 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=__UpperCAmelCase , ) self.assertEqual( nested_simplify(__UpperCAmelCase ) , { '''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.817, 0.713, 0.018, 0.018], } , )
0
from math import factorial UpperCAmelCase__ = {str(digit): factorial(digit) for digit in range(10)} def _a ( a :int ) -> int: if not isinstance(a , a ): 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(a ) ) def _a ( a :int = 60 , a :int = 1_000_000 ) -> int: if not isinstance(a , a ) or not isinstance(a , a ): 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 a = 0 # the cached sizes of the previous chains a = {} for start_chain_element in range(1 , a ): # The temporary set will contain the elements of the chain a = set() a = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. a = 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(a ) chain_set_length += 1 a = digit_factorial_sum(a ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] a = 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
1
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''decision_transformer''' __snake_case = ['''past_key_values'''] __snake_case = { '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Any , __UpperCAmelCase : List[Any]=17 , __UpperCAmelCase : int=4 , __UpperCAmelCase : Optional[int]=128 , __UpperCAmelCase : Union[str, Any]=4_096 , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : Optional[Any]=1 , __UpperCAmelCase : Optional[Any]=1_024 , __UpperCAmelCase : Any=3 , __UpperCAmelCase : Dict=1 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : Tuple=0.1 , __UpperCAmelCase : Any=0.1 , __UpperCAmelCase : Dict=0.1 , __UpperCAmelCase : Tuple=1e-5 , __UpperCAmelCase : str=0.02 , __UpperCAmelCase : Any=True , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=50_256 , __UpperCAmelCase : int=50_256 , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Tuple=False , **__UpperCAmelCase : List[str] , ) ->str: """simple docstring""" a = state_dim a = act_dim a = hidden_size a = max_ep_len a = action_tanh a = vocab_size a = n_positions a = n_layer a = n_head a = n_inner a = activation_function a = resid_pdrop a = embd_pdrop a = attn_pdrop a = layer_norm_epsilon a = initializer_range a = scale_attn_weights a = use_cache a = scale_attn_by_inverse_layer_idx a = reorder_and_upcast_attn a = bos_token_id a = eos_token_id super().__init__(bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase )
0
def _a ( a :int = 100 ) -> int: a = n * (n + 1) * (2 * n + 1) / 6 a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(f"""{solution() = }""")
0
1
def _a ( a :str = "The quick brown fox jumps over the lazy dog" , ) -> bool: a = set() # Replace all the whitespace in our sentence a = input_str.replace(''' ''' , '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(a ) == 26 def _a ( a :str = "The quick brown fox jumps over the lazy dog" , ) -> bool: a = [False] * 26 for char in input_str: if char.islower(): a = True elif char.isupper(): a = True return all(a ) def _a ( a :str = "The quick brown fox jumps over the lazy dog" , ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def _a ( ) -> None: from timeit import timeit a = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''' , setup=a ) ) print(timeit('''is_pangram_faster()''' , setup=a ) ) print(timeit('''is_pangram_fastest()''' , setup=a ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { "configuration_groupvit": [ "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GroupViTModel", "GroupViTPreTrainedModel", "GroupViTTextModel", "GroupViTVisionModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFGroupViTModel", "TFGroupViTPreTrainedModel", "TFGroupViTTextModel", "TFGroupViTVisionModel", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
0
1
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 UpperCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece.model") UpperCAmelCase__ = {"target_lang": "fi", "source_lang": "en"} UpperCAmelCase__ = ">>zh<<" UpperCAmelCase__ = "Helsinki-NLP/" if is_torch_available(): UpperCAmelCase__ = "pt" elif is_tf_available(): UpperCAmelCase__ = "tf" else: UpperCAmelCase__ = "jax" @require_sentencepiece class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = MarianTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" super().setUp() a = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] a = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) a = Path(self.tmpdirname ) save_json(__UpperCAmelCase , save_dir / VOCAB_FILES_NAMES['''vocab'''] ) save_json(__UpperCAmelCase , save_dir / VOCAB_FILES_NAMES['''tokenizer_config_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__UpperCAmelCase , save_dir / VOCAB_FILES_NAMES['''source_spm'''] ) copyfile(__UpperCAmelCase , save_dir / VOCAB_FILES_NAMES['''target_spm'''] ) a = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self : Optional[int] , **__UpperCAmelCase : Dict ) ->MarianTokenizer: """simple docstring""" return MarianTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : List[Any] ) ->List[str]: """simple docstring""" return ( "This is a test", "This is a test", ) def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" a = '''</s>''' a = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Dict: """simple docstring""" a = 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(__UpperCAmelCase ) , 9 ) def __lowerCAmelCase ( self : Dict ) ->List[str]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" a = MarianTokenizer.from_pretrained(F"""{ORG_NAME}opus-mt-en-de""" ) a = en_de_tokenizer(['''I am a small frog'''] , return_tensors=__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) a = [38, 121, 14, 697, 38_848, 0] self.assertListEqual(__UpperCAmelCase , batch.input_ids[0] ) a = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__UpperCAmelCase ) a = [x.name for x in Path(__UpperCAmelCase ).glob('''*''' )] self.assertIn('''source.spm''' , __UpperCAmelCase ) MarianTokenizer.from_pretrained(__UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" a = self.get_tokenizer() a = tok( ['''I am a small frog''' * 1_000, '''I am a small frog'''] , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors=__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def __lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" a = self.get_tokenizer() a = tok(['''I am a tiny frog''', '''I am a small frog'''] , padding=__UpperCAmelCase , return_tensors=__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def __lowerCAmelCase ( self : List[Any] ) ->Tuple: """simple docstring""" a = {'''input_ids''': [[43_495, 462, 20, 42_164, 1_369, 52, 464, 132, 1_703, 492, 13, 7_491, 38_999, 6, 8, 464, 132, 1_703, 492, 13, 4_669, 37_867, 13, 7_525, 27, 1_593, 988, 13, 33_972, 7_029, 6, 20, 8_251, 383, 2, 270, 5_866, 3_788, 2, 2_353, 8_251, 12_338, 2, 13_958, 387, 2, 3_629, 6_953, 188, 2_900, 2, 13_958, 8_011, 11_501, 23, 8_460, 4_073, 34_009, 20, 435, 11_439, 27, 8, 8_460, 4_073, 6_004, 20, 9_988, 375, 27, 33, 266, 1_945, 1_076, 1_350, 37_867, 3_288, 5, 577, 1_076, 4_374, 8, 5_082, 5, 26_453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10_767, 6, 316, 304, 4_239, 3, 0], [148, 15_722, 19, 1_839, 12, 1_350, 13, 22_327, 5_082, 5_418, 47_567, 35_938, 59, 318, 19_552, 108, 2_183, 54, 14_976, 4_835, 32, 547, 1_114, 8, 315, 2_417, 5, 92, 19_088, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100], [36, 6_395, 12_570, 39_147, 11_597, 6, 266, 4, 45_405, 7_296, 3, 0, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100, 58_100]], '''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=__UpperCAmelCase , model_name='''Helsinki-NLP/opus-mt-en-de''' , revision='''1a8c2263da11e68e50938f97e10cd57820bd504c''' , decode_kwargs={'''use_source_tokenizer''': True} , ) def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = MarianTokenizer.from_pretrained('''hf-internal-testing/test-marian-two-vocabs''' ) a = '''Tämä on testi''' a = '''This is a test''' a = [76, 7, 2_047, 2] a = [69, 12, 11, 940, 2] a = tokenizer(__UpperCAmelCase ).input_ids self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) a = tokenizer(text_target=__UpperCAmelCase ).input_ids self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) a = tokenizer.decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase ) self.assertEqual(__UpperCAmelCase , __UpperCAmelCase )
0
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 lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = ShapEPipeline __snake_case = ['''prompt'''] __snake_case = ['''prompt'''] __snake_case = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __snake_case = False @property def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" return 32 @property def __lowerCAmelCase ( self : Any ) ->Tuple: """simple docstring""" return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : Tuple ) ->Optional[Any]: """simple docstring""" return 8 @property def __lowerCAmelCase ( self : Tuple ) ->str: """simple docstring""" a = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" torch.manual_seed(0 ) a = 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-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModelWithProjection(__UpperCAmelCase ) @property def __lowerCAmelCase ( self : Dict ) ->Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, } a = PriorTransformer(**__UpperCAmelCase ) return model @property def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" torch.manual_seed(0 ) a = { '''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, ), } a = ShapERenderer(**__UpperCAmelCase ) return model def __lowerCAmelCase ( self : List[Any] ) ->Any: """simple docstring""" a = self.dummy_prior a = self.dummy_text_encoder a = self.dummy_tokenizer a = self.dummy_renderer a = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_024 , prediction_type='''sample''' , use_karras_sigmas=__UpperCAmelCase , clip_sample=__UpperCAmelCase , clip_sample_range=1.0 , ) a = { '''prior''': prior, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''renderer''': renderer, '''scheduler''': scheduler, } return components def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : str=0 ) ->Optional[int]: """simple docstring""" if str(__UpperCAmelCase ).startswith('''mps''' ): a = torch.manual_seed(__UpperCAmelCase ) else: a = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) a = { '''prompt''': '''horse''', '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" a = '''cpu''' a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = pipe(**self.get_dummy_inputs(__UpperCAmelCase ) ) a = output.images[0] a = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) a = np.array( [ 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, 0.00039216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __lowerCAmelCase ( self : Dict ) ->Optional[Any]: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = torch_device == '''cpu''' a = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__UpperCAmelCase , relax_max_difference=__UpperCAmelCase , ) def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = self.get_dummy_components() a = self.pipeline_class(**__UpperCAmelCase ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = 1 a = 2 a = self.get_dummy_inputs(__UpperCAmelCase ) for key in inputs.keys(): if key in self.batch_params: a = batch_size * [inputs[key]] a = pipe(**__UpperCAmelCase , num_images_per_prompt=__UpperCAmelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->Any: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : List[Any] ) ->Union[str, Any]: """simple docstring""" a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_np_out.npy''' ) a = ShapEPipeline.from_pretrained('''openai/shap-e''' ) a = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) a = torch.Generator(device=__UpperCAmelCase ).manual_seed(0 ) a = pipe( '''a shark''' , generator=__UpperCAmelCase , guidance_scale=15.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase )
0
1
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelForTokenClassification, AutoModelWithLMHead, AutoTokenizer, PretrainedConfig, PreTrainedTokenizer, ) from transformers.optimization import ( Adafactor, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.utils.versions import require_version UpperCAmelCase__ = logging.getLogger(__name__) require_version("pytorch_lightning>=1.0.4") UpperCAmelCase__ = { "base": AutoModel, "sequence-classification": AutoModelForSequenceClassification, "question-answering": AutoModelForQuestionAnswering, "pretraining": AutoModelForPreTraining, "token-classification": AutoModelForTokenClassification, "language-modeling": AutoModelWithLMHead, "summarization": AutoModelForSeqaSeqLM, "translation": AutoModelForSeqaSeqLM, } # update this and the import above to support new schedulers from transformers.optimization UpperCAmelCase__ = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, # '': get_constant_schedule, # not supported for now # '': get_constant_schedule_with_warmup, # not supported for now } UpperCAmelCase__ = sorted(arg_to_scheduler.keys()) UpperCAmelCase__ = "{" + ", ".join(arg_to_scheduler_choices) + "}" class lowercase_ ( pl.LightningModule ): '''simple docstring''' def __init__( self : str , __UpperCAmelCase : argparse.Namespace , __UpperCAmelCase : str=None , __UpperCAmelCase : List[str]="base" , __UpperCAmelCase : str=None , __UpperCAmelCase : int=None , __UpperCAmelCase : Optional[Any]=None , **__UpperCAmelCase : Optional[int] , ) ->Tuple: """simple docstring""" super().__init__() # TODO: move to self.save_hyperparameters() # self.save_hyperparameters() # can also expand arguments into trainer signature for easier reading self.save_hyperparameters(__UpperCAmelCase ) a = 0 a = Path(self.hparams.output_dir ) a = self.hparams.cache_dir if self.hparams.cache_dir else None if config is None: a = AutoConfig.from_pretrained( self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path , **({'''num_labels''': num_labels} if num_labels is not None else {}) , cache_dir=__UpperCAmelCase , **__UpperCAmelCase , ) else: a = config a = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(self.hparams , __UpperCAmelCase , __UpperCAmelCase ): assert hasattr(self.config , __UpperCAmelCase ), F"""model config doesn't have a `{p}` attribute""" setattr(self.config , __UpperCAmelCase , getattr(self.hparams , __UpperCAmelCase ) ) if tokenizer is None: a = AutoTokenizer.from_pretrained( self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path , cache_dir=__UpperCAmelCase , ) else: a = tokenizer a = MODEL_MODES[mode] if model is None: a = self.model_type.from_pretrained( self.hparams.model_name_or_path , from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path ) , config=self.config , cache_dir=__UpperCAmelCase , ) else: a = model def __lowerCAmelCase ( self : Any , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : str ) ->str: """simple docstring""" a = self.model_type.from_pretrained(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : List[str] ) ->Optional[Any]: """simple docstring""" a = arg_to_scheduler[self.hparams.lr_scheduler] a = get_schedule_func( self.opt , num_warmup_steps=self.hparams.warmup_steps , num_training_steps=self.total_steps() ) a = {'''scheduler''': scheduler, '''interval''': '''step''', '''frequency''': 1} return scheduler def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.model a = ['''bias''', '''LayerNorm.weight'''] a = [ { '''params''': [ p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay ) ], # check this named paramters '''weight_decay''': self.hparams.weight_decay, }, { '''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )], '''weight_decay''': 0.0, }, ] if self.hparams.adafactor: a = Adafactor( __UpperCAmelCase , lr=self.hparams.learning_rate , scale_parameter=__UpperCAmelCase , relative_step=__UpperCAmelCase ) else: a = AdamW( __UpperCAmelCase , lr=self.hparams.learning_rate , eps=self.hparams.adam_epsilon ) a = optimizer a = self.get_lr_scheduler() return [optimizer], [scheduler] def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Optional[Any] ) ->Dict: """simple docstring""" return self.validation_step(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[Any] ) ->Any: """simple docstring""" return self.validation_end(__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" a = max(1 , self.hparams.gpus ) # TODO: consider num_tpu_cores a = self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Dict ) ->Optional[int]: """simple docstring""" if stage == "test": a = len(self.test_dataloader().dataset ) else: a = self.get_dataloader('''train''' , self.hparams.train_batch_size , shuffle=__UpperCAmelCase ) a = len(self.train_dataloader().dataset ) def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : bool = False ) ->str: """simple docstring""" raise NotImplementedError('''You must implement this for your task''' ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" return self.train_loader def __lowerCAmelCase ( self : List[Any] ) ->List[Any]: """simple docstring""" return self.get_dataloader('''dev''' , self.hparams.eval_batch_size , shuffle=__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" return self.get_dataloader('''test''' , self.hparams.eval_batch_size , shuffle=__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] ) ->Optional[Any]: """simple docstring""" return os.path.join( self.hparams.data_dir , '''cached_{}_{}_{}'''.format( __UpperCAmelCase , list(filter(__UpperCAmelCase , self.hparams.model_name_or_path.split('''/''' ) ) ).pop() , str(self.hparams.max_seq_length ) , ) , ) @pl.utilities.rank_zero_only def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Dict[str, Any] ) ->None: """simple docstring""" a = self.output_dir.joinpath('''best_tfmr''' ) a = self.step_count self.model.save_pretrained(__UpperCAmelCase ) self.tokenizer.save_pretrained(__UpperCAmelCase ) @staticmethod def __lowerCAmelCase ( __UpperCAmelCase : Dict , __UpperCAmelCase : int ) ->int: """simple docstring""" parser.add_argument( '''--model_name_or_path''' , default=__UpperCAmelCase , type=__UpperCAmelCase , required=__UpperCAmelCase , help='''Path to pretrained model or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--config_name''' , default='''''' , type=__UpperCAmelCase , help='''Pretrained config name or path if not the same as model_name''' ) parser.add_argument( '''--tokenizer_name''' , default=__UpperCAmelCase , type=__UpperCAmelCase , help='''Pretrained tokenizer name or path if not the same as model_name''' , ) parser.add_argument( '''--cache_dir''' , default=str(Path(__UpperCAmelCase ).parent / '''test_run''' / '''cache''' ) , type=__UpperCAmelCase , help='''Where do you want to store the pre-trained models downloaded from huggingface.co''' , ) parser.add_argument( '''--encoder_layerdrop''' , type=__UpperCAmelCase , help='''Encoder layer dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--decoder_layerdrop''' , type=__UpperCAmelCase , help='''Decoder layer dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--dropout''' , type=__UpperCAmelCase , help='''Dropout probability (Optional). Goes into model.config''' , ) parser.add_argument( '''--attention_dropout''' , type=__UpperCAmelCase , help='''Attention dropout probability (Optional). Goes into model.config''' , ) parser.add_argument('''--learning_rate''' , default=5e-5 , type=__UpperCAmelCase , help='''The initial learning rate for Adam.''' ) parser.add_argument( '''--lr_scheduler''' , default='''linear''' , choices=__UpperCAmelCase , metavar=__UpperCAmelCase , type=__UpperCAmelCase , help='''Learning rate scheduler''' , ) parser.add_argument('''--weight_decay''' , default=0.0 , type=__UpperCAmelCase , help='''Weight decay if we apply some.''' ) parser.add_argument('''--adam_epsilon''' , default=1e-8 , type=__UpperCAmelCase , help='''Epsilon for Adam optimizer.''' ) parser.add_argument('''--warmup_steps''' , default=0 , type=__UpperCAmelCase , help='''Linear warmup over warmup_steps.''' ) parser.add_argument('''--num_workers''' , default=4 , type=__UpperCAmelCase , help='''kwarg passed to DataLoader''' ) parser.add_argument('''--num_train_epochs''' , dest='''max_epochs''' , default=3 , type=__UpperCAmelCase ) parser.add_argument('''--train_batch_size''' , default=32 , type=__UpperCAmelCase ) parser.add_argument('''--eval_batch_size''' , default=32 , type=__UpperCAmelCase ) parser.add_argument('''--adafactor''' , action='''store_true''' ) class lowercase_ ( pl.Callback ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : int , __UpperCAmelCase : Optional[int] ) ->int: """simple docstring""" if ( trainer.is_global_zero and trainer.global_rank == 0 ): # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed. pl_module.model.rag.retriever.init_retrieval() # better to use hook functions. class lowercase_ ( pl.Callback ): '''simple docstring''' def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[Any] ) ->Union[str, Any]: """simple docstring""" for name, param in pl_module.model.rag.named_parameters(): if param.grad is None: print(__UpperCAmelCase ) class lowercase_ ( pl.Callback ): '''simple docstring''' def __lowerCAmelCase ( self : int , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict ) ->int: """simple docstring""" a = trainer.lr_schedulers[0]['''scheduler'''] a = {F"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr() )} pl_module.logger.log_metrics(__UpperCAmelCase ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : pl.Trainer , __UpperCAmelCase : pl.LightningModule ) ->Union[str, Any]: """simple docstring""" rank_zero_info('''***** Validation results *****''' ) a = trainer.callback_metrics # Log results for key in sorted(__UpperCAmelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('''{} = {}\n'''.format(__UpperCAmelCase , str(metrics[key] ) ) ) def __lowerCAmelCase ( self : int , __UpperCAmelCase : pl.Trainer , __UpperCAmelCase : pl.LightningModule ) ->Optional[int]: """simple docstring""" rank_zero_info('''***** Test results *****''' ) a = trainer.callback_metrics # Log and save results to file a = os.path.join(pl_module.hparams.output_dir , '''test_results.txt''' ) with open(__UpperCAmelCase , '''w''' ) as writer: for key in sorted(__UpperCAmelCase ): if key not in ["log", "progress_bar"]: rank_zero_info('''{} = {}\n'''.format(__UpperCAmelCase , str(metrics[key] ) ) ) writer.write('''{} = {}\n'''.format(__UpperCAmelCase , str(metrics[key] ) ) ) def _a ( a :Union[str, Any] , a :int ) -> None: # To allow all pl args uncomment the following line # parser = pl.Trainer.add_argparse_args(parser) parser.add_argument( '''--output_dir''' , default=str(Path(a ).parent / '''test_run''' / '''model_checkpoints''' ) , type=a , help='''The output directory where the model predictions and checkpoints will be written.''' , ) parser.add_argument( '''--fp16''' , action='''store_true''' , help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''' , ) parser.add_argument( '''--fp16_opt_level''' , type=a , default='''O2''' , help=( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].''' '''See details at https://nvidia.github.io/apex/amp.html''' ) , ) parser.add_argument('''--n_tpu_cores''' , dest='''tpu_cores''' , type=a ) parser.add_argument('''--max_grad_norm''' , dest='''gradient_clip_val''' , default=1.0 , type=a , help='''Max gradient norm''' ) parser.add_argument('''--do_train''' , action='''store_true''' , help='''Whether to run training.''' ) parser.add_argument('''--do_predict''' , action='''store_true''' , help='''Whether to run predictions on the test set.''' ) parser.add_argument( '''--gradient_accumulation_steps''' , dest='''accumulate_grad_batches''' , type=a , default=1 , help='''Number of updates steps to accumulate before performing a backward/update pass.''' , ) parser.add_argument('''--seed''' , type=a , default=42 , help='''random seed for initialization''' ) parser.add_argument( '''--data_dir''' , default=str(Path(a ).parent / '''test_run''' / '''dummy-train-data''' ) , type=a , help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.''' , ) def _a ( a :BaseTransformer , a :argparse.Namespace , a :Tuple=None , a :Any=True , a :List[str]=[] , a :List[Any]=None , a :Union[str, Any]=None , **a :Optional[Any] , ) -> List[str]: pl.seed_everything(args.seed ) # init model a = Path(model.hparams.output_dir ) odir.mkdir(exist_ok=a ) # add custom checkpoints if checkpoint_callback is None: a = pl.callbacks.ModelCheckpoint( filepath=args.output_dir , prefix='''checkpoint''' , monitor='''val_loss''' , mode='''min''' , save_top_k=1 ) if early_stopping_callback: extra_callbacks.append(a ) if logging_callback is None: a = LoggingCallback() a = {} if args.fpaa: a = 16 if args.gpus > 1: a = '''auto''' a = '''ddp''' a = args.accumulate_grad_batches a = None a = '''auto''' a = pl.Trainer.from_argparse_args( a , weights_summary=a , callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] , logger=a , val_check_interval=1 , num_sanity_val_steps=2 , **a , ) if args.do_train: trainer.fit(a ) else: print('''RAG modeling tests with new set functions successfuly executed!''' ) return trainer
0
from __future__ import annotations import time import numpy as np UpperCAmelCase__ = [8, 5, 9, 7] UpperCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] UpperCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : list[int] , __UpperCAmelCase : list[list[int]] , __UpperCAmelCase : list[list[int]] , ) ->None: """simple docstring""" a = claim_vector a = allocated_resources_table a = maximum_claim_table def __lowerCAmelCase ( self : Any ) ->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 __lowerCAmelCase ( self : Optional[int] ) ->list[int]: """simple docstring""" return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def __lowerCAmelCase ( self : Union[str, Any] ) ->list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(__UpperCAmelCase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def __lowerCAmelCase ( self : Tuple ) ->dict[int, list[int]]: """simple docstring""" return {self.__need().index(__UpperCAmelCase ): i for i in self.__need()} def __lowerCAmelCase ( self : Optional[Any] , **__UpperCAmelCase : Any ) ->None: """simple docstring""" a = self.__need() a = self.__allocated_resources_table a = self.__available_resources() a = 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: a = False for each_need in need_list: a = True for index, need in enumerate(__UpperCAmelCase ): if need > available_resources[index]: a = False break if execution: a = 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: a = original_need_index print(F"""Process {process_number + 1} is executing.""" ) # remove the process run from stack need_list.remove(__UpperCAmelCase ) # update available/freed resources stack a = np.array(__UpperCAmelCase ) + np.array( alloc_resources_table[process_number] ) print( '''Updated available resource stack for processes: ''' + ''' '''.join([str(__UpperCAmelCase ) 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 __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" print(''' ''' * 9 + '''Allocated Resource Table''' ) for item in self.__allocated_resources_table: print( F"""P{self.__allocated_resources_table.index(__UpperCAmelCase ) + 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(__UpperCAmelCase ) + 1}""" + ''' '''.join(F"""{it:>8}""" for it in item ) + '''\n''' ) print( '''Current Usage by Active Processes: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__claim_vector ) ) print( '''Initial Available Resources: ''' + ''' '''.join(str(__UpperCAmelCase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
0
1
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 ( a :List[str] , a :Tuple , a :List[str] , a :Dict ) -> int: if isinstance(a , a ): a = np.full((len(a ), sequence_length, 2) , a ) else: a = np.full((len(a ), sequence_length) , a ) for i, tensor in enumerate(a ): if padding_side == "right": if isinstance(a , a ): a = tensor[:sequence_length] else: a = tensor[:sequence_length] else: if isinstance(a , a ): a = tensor[:sequence_length] else: a = tensor[:sequence_length] return out_tensor.tolist() def _a ( a :Optional[int] ) -> int: a = ord(a ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True a = unicodedata.category(a ) if cat.startswith('''P''' ): return True return False @dataclass class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = 42 __snake_case = True __snake_case = None __snake_case = None __snake_case = -1_00 __snake_case = "pt" def __lowerCAmelCase ( self : int , __UpperCAmelCase : Any ) ->Tuple: """simple docstring""" import torch a = '''label''' if '''label''' in features[0].keys() else '''labels''' a = [feature[label_name] for feature in features] if label_name in features[0].keys() else None a = self.tokenizer.pad( __UpperCAmelCase , 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 a = torch.tensor(batch['''entity_ids'''] ).shape[1] a = self.tokenizer.padding_side if padding_side == "right": a = [ list(__UpperCAmelCase ) + [self.label_pad_token_id] * (sequence_length - len(__UpperCAmelCase )) for label in labels ] else: a = [ [self.label_pad_token_id] * (sequence_length - len(__UpperCAmelCase )) + list(__UpperCAmelCase ) for label in labels ] a = [feature['''ner_tags'''] for feature in features] a = padding_tensor(__UpperCAmelCase , -1 , __UpperCAmelCase , __UpperCAmelCase ) a = [feature['''original_entity_spans'''] for feature in features] a = padding_tensor(__UpperCAmelCase , (-1, -1) , __UpperCAmelCase , __UpperCAmelCase ) a = {k: torch.tensor(__UpperCAmelCase , dtype=torch.intaa ) for k, v in batch.items()} return batch
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer UpperCAmelCase__ = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ = { "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" ), }, } UpperCAmelCase__ = { "google/electra-small-generator": 512, "google/electra-base-generator": 512, "google/electra-large-generator": 512, "google/electra-small-discriminator": 512, "google/electra-base-discriminator": 512, "google/electra-large-discriminator": 512, } UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ElectraTokenizer def __init__( self : Dict , __UpperCAmelCase : int=None , __UpperCAmelCase : str=None , __UpperCAmelCase : Optional[int]=True , __UpperCAmelCase : str="[UNK]" , __UpperCAmelCase : Any="[SEP]" , __UpperCAmelCase : str="[PAD]" , __UpperCAmelCase : Optional[Any]="[CLS]" , __UpperCAmelCase : Union[str, Any]="[MASK]" , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Optional[int] , ) ->str: """simple docstring""" super().__init__( __UpperCAmelCase , tokenizer_file=__UpperCAmelCase , do_lower_case=__UpperCAmelCase , unk_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , cls_token=__UpperCAmelCase , mask_token=__UpperCAmelCase , tokenize_chinese_chars=__UpperCAmelCase , strip_accents=__UpperCAmelCase , **__UpperCAmelCase , ) a = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , __UpperCAmelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , __UpperCAmelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , __UpperCAmelCase ) != tokenize_chinese_chars ): a = getattr(__UpperCAmelCase , normalizer_state.pop('''type''' ) ) a = do_lower_case a = strip_accents a = tokenize_chinese_chars a = normalizer_class(**__UpperCAmelCase ) a = do_lower_case def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple=None ) ->str: """simple docstring""" a = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : List[int] , __UpperCAmelCase : Optional[List[int]] = None ) ->List[int]: """simple docstring""" a = [self.sep_token_id] a = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[str] = None ) ->Tuple[str]: """simple docstring""" a = self._tokenizer.model.save(__UpperCAmelCase , name=__UpperCAmelCase ) return tuple(__UpperCAmelCase )
0
1
import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertJapaneseTokenizer __snake_case = False __snake_case = True def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" super().setUp() a = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''', '''世界''', '''##世界''', '''、''', '''##、''', '''。''', '''##。''', ] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Optional[int] ) ->Union[str, Any]: """simple docstring""" a = '''こんにちは、世界。 \nこんばんは、世界。''' a = '''こんにちは 、 世界 。 こんばんは 、 世界 。''' return input_text, output_text def __lowerCAmelCase ( self : str , __UpperCAmelCase : List[str] ) ->Union[str, Any]: """simple docstring""" a , a = self.get_input_output_texts(__UpperCAmelCase ) a = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) a = tokenizer.decode(__UpperCAmelCase , clean_up_tokenization_spaces=__UpperCAmelCase ) return text, ids def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : int ) ->int: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : Dict ) ->Any: """simple docstring""" a = self.tokenizer_class(self.vocab_file ) a = tokenizer.tokenize('''こんにちは、世界。\nこんばんは、世界。''' ) self.assertListEqual(__UpperCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def __lowerCAmelCase ( self : List[str] ) ->Dict: """simple docstring""" a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''mecab''' ) self.assertIsNotNone(__UpperCAmelCase ) a = '''こんにちは、世界。\nこんばんは、世界。''' a = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(__UpperCAmelCase , '''wb''' ) as handle: pickle.dump(__UpperCAmelCase , __UpperCAmelCase ) with open(__UpperCAmelCase , '''rb''' ) as handle: a = pickle.load(__UpperCAmelCase ) a = tokenizer_new.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->str: """simple docstring""" a = MecabTokenizer(mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" try: a = MecabTokenizer(mecab_dic='''unidic_lite''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" try: a = MecabTokenizer(mecab_dic='''unidic''' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self : Union[str, Any] ) ->List[Any]: """simple docstring""" a = MecabTokenizer(do_lower_case=__UpperCAmelCase , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iphone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" try: a = MecabTokenizer( do_lower_case=__UpperCAmelCase , normalize_text=__UpperCAmelCase , mecab_option='''-d /usr/local/lib/mecab/dic/jumandic''' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" a = MecabTokenizer(normalize_text=__UpperCAmelCase , mecab_dic='''ipadic''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。'''] , ) @require_sudachi def __lowerCAmelCase ( self : Optional[Any] ) ->Dict: """simple docstring""" a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''sudachi''' ) self.assertIsNotNone(__UpperCAmelCase ) a = '''こんにちは、世界。\nこんばんは、世界。''' a = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(__UpperCAmelCase , '''wb''' ) as handle: pickle.dump(__UpperCAmelCase , __UpperCAmelCase ) with open(__UpperCAmelCase , '''rb''' ) as handle: a = pickle.load(__UpperCAmelCase ) a = tokenizer_new.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @require_sudachi def __lowerCAmelCase ( self : str ) ->Optional[int]: """simple docstring""" a = SudachiTokenizer(sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''A''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国''', '''人''', '''参政''', '''権'''] ) @require_sudachi def __lowerCAmelCase ( self : str ) ->Tuple: """simple docstring""" a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''B''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人''', '''参政権'''] ) @require_sudachi def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''C''' ) self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人参政権'''] ) @require_sudachi def __lowerCAmelCase ( self : List[Any] ) ->Dict: """simple docstring""" a = SudachiTokenizer(do_lower_case=__UpperCAmelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" a = SudachiTokenizer(normalize_text=__UpperCAmelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', '''\u3000''', '''。''', ''' ''', ''' '''] , ) @require_sudachi def __lowerCAmelCase ( self : Any ) ->Optional[Any]: """simple docstring""" a = SudachiTokenizer(trim_whitespace=__UpperCAmelCase , sudachi_dict_type='''core''' ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self : Optional[Any] ) ->List[str]: """simple docstring""" a = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''jumanpp''' ) self.assertIsNotNone(__UpperCAmelCase ) a = '''こんにちは、世界。\nこんばんは、世界。''' a = tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a = os.path.join(self.tmpdirname , '''tokenizer.bin''' ) with open(__UpperCAmelCase , '''wb''' ) as handle: pickle.dump(__UpperCAmelCase , __UpperCAmelCase ) with open(__UpperCAmelCase , '''rb''' ) as handle: a = pickle.load(__UpperCAmelCase ) a = tokenizer_new.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @require_jumanpp def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" a = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self : int ) ->Tuple: """simple docstring""" a = JumanppTokenizer(do_lower_case=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self : List[str] ) ->Tuple: """simple docstring""" a = JumanppTokenizer(normalize_text=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''ア''', '''ッ''', '''フ''', '''゚''', '''ル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self : int ) ->Optional[int]: """simple docstring""" a = JumanppTokenizer(trim_whitespace=__UpperCAmelCase ) self.assertListEqual( tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''。'''] , ) @require_jumanpp def __lowerCAmelCase ( self : Union[str, Any] ) ->Tuple: """simple docstring""" a = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('''ありがとうございますm(_ _)m見つけるのが大変です。''' ) , ['''ありがとう''', '''ございます''', '''m(_ _)m''', '''見つける''', '''の''', '''が''', '''大変です''', '''。'''] , ) def __lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = WordpieceTokenizer(vocab=__UpperCAmelCase , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こんにちは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは''' ) , ['''こん''', '''##ばんは'''] ) self.assertListEqual(tokenizer.tokenize('''こんばんは こんばんにちは こんにちは''' ) , ['''こん''', '''##ばんは''', '''[UNK]''', '''こんにちは'''] ) def __lowerCAmelCase ( self : int ) ->List[str]: """simple docstring""" a = BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp''' ) a = tokenizer.subword_tokenizer a = subword_tokenizer.tokenize('''国境 の 長い トンネル を 抜ける と 雪国 であった 。''' ) self.assertListEqual(__UpperCAmelCase , ['''▁国境''', '''▁の''', '''▁長い''', '''▁トンネル''', '''▁を''', '''▁抜ける''', '''▁と''', '''▁雪''', '''国''', '''▁であった''', '''▁。'''] ) a = subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは''' ) self.assertListEqual(__UpperCAmelCase , ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) ->List[str]: """simple docstring""" a = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese''' ) a = tokenizer.encode('''ありがとう。''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''どういたしまして。''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class lowercase_ ( lowercase , unittest.TestCase ): '''simple docstring''' __snake_case = BertJapaneseTokenizer __snake_case = False def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" super().setUp() a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : List[str] , **__UpperCAmelCase : str ) ->List[Any]: """simple docstring""" return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='''character''' , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[Any] ) ->int: """simple docstring""" a = '''こんにちは、世界。 \nこんばんは、世界。''' a = '''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。''' return input_text, output_text def __lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : Tuple ) ->int: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" pass # TODO add if relevant def __lowerCAmelCase ( self : Tuple ) ->Optional[int]: """simple docstring""" a = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='''character''' ) a = tokenizer.tokenize('''こんにちは、世界。 \nこんばんは、世界。''' ) self.assertListEqual( __UpperCAmelCase , ['''こ''', '''ん''', '''に''', '''ち''', '''は''', '''、''', '''世''', '''界''', '''。''', '''こ''', '''ん''', '''ば''', '''ん''', '''は''', '''、''', '''世''', '''界''', '''。'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def __lowerCAmelCase ( self : Any ) ->Optional[int]: """simple docstring""" a = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。'''] a = {} for i, token in enumerate(__UpperCAmelCase ): a = i a = CharacterTokenizer(vocab=__UpperCAmelCase , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''は'''] ) self.assertListEqual(tokenizer.tokenize('''こんにちほ''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Optional[int] ) ->Dict: """simple docstring""" a = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char''' ) a = tokenizer.encode('''ありがとう。''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.encode('''どういたしまして。''' , add_special_tokens=__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ) a = tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase , __UpperCAmelCase ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : Union[str, Any] ) ->Any: """simple docstring""" a = '''cl-tohoku/bert-base-japanese''' a = AutoTokenizer.from_pretrained(__UpperCAmelCase ) self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase ) class lowercase_ ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[Any] ) ->int: """simple docstring""" a = '''cl-tohoku/bert-base-japanese''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertTokenizer.from_pretrained(__UpperCAmelCase ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) ) a = '''bert-base-cased''' with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm: BertJapaneseTokenizer.from_pretrained(__UpperCAmelCase ) self.assertTrue( cm.records[0].message.startswith( '''The tokenizer class you load from this checkpoint is not the same type as the class this function''' ''' is called from.''' ) )
0
def _a ( a :int ) -> bool: a = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
0
1
UpperCAmelCase__ = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(100000)] def _a ( a :int ) -> int: a = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100_000] number //= 100_000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution UpperCAmelCase__ = [None] * 10000000 UpperCAmelCase__ = True UpperCAmelCase__ = False def _a ( a :int ) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore a = chain(next_number(a ) ) a = number_chain while number < 10_000_000: a = number_chain number *= 10 return number_chain def _a ( a :int = 10_000_000 ) -> int: for i in range(1 , a ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(a ) if __name__ == "__main__": import doctest doctest.testmod() print(f"""{solution() = }""")
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 UpperCAmelCase__ = pytest.mark.integration @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" a = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__UpperCAmelCase ) for x in np.arange(30 ).tolist()]} ) return dset def __lowerCAmelCase ( self : Tuple ) ->Any: """simple docstring""" import faiss a = self._create_dummy_dataset() a = dset.map( lambda __UpperCAmelCase , __UpperCAmelCase : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__UpperCAmelCase , keep_in_memory=__UpperCAmelCase ) a = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) a , a = 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 __lowerCAmelCase ( self : Union[str, Any] ) ->Optional[Any]: """simple docstring""" import faiss a = 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 , ) a , a = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Any ) ->Union[str, Any]: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) a , a = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = 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(__UpperCAmelCase , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" from elasticsearch import Elasticsearch a = 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: a = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} a = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__UpperCAmelCase ) a , a = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : Any ) ->Any: """simple docstring""" import faiss a = 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 a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries a = np.eye(5 , dtype=np.floataa )[::-1] a , a = index.search_batch(__UpperCAmelCase ) self.assertRaises(__UpperCAmelCase , index.search_batch , queries[0] ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __UpperCAmelCase ) def __lowerCAmelCase ( self : Any ) ->List[Any]: """simple docstring""" import faiss a = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) a = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__UpperCAmelCase ): a = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowerCAmelCase ( self : int ) ->Optional[Any]: """simple docstring""" import faiss a = faiss.IndexFlat(5 ) a = FaissIndex(custom_index=__UpperCAmelCase ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowerCAmelCase ( self : int ) ->Dict: """simple docstring""" import faiss a = 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=__UpperCAmelCase ) as tmp_file: index.save(tmp_file.name ) a = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(__UpperCAmelCase ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def _a ( a :Dict ) -> Any: import faiss a = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) a = '''index.faiss''' a = F"""mock://{index_name}""" index.save(a , storage_options=mockfs.storage_options ) a = FaissIndex.load(a , storage_options=mockfs.storage_options ) a = np.zeros(5 , dtype=np.floataa ) a = 1 a , a = index.search(a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowercase_ ( lowercase ): '''simple docstring''' def __lowerCAmelCase ( self : int ) ->List[Any]: """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: a = Elasticsearch() a = {'''acknowledged''': True} a = ElasticSearchIndex(es_client=__UpperCAmelCase ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout a = '''foo''' a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} a , a = index.search(__UpperCAmelCase , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase ) # batched queries with timeout a = ['''foo''', '''bar''', '''foobar'''] a = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} a , a = index.search_batch(__UpperCAmelCase , request_timeout=30 ) a = [scores[0] for scores in total_scores] a = [indices[0] for indices in total_indices] self.assertGreater(np.min(__UpperCAmelCase ) , 0 ) self.assertListEqual([1, 1, 1] , __UpperCAmelCase )
0
1
import functools import gc import inspect import torch from .imports import is_npu_available, is_xpu_available def _a ( *a :List[str] ) -> Dict: if not isinstance(a , a ): a = list(a ) for i in range(len(a ) ): a = None gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() return objects def _a ( a :Exception ) -> bool: a = [ '''CUDA out of memory.''', # CUDA OOM '''cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.''', # CUDNN SNAFU '''DefaultCPUAllocator: can\'t allocate memory''', # CPU OOM ] if isinstance(a , a ) and len(exception.args ) == 1: return any(err in exception.args[0] for err in _statements ) return False def _a ( a :callable = None , a :int = 128 ) -> Optional[Any]: if function is None: return functools.partial(a , starting_batch_size=a ) a = starting_batch_size def decorator(*a :Union[str, Any] , **a :Dict ): nonlocal batch_size gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() a = list(inspect.signature(a ).parameters.keys() ) # Guard against user error if len(a ) < (len(a ) + 1): a = ''', '''.join([F"""{arg}={value}""" for arg, value in zip(params[1:] , args[1:] )] ) raise TypeError( F"""Batch size was passed into `{function.__name__}` as the first argument when called.""" F"""Remove this as the decorator already does so: `{function.__name__}({arg_str})`""" ) while True: if batch_size == 0: raise RuntimeError('''No executable batch size found, reached zero.''' ) try: return function(a , *a , **a ) except Exception as e: if should_reduce_batch_size(a ): gc.collect() if is_xpu_available(): torch.xpu.empty_cache() elif is_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() batch_size //= 2 else: raise return decorator
0
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = { "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 lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''t5''' __snake_case = ['''past_key_values'''] __snake_case = {'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''} def __init__( self : Optional[Any] , __UpperCAmelCase : Optional[Any]=32_128 , __UpperCAmelCase : List[Any]=512 , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : int=6 , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Optional[int]=8 , __UpperCAmelCase : str=32 , __UpperCAmelCase : Tuple=128 , __UpperCAmelCase : Optional[Any]=0.1 , __UpperCAmelCase : int=1e-6 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : int=True , __UpperCAmelCase : int=True , __UpperCAmelCase : List[Any]=0 , __UpperCAmelCase : int=1 , **__UpperCAmelCase : str , ) ->Optional[Any]: """simple docstring""" a = vocab_size a = d_model a = d_kv a = d_ff a = num_layers a = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a = num_heads a = relative_attention_num_buckets a = relative_attention_max_distance a = dropout_rate a = layer_norm_epsilon a = initializer_factor a = feed_forward_proj a = use_cache a = self.feed_forward_proj.split('''-''' ) a = act_info[-1] a = act_info[0] == '''gated''' if len(__UpperCAmelCase ) > 1 and act_info[0] != "gated" or len(__UpperCAmelCase ) > 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": a = '''gelu_new''' super().__init__( pad_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase , ) class lowercase_ ( lowercase ): '''simple docstring''' @property def __lowerCAmelCase ( self : Optional[Any] ) ->Mapping[str, Mapping[int, str]]: """simple docstring""" a = { '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''}, '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''}, } if self.use_past: a = '''past_encoder_sequence + sequence''' a = {0: '''batch'''} a = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: a = {0: '''batch''', 1: '''decoder_sequence'''} a = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__UpperCAmelCase , direction='''inputs''' ) return common_inputs @property def __lowerCAmelCase ( self : Union[str, Any] ) ->int: """simple docstring""" return 13
0
1
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 ( a :Tuple ) -> Optional[Any]: a = 384 a = 7 if "tiny" in model_name: a = 96 a = (2, 2, 6, 2) a = (3, 6, 12, 24) elif "small" in model_name: a = 96 a = (2, 2, 18, 2) a = (3, 6, 12, 24) elif "base" in model_name: a = 128 a = (2, 2, 18, 2) a = (4, 8, 16, 32) a = 12 a = 512 elif "large" in model_name: a = 192 a = (2, 2, 18, 2) a = (6, 12, 24, 48) a = 12 a = 768 # set label information a = 150 a = '''huggingface/label-files''' a = '''ade20k-id2label.json''' a = json.load(open(hf_hub_download(a , a , repo_type='''dataset''' ) , '''r''' ) ) a = {int(a ): v for k, v in idalabel.items()} a = {v: k for k, v in idalabel.items()} a = SwinConfig( embed_dim=a , depths=a , num_heads=a , window_size=a , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) a = UperNetConfig( backbone_config=a , auxiliary_in_channels=a , num_labels=a , idalabel=a , labelaid=a , ) return config def _a ( a :Dict ) -> List[str]: a = [] # 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 ( a :Optional[int] , a :Optional[Any] , a :List[Any] ) -> Optional[int]: a = dct.pop(a ) a = val def _a ( a :Union[str, Any] , a :str ) -> Any: a = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): a = 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) a = state_dict.pop(F"""backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight""" ) a = 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 a = in_proj_weight[:dim, :] a = in_proj_bias[: dim] a = in_proj_weight[ dim : dim * 2, : ] a = in_proj_bias[ dim : dim * 2 ] a = in_proj_weight[ -dim :, : ] a = in_proj_bias[-dim :] # fmt: on def _a ( a :List[str] ) -> List[str]: a , a = x.shape a = x.reshape(a , 4 , in_channel // 4 ) a = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(a , a ) return x def _a ( a :Optional[Any] ) -> Any: a , a = x.shape a = x.reshape(a , in_channel // 4 , 4 ) a = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(a , a ) return x def _a ( a :Dict ) -> Any: a = x.shape[0] a = x.reshape(4 , in_channel // 4 ) a = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(a ) return x def _a ( a :Any ) -> List[str]: a = x.shape[0] a = x.reshape(in_channel // 4 , 4 ) a = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(a ) return x def _a ( a :Union[str, Any] , a :str , a :Optional[int] ) -> Any: a = { '''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''', } a = model_name_to_url[model_name] a = torch.hub.load_state_dict_from_url(a , map_location='''cpu''' , file_name=a )[ '''state_dict''' ] for name, param in state_dict.items(): print(a , param.shape ) a = get_upernet_config(a ) a = UperNetForSemanticSegmentation(a ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): a = state_dict.pop(a ) if "bn" in key: a = key.replace('''bn''' , '''batch_norm''' ) a = val # rename keys a = create_rename_keys(a ) for src, dest in rename_keys: rename_key(a , a , a ) read_in_q_k_v(a , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: a = reverse_correct_unfold_reduction_order(a ) if "norm" in key: a = reverse_correct_unfold_norm_order(a ) model.load_state_dict(a ) # verify on image a = '''https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg''' a = Image.open(requests.get(a , stream=a ).raw ).convert('''RGB''' ) a = SegformerImageProcessor() a = processor(a , return_tensors='''pt''' ).pixel_values with torch.no_grad(): a = model(a ) a = outputs.logits print(logits.shape ) print('''First values of logits:''' , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": a = torch.tensor( [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]] ) elif model_name == "upernet-swin-small": a = torch.tensor( [[-7.1_921, -7.1_921, -6.9_532], [-7.1_921, -7.1_921, -6.9_532], [-7.0_908, -7.0_908, -6.8_534]] ) elif model_name == "upernet-swin-base": a = torch.tensor( [[-6.5_851, -6.5_851, -6.4_330], [-6.5_851, -6.5_851, -6.4_330], [-6.4_763, -6.4_763, -6.3_254]] ) elif model_name == "upernet-swin-large": a = torch.tensor( [[-7.5_297, -7.5_297, -7.3_802], [-7.5_297, -7.5_297, -7.3_802], [-7.4_044, -7.4_044, -7.2_586]] ) print('''Logits:''' , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , a , 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(a ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(a ) if push_to_hub: print(F"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(F"""openmmlab/{model_name}""" ) processor.push_to_hub(F"""openmmlab/{model_name}""" ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="upernet-swin-tiny", type=str, choices=[f"""upernet-swin-{size}""" for size in ["tiny", "small", "base", "large"]], help="Name of the Swin + UperNet model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) UpperCAmelCase__ = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ = logging.get_logger(__name__) UpperCAmelCase__ = {} class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = '''llama''' __snake_case = ['''past_key_values'''] def __init__( self : Optional[Any] , __UpperCAmelCase : Union[str, Any]=32_000 , __UpperCAmelCase : str=4_096 , __UpperCAmelCase : int=11_008 , __UpperCAmelCase : Tuple=32 , __UpperCAmelCase : Optional[int]=32 , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Union[str, Any]="silu" , __UpperCAmelCase : Tuple=2_048 , __UpperCAmelCase : Optional[Any]=0.02 , __UpperCAmelCase : Any=1e-6 , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Optional[int]=0 , __UpperCAmelCase : Optional[int]=1 , __UpperCAmelCase : Optional[int]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : List[str]=False , __UpperCAmelCase : Tuple=None , **__UpperCAmelCase : Tuple , ) ->str: """simple docstring""" a = vocab_size a = max_position_embeddings a = hidden_size a = intermediate_size a = num_hidden_layers a = num_attention_heads # for backward compatibility if num_key_value_heads is None: a = num_attention_heads a = num_key_value_heads a = hidden_act a = initializer_range a = rms_norm_eps a = pretraining_tp a = use_cache a = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , tie_word_embeddings=__UpperCAmelCase , **__UpperCAmelCase , ) def __lowerCAmelCase ( self : Tuple ) ->Tuple: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , __UpperCAmelCase ) 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}""" ) a = self.rope_scaling.get('''type''' , __UpperCAmelCase ) a = self.rope_scaling.get('''factor''' , __UpperCAmelCase ) 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(__UpperCAmelCase , __UpperCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F"""`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}""" )
0
1
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : str , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : UNetaDModel , __UpperCAmelCase : DDPMScheduler , __UpperCAmelCase : Union[str, Any] , ) ->int: """simple docstring""" super().__init__() a = value_function a = unet a = scheduler a = env a = env.get_dataset() a = {} for key in self.data.keys(): try: a = self.data[key].mean() except: # noqa: E722 pass a = {} for key in self.data.keys(): try: a = self.data[key].std() except: # noqa: E722 pass a = env.observation_space.shape[0] a = env.action_space.shape[0] def __lowerCAmelCase ( self : Dict , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Dict ) ->Optional[Any]: """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def __lowerCAmelCase ( self : Any , __UpperCAmelCase : Any , __UpperCAmelCase : int ) ->Dict: """simple docstring""" return x_in * self.stds[key] + self.means[key] def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : Any ) ->Any: """simple docstring""" if type(__UpperCAmelCase ) is dict: return {k: self.to_torch(__UpperCAmelCase ) for k, v in x_in.items()} elif torch.is_tensor(__UpperCAmelCase ): return x_in.to(self.unet.device ) return torch.tensor(__UpperCAmelCase , device=self.unet.device ) def __lowerCAmelCase ( self : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] ) ->Tuple: """simple docstring""" for key, val in cond.items(): a = val.clone() return x_in def __lowerCAmelCase ( self : str , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[Any] ) ->List[Any]: """simple docstring""" a = x.shape[0] a = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model a = torch.full((batch_size,) , __UpperCAmelCase , device=self.unet.device , dtype=torch.long ) for _ in range(__UpperCAmelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models a = self.value_function(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample a = torch.autograd.grad([y.sum()] , [x] )[0] a = self.scheduler._get_variance(__UpperCAmelCase ) a = torch.exp(0.5 * posterior_variance ) a = model_std * grad a = 0 a = x.detach() a = x + scale * grad a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.unet(x.permute(0 , 2 , 1 ) , __UpperCAmelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg a = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , predict_epsilon=__UpperCAmelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) return x, y def __call__( self : Optional[int] , __UpperCAmelCase : List[str] , __UpperCAmelCase : Dict=64 , __UpperCAmelCase : Union[str, Any]=32 , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : int=0.1 ) ->Optional[Any]: """simple docstring""" a = self.normalize(__UpperCAmelCase , '''observations''' ) a = obs[None].repeat(__UpperCAmelCase , axis=0 ) a = {0: self.to_torch(__UpperCAmelCase )} a = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) a = randn_tensor(__UpperCAmelCase , device=self.unet.device ) a = self.reset_xa(__UpperCAmelCase , __UpperCAmelCase , self.action_dim ) a = self.to_torch(__UpperCAmelCase ) # run the diffusion process a , a = self.run_diffusion(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) # sort output trajectories by value a = y.argsort(0 , descending=__UpperCAmelCase ).squeeze() a = x[sorted_idx] a = sorted_values[:, :, : self.action_dim] a = actions.detach().cpu().numpy() a = self.de_normalize(__UpperCAmelCase , key='''actions''' ) # select the action with the highest value if y is not None: a = 0 else: # if we didn't run value guiding, select a random action a = np.random.randint(0 , __UpperCAmelCase ) a = denorm_actions[selected_index, 0] return denorm_actions
0
from __future__ import annotations UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "MIT" UpperCAmelCase__ = "1.0.0" UpperCAmelCase__ = "Muhammad Umer Farooq" UpperCAmelCase__ = "[email protected]" UpperCAmelCase__ = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class lowercase_ ( lowercase ): '''simple docstring''' def __init__( self : Union[str, Any] , __UpperCAmelCase : str ) ->None: """simple docstring""" super().__init__() a = [] a = domain def __lowerCAmelCase ( self : List[str] , __UpperCAmelCase : str , __UpperCAmelCase : list[tuple[str, str | None]] ) ->None: """simple docstring""" 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: a = parse.urljoin(self.domain , __UpperCAmelCase ) self.urls.append(__UpperCAmelCase ) def _a ( a :str ) -> str: return ".".join(get_sub_domain_name(a ).split('''.''' )[-2:] ) def _a ( a :str ) -> str: return parse.urlparse(a ).netloc def _a ( a :str = "https://github.com" ) -> list[str]: a = get_domain_name(a ) # Initialize the parser a = Parser(a ) try: # Open URL a = requests.get(a ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a = requests.get(a ) # Get the valid email. a = re.findall('''[a-zA-Z0-9]+@''' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(a ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(a ) if __name__ == "__main__": UpperCAmelCase__ = emails_from_url("https://github.com") print(f"""{len(emails)} emails found:""") print("\n".join(sorted(emails)))
0
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() UpperCAmelCase__ = logging.get_logger(__name__) def _a ( a :Union[str, Any] , a :List[str] , a :List[str] ) -> int: a = UniSpeechSatForSequenceClassification.from_pretrained(a , config=a ) a = downstream_dict['''projector.weight'''] a = downstream_dict['''projector.bias'''] a = downstream_dict['''model.post_net.linear.weight'''] a = downstream_dict['''model.post_net.linear.bias'''] return model def _a ( a :Any , a :str , a :List[Any] ) -> Tuple: a = UniSpeechSatForAudioFrameClassification.from_pretrained(a , config=a ) a = downstream_dict['''model.linear.weight'''] a = downstream_dict['''model.linear.bias'''] return model def _a ( a :Dict , a :int , a :Union[str, Any] ) -> Dict: a = UniSpeechSatForXVector.from_pretrained(a , config=a ) a = downstream_dict['''connector.weight'''] a = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): a = downstream_dict[ F"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] a = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] a = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] a = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] a = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] a = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] a = downstream_dict['''objective.W'''] return model @torch.no_grad() def _a ( a :str , a :List[Any] , a :Optional[int] , a :Any ) -> str: a = torch.load(a , map_location='''cpu''' ) a = checkpoint['''Downstream'''] a = UniSpeechSatConfig.from_pretrained(a ) a = WavaVecaFeatureExtractor.from_pretrained( a , return_attention_mask=a , do_normalize=a ) a = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): a = convert_classification(a , a , a ) elif arch.endswith('''ForAudioFrameClassification''' ): a = convert_diarization(a , a , a ) elif arch.endswith('''ForXVector''' ): a = convert_xvector(a , a , a ) else: raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: a = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(a ) hf_model.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") UpperCAmelCase__ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
0
import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) UpperCAmelCase__ = logging.getLogger() def _a ( ) -> Optional[int]: a = argparse.ArgumentParser() parser.add_argument('''-f''' ) a = parser.parse_args() return args.f def _a ( a :Any ) -> Tuple: a = {} a = os.path.join(a , '''all_results.json''' ) if os.path.exists(a ): with open(a , '''r''' ) as f: a = json.load(a ) else: raise ValueError(F"""can't find {path}""" ) return results def _a ( ) -> int: a = torch.cuda.is_available() and torch_device == '''cuda''' return is_using_cuda and is_apex_available() UpperCAmelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowercase_ ( lowercase ): '''simple docstring''' @classmethod def __lowerCAmelCase ( cls : str ) ->Tuple: """simple docstring""" a = tempfile.mkdtemp() a = os.path.join(cls.tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) a = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def __lowerCAmelCase ( cls : Optional[int] ) ->Union[str, Any]: """simple docstring""" shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''glue_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 100 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''clm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertLess(result['''perplexity'''] , 42 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''mlm_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->str: """simple docstring""" a = 7 if get_gpu_count() > 1 else 2 a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) self.assertLess(result['''train_loss'''] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''ner_no_trainer''' ) ) ) @unittest.skip(reason='''Fix me @muellerzr''' ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Any ) ->int: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''qa_no_trainer''' ) ) ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''swag_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Union[str, Any] ) ->Union[str, Any]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) 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(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''summarization_no_trainer''' ) ) ) @slow @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_bleu'''] , 30 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''epoch_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''translation_no_trainer''' ) ) ) @slow def __lowerCAmelCase ( self : List[str] ) ->int: """simple docstring""" a = logging.StreamHandler(sys.stdout ) logger.addHandler(__UpperCAmelCase ) a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) self.assertGreaterEqual(result['''eval_overall_accuracy'''] , 0.10 ) @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def __lowerCAmelCase ( self : Optional[Any] ) ->Tuple: """simple docstring""" a = self.get_auto_remove_tmp_dir() a = 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 ) a = get_results(__UpperCAmelCase ) # The base model scores a 25% self.assertGreaterEqual(result['''eval_accuracy'''] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''step_1''' ) ) ) self.assertTrue(os.path.exists(os.path.join(__UpperCAmelCase , '''image_classification_no_trainer''' ) ) )
0
1