code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def _lowercase( __a : int ): 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()
20
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
0
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 __A : def __init__( self :Tuple , __snake_case :int , __snake_case :int=14 , __snake_case :Tuple=7 , __snake_case :Any=True , __snake_case :Dict=True , __snake_case :Any=True , __snake_case :Optional[Any]=True , __snake_case :Optional[Any]=True , __snake_case :Dict=99 , __snake_case :Any=32 , __snake_case :int=5 , __snake_case :Any=4 , __snake_case :str=37 , __snake_case :List[Any]="gelu" , __snake_case :str=0.1 , __snake_case :str=0.1 , __snake_case :str=5_12 , __snake_case :int=16 , __snake_case :Optional[Any]=2 , __snake_case :Dict=0.02 , __snake_case :Tuple=3 , __snake_case :List[str]=4 , __snake_case :Any=None , ): '''simple docstring''' __magic_name__ : int =parent __magic_name__ : str =batch_size __magic_name__ : str =seq_length __magic_name__ : Tuple =is_training __magic_name__ : List[str] =use_token_type_ids __magic_name__ : Tuple =use_input_mask __magic_name__ : Any =use_labels __magic_name__ : str =use_mc_token_ids __magic_name__ : List[Any] =vocab_size __magic_name__ : List[str] =hidden_size __magic_name__ : Tuple =num_hidden_layers __magic_name__ : Union[str, Any] =num_attention_heads __magic_name__ : Tuple =intermediate_size __magic_name__ : Optional[int] =hidden_act __magic_name__ : Tuple =hidden_dropout_prob __magic_name__ : str =attention_probs_dropout_prob __magic_name__ : Dict =max_position_embeddings __magic_name__ : Dict =type_vocab_size __magic_name__ : Any =type_sequence_label_size __magic_name__ : Optional[Any] =initializer_range __magic_name__ : Optional[Any] =num_labels __magic_name__ : Any =num_choices __magic_name__ : List[str] =scope __magic_name__ : Optional[Any] =self.vocab_size - 1 def A__ ( self :List[Any] ): '''simple docstring''' __magic_name__ : Tuple =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Any =None if self.use_input_mask: __magic_name__ : Optional[int] =random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : Any =None if self.use_token_type_ids: __magic_name__ : int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : Tuple =None if self.use_mc_token_ids: __magic_name__ : Tuple =ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __magic_name__ : Optional[Any] =None __magic_name__ : str =None __magic_name__ : List[str] =None if self.use_labels: __magic_name__ : int =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ : List[Any] =ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ : Optional[int] =self.get_config() __magic_name__ : List[Any] =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 A__ ( self :List[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 A__ ( self :int , __snake_case :Dict , __snake_case :Optional[Any] , __snake_case :Tuple , __snake_case :Dict , __snake_case :Dict , *__snake_case :str ): '''simple docstring''' __magic_name__ : Optional[int] =CTRLModel(config=__snake_case ) model.to(__snake_case ) model.eval() model(__snake_case , token_type_ids=__snake_case , head_mask=__snake_case ) model(__snake_case , token_type_ids=__snake_case ) __magic_name__ : int =model(__snake_case ) 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 A__ ( self :Dict , __snake_case :Tuple , __snake_case :str , __snake_case :Dict , __snake_case :Tuple , __snake_case :List[Any] , *__snake_case :List[str] ): '''simple docstring''' __magic_name__ : str =CTRLLMHeadModel(__snake_case ) model.to(__snake_case ) model.eval() __magic_name__ : Any =model(__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def A__ ( self :Optional[int] ): '''simple docstring''' __magic_name__ : Tuple =self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) : Any =config_and_inputs __magic_name__ : str ={"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def A__ ( self :Union[str, Any] , __snake_case :Union[str, Any] , __snake_case :str , __snake_case :Optional[int] , __snake_case :str , *__snake_case :List[str] ): '''simple docstring''' __magic_name__ : Tuple =self.num_labels __magic_name__ : str =CTRLForSequenceClassification(__snake_case ) model.to(__snake_case ) model.eval() __magic_name__ : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ : Any =model(__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): UpperCamelCase = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () UpperCamelCase = (CTRLLMHeadModel,) if is_torch_available() else () UpperCamelCase = ( { """feature-extraction""": CTRLModel, """text-classification""": CTRLForSequenceClassification, """text-generation""": CTRLLMHeadModel, """zero-shot""": CTRLForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def A__ ( self :Any , __snake_case :List[Any] , __snake_case :List[str] , __snake_case :List[Any] , __snake_case :List[str] , __snake_case :int ): '''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 A__ ( self :str ): '''simple docstring''' __magic_name__ : Any =CTRLModelTester(self ) __magic_name__ : Optional[int] =ConfigTester(self , config_class=__snake_case , n_embd=37 ) def A__ ( self :Any ): '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def A__ ( self :Any ): '''simple docstring''' self.config_tester.run_common_tests() def A__ ( self :Union[str, Any] ): '''simple docstring''' __magic_name__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*__snake_case ) def A__ ( self :Dict ): '''simple docstring''' __magic_name__ : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__snake_case ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def A__ ( self :Tuple ): '''simple docstring''' pass @slow def A__ ( self :Any ): '''simple docstring''' for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Tuple =CTRLModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def A__ ( self :List[Any] ): '''simple docstring''' pass @require_torch class __A ( unittest.TestCase ): def A__ ( self :Dict ): '''simple docstring''' super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def A__ ( self :List[str] ): '''simple docstring''' __magic_name__ : int =CTRLLMHeadModel.from_pretrained("""ctrl""" ) model.to(__snake_case ) __magic_name__ : Optional[Any] =torch.tensor( [[1_18_59, 0, 16_11, 8]] , dtype=torch.long , device=__snake_case ) # Legal the president is __magic_name__ : Optional[int] =[ 1_18_59, 0, 16_11, 8, 5, 1_50, 2_64_49, 2, 19, 3_48, 4_69, 3, 25_95, 48, 2_07_40, 24_65_33, 24_65_33, 19, 30, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __magic_name__ : str =model.generate(__snake_case , do_sample=__snake_case ) self.assertListEqual(output_ids[0].tolist() , __snake_case )
21
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
'''simple docstring''' import argparse import copy def snake_case_ (UpperCamelCase : Tuple ): '''simple docstring''' _a = {} with open(UpperCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: _a = [] _list.append([line.split()[1], line.split()[2]] ) _a = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: _a = [] _list.append([line.split()[0], line.split()[2]] ) _a = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : List[str] ): '''simple docstring''' with open(UpperCamelCase ) as f: _a = f.read(1 ) _a = start_node _a = [] _a = start_node _a = 0 while visiting not in first_solution: _a = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(UpperCamelCase ) and k[0] not in first_solution: _a = k[1] _a = k[0] first_solution.append(UpperCamelCase ) _a = distance_of_first_solution + int(UpperCamelCase ) _a = best_node first_solution.append(UpperCamelCase ) _a = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 _a = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def snake_case_ (UpperCamelCase : Tuple , UpperCamelCase : List[str] ): '''simple docstring''' _a = [] for n in solution[1:-1]: _a = solution.index(UpperCamelCase ) for kn in solution[1:-1]: _a = solution.index(UpperCamelCase ) if n == kn: continue _a = copy.deepcopy(UpperCamelCase ) _a = kn _a = n _a = 0 for k in _tmp[:-1]: _a = _tmp[_tmp.index(UpperCamelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: _a = distance + int(i[1] ) _tmp.append(UpperCamelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) _a = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda UpperCamelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def snake_case_ (UpperCamelCase : List[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Dict ): '''simple docstring''' _a = 1 _a = first_solution _a = [] _a = distance_of_first_solution _a = solution while count <= iters: _a = find_neighborhood(UpperCamelCase , UpperCamelCase ) _a = 0 _a = neighborhood[index_of_best_solution] _a = len(UpperCamelCase ) - 1 _a = False while not found: _a = 0 while i < len(UpperCamelCase ): if best_solution[i] != solution[i]: _a = best_solution[i] _a = solution[i] break _a = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) _a = True _a = best_solution[:-1] _a = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: _a = cost _a = solution else: _a = index_of_best_solution + 1 _a = neighborhood[index_of_best_solution] if len(UpperCamelCase ) >= size: tabu_list.pop(0 ) _a = count + 1 return best_solution_ever, best_cost def snake_case_ (UpperCamelCase : str=None ): '''simple docstring''' _a = generate_neighbours(args.File ) _a , _a = generate_first_solution( args.File , UpperCamelCase ) _a , _a = tabu_search( UpperCamelCase , UpperCamelCase , UpperCamelCase , args.Iterations , args.Size , ) print(f'Best solution: {best_sol}, with total distance: {best_cost}.' ) if __name__ == "__main__": _snake_case : Dict = argparse.ArgumentParser(description='Tabu Search') parser.add_argument( '-f', '--File', type=str, help='Path to the file containing the data', required=True, ) parser.add_argument( '-i', '--Iterations', type=int, help='How many iterations the algorithm should perform', required=True, ) parser.add_argument( '-s', '--Size', type=int, help='Size of the tabu list', required=True ) # Pass the arguments to main method main(parser.parse_args())
22
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def _snake_case (__lowercase , __lowercase): UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' UpperCamelCase_ = Image.open(requests.get(__lowercase , stream=__lowercase).raw).convert('RGB') UpperCamelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC), transforms.ToTensor(), transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073) , (0.26_862_954, 0.26_130_258, 0.27_577_711)), ]) UpperCamelCase_ = transform(__lowercase).unsqueeze(0).to(__lowercase) return image def _snake_case (__lowercase): if "visual_encoder" in key: UpperCamelCase_ = re.sub('visual_encoder*' , 'vision_model.encoder' , __lowercase) if "blocks" in key: UpperCamelCase_ = re.sub(r'blocks' , 'layers' , __lowercase) if "attn" in key: UpperCamelCase_ = re.sub(r'attn' , 'self_attn' , __lowercase) if "norm1" in key: UpperCamelCase_ = re.sub(r'norm1' , 'layer_norm1' , __lowercase) if "norm2" in key: UpperCamelCase_ = re.sub(r'norm2' , 'layer_norm2' , __lowercase) if "encoder.norm" in key: UpperCamelCase_ = re.sub(r'encoder.norm' , 'post_layernorm' , __lowercase) if "encoder.patch_embed.proj" in key: UpperCamelCase_ = re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , __lowercase) if "encoder.pos_embed" in key: UpperCamelCase_ = re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , __lowercase) if "encoder.cls_token" in key: UpperCamelCase_ = re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , __lowercase) if "self_attn" in key: UpperCamelCase_ = re.sub(r'self_attn.proj' , 'self_attn.projection' , __lowercase) return key @torch.no_grad() def _snake_case (__lowercase , __lowercase=None): if config_path is not None: UpperCamelCase_ = BlipConfig.from_pretrained(__lowercase) else: UpperCamelCase_ = BlipConfig(projection_dim=512 , text_config={} , vision_config={}) UpperCamelCase_ = BlipForConditionalGeneration(__lowercase).eval() UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' UpperCamelCase_ = blip_decoder(pretrained=__lowercase , image_size=384 , vit='base') UpperCamelCase_ = pt_model.eval() UpperCamelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value hf_model.load_state_dict(__lowercase) UpperCamelCase_ = 384 UpperCamelCase_ = load_demo_image(image_size=__lowercase , device='cpu') UpperCamelCase_ = BertTokenizer.from_pretrained('bert-base-uncased') UpperCamelCase_ = tokenizer(['a picture of']).input_ids UpperCamelCase_ = hf_model.generate(__lowercase , __lowercase) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] UpperCamelCase_ = hf_model.generate(__lowercase) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(__lowercase) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCamelCase_ = ( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) UpperCamelCase_ = blip_vqa(pretrained=__lowercase , image_size=__lowercase , vit='base') vqa_model.eval() UpperCamelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value UpperCamelCase_ = BlipForQuestionAnswering(__lowercase) hf_vqa_model.load_state_dict(__lowercase) UpperCamelCase_ = ['How many dogs are in this image?'] UpperCamelCase_ = tokenizer(__lowercase , return_tensors='pt').input_ids UpperCamelCase_ = hf_vqa_model.generate(__lowercase , __lowercase) print(tokenizer.decode(answer[0])) assert tokenizer.decode(answer[0]) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa') UpperCamelCase_ = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' UpperCamelCase_ = blip_itm(pretrained=__lowercase , image_size=__lowercase , vit='base') itm_model.eval() UpperCamelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCamelCase_ = modified_state_dict.pop(__lowercase) UpperCamelCase_ = rename_key(__lowercase) UpperCamelCase_ = value UpperCamelCase_ = BlipForImageTextRetrieval(__lowercase) UpperCamelCase_ = ['A picture of a woman with a dog sitting in a beach'] UpperCamelCase_ = tokenizer( __lowercase , return_tensors='pt' , padding='max_length' , truncation=__lowercase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(__lowercase) hf_itm_model.eval() UpperCamelCase_ = hf_itm_model(__lowercase , __lowercase , use_itm_head=__lowercase) UpperCamelCase_ = hf_itm_model(__lowercase , __lowercase , use_itm_head=__lowercase) assert out[0].item() == 0.2_110_687_494_277_954 assert torch.nn.functional.softmax(out_itm[0] , dim=1)[:, 1].item() == 0.45_698_845_386_505_127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm') if __name__ == "__main__": snake_case__ : Tuple = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") snake_case__ : Optional[Any] = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
23
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging UpperCAmelCase_ : Any = logging.get_logger(__name__) UpperCAmelCase_ : int = { '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json''', # See all Marian models at https://huggingface.co/models?filter=marian } class lowerCAmelCase ( __lowerCAmelCase): __lowercase : int = '''marian''' __lowercase : Any = ['''past_key_values'''] __lowercase : List[Any] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self , __SCREAMING_SNAKE_CASE=5_8101 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=1024 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=4096 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=12 , __SCREAMING_SNAKE_CASE=4096 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=1024 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=5_8100 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=5_8100 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ) -> str: '''simple docstring''' __snake_case = vocab_size __snake_case = decoder_vocab_size or vocab_size __snake_case = max_position_embeddings __snake_case = d_model __snake_case = encoder_ffn_dim __snake_case = encoder_layers __snake_case = encoder_attention_heads __snake_case = decoder_ffn_dim __snake_case = decoder_layers __snake_case = decoder_attention_heads __snake_case = dropout __snake_case = attention_dropout __snake_case = activation_dropout __snake_case = activation_function __snake_case = init_std __snake_case = encoder_layerdrop __snake_case = decoder_layerdrop __snake_case = use_cache __snake_case = encoder_layers __snake_case = scale_embedding # scale factor will be sqrt(d_model) if True __snake_case = share_encoder_decoder_embeddings super().__init__( pad_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , is_encoder_decoder=__SCREAMING_SNAKE_CASE , decoder_start_token_id=__SCREAMING_SNAKE_CASE , forced_eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) class lowerCAmelCase ( __lowerCAmelCase): @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __snake_case = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __snake_case = {0: '''batch'''} __snake_case = {0: '''batch''', 1: '''past_decoder_sequence + sequence'''} else: __snake_case = {0: '''batch''', 1: '''decoder_sequence'''} __snake_case = {0: '''batch''', 1: '''decoder_sequence'''} if self.use_past: self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE , direction='''inputs''' ) elif self.task == "causal-lm": # TODO: figure this case out. __snake_case = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ] ) if self.use_past: __snake_case , __snake_case = self.num_layers for i in range(__SCREAMING_SNAKE_CASE ): __snake_case = {0: '''batch''', 2: '''past_sequence + sequence'''} __snake_case = {0: '''batch''', 2: '''past_sequence + sequence'''} else: __snake_case = OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}), ('''decoder_input_ids''', {0: '''batch''', 1: '''decoder_sequence'''}), ('''decoder_attention_mask''', {0: '''batch''', 1: '''decoder_sequence'''}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __snake_case = super().outputs else: __snake_case = super(__SCREAMING_SNAKE_CASE , self ).outputs if self.use_past: __snake_case , __snake_case = self.num_layers for i in range(__SCREAMING_SNAKE_CASE ): __snake_case = {0: '''batch''', 2: '''past_sequence + sequence'''} __snake_case = {0: '''batch''', 2: '''past_sequence + sequence'''} return common_outputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Generate decoder inputs __snake_case = seq_length if not self.use_past else 1 __snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __snake_case = {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} __snake_case = dict(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch __snake_case , __snake_case = common_inputs['''input_ids'''].shape __snake_case = common_inputs['''decoder_input_ids'''].shape[1] __snake_case , __snake_case = self.num_attention_heads __snake_case = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __snake_case = decoder_seq_length + 3 __snake_case = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __snake_case = torch.cat( [common_inputs['''decoder_attention_mask'''], torch.ones(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )] , dim=1 ) __snake_case = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __snake_case , __snake_case = self.num_layers __snake_case = min(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __snake_case = max(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) - min_num_layers __snake_case = '''encoder''' if num_encoder_layers > num_decoder_layers else '''decoder''' for _ in range(__SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append( ( torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE ), ) ) # TODO: test this. __snake_case = encoder_shape if remaining_side_name == '''encoder''' else decoder_shape for _ in range(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append((torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE )) ) return common_inputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case = self._generate_dummy_inputs_for_encoder_and_decoder( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch __snake_case , __snake_case = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values __snake_case = seqlen + 2 __snake_case , __snake_case = self.num_layers __snake_case , __snake_case = self.num_attention_heads __snake_case = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __snake_case = common_inputs['''attention_mask'''].dtype __snake_case = torch.cat( [common_inputs['''attention_mask'''], torch.ones(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , dtype=__SCREAMING_SNAKE_CASE )] , dim=1 ) __snake_case = [ (torch.zeros(__SCREAMING_SNAKE_CASE ), torch.zeros(__SCREAMING_SNAKE_CASE )) for _ in range(__SCREAMING_SNAKE_CASE ) ] return common_inputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' __snake_case = compute_effective_axis_dimension( __SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __snake_case = tokenizer.num_special_tokens_to_add(__SCREAMING_SNAKE_CASE ) __snake_case = compute_effective_axis_dimension( __SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__SCREAMING_SNAKE_CASE ) # Generate dummy inputs according to compute batch and sequence __snake_case = [''' '''.join([tokenizer.unk_token] ) * seq_length] * batch_size __snake_case = dict(tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) ) return common_inputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = -1 , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __snake_case = self._generate_dummy_inputs_for_default_and_seqaseq_lm( __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , seq_length=__SCREAMING_SNAKE_CASE , is_pair=__SCREAMING_SNAKE_CASE , framework=__SCREAMING_SNAKE_CASE ) else: __snake_case = self._generate_dummy_inputs_for_causal_lm( __SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , seq_length=__SCREAMING_SNAKE_CASE , is_pair=__SCREAMING_SNAKE_CASE , framework=__SCREAMING_SNAKE_CASE ) return common_inputs def lowerCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: __snake_case = super()._flatten_past_key_values_(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: __snake_case = super(__SCREAMING_SNAKE_CASE , self )._flatten_past_key_values_( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @property def lowerCAmelCase ( self ) -> float: '''simple docstring''' return 1E-4
24
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =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_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
from collections import Counter from timeit import timeit def lowerCamelCase__ ( _a = "" , ): return sum(c % 2 for c in Counter(input_str.replace(" " , "").lower()).values()) < 2 def lowerCamelCase__ ( _a = ""): if len(_a) == 0: return True SCREAMING_SNAKE_CASE : List[Any] = input_str.replace(" " , "").lower() # character_freq_dict: Stores the frequency of every character in the input string SCREAMING_SNAKE_CASE : dict[str, int] = {} for character in lower_case_input_str: SCREAMING_SNAKE_CASE : Optional[int] = character_freq_dict.get(_a , 0) + 1 SCREAMING_SNAKE_CASE : Optional[Any] = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def lowerCamelCase__ ( _a = ""): print("\nFor string = " , _a , ":") print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(_a) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(_a) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": a_ = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) a_ = can_string_be_rearranged_as_palindrome_counter(check_str) print(F'''{check_str} can {"" if status else "not "}be rearranged as a palindrome''')
25
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =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() = }')
59
0
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig __UpperCamelCase = { "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class _A ( __lowercase ): lowercase__: int = '''ernie_m''' lowercase__: Dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self : Optional[int] , __magic_name__ : int = 25_00_02 , __magic_name__ : int = 7_68 , __magic_name__ : int = 12 , __magic_name__ : int = 12 , __magic_name__ : int = 30_72 , __magic_name__ : str = "gelu" , __magic_name__ : float = 0.1 , __magic_name__ : float = 0.1 , __magic_name__ : int = 5_14 , __magic_name__ : float = 0.02 , __magic_name__ : int = 1 , __magic_name__ : float = 1E-05 , __magic_name__ : Union[str, Any]=None , __magic_name__ : List[Any]=False , __magic_name__ : Union[str, Any]=0.0 , **__magic_name__ : Optional[Any] , ) -> Tuple: """simple docstring""" super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) __snake_case : List[Any] = vocab_size __snake_case : Dict = hidden_size __snake_case : Optional[Any] = num_hidden_layers __snake_case : List[Any] = num_attention_heads __snake_case : Any = intermediate_size __snake_case : Tuple = hidden_act __snake_case : Optional[Any] = hidden_dropout_prob __snake_case : Optional[int] = attention_probs_dropout_prob __snake_case : Optional[Any] = max_position_embeddings __snake_case : Optional[Any] = initializer_range __snake_case : Optional[Any] = layer_norm_eps __snake_case : Optional[int] = classifier_dropout __snake_case : Any = is_decoder __snake_case : Tuple = act_dropout
26
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate __A : Dict = trt.Logger(trt.Logger.WARNING) __A : Dict = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) __A : List[str] = logging.getLogger(__name__) __A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--onnx_model_path", default=None, type=str, required=True, help="Path to ONNX model: ", ) parser.add_argument( "--output_dir", default=None, type=str, required=True, help="The output directory where the model checkpoints and predictions will be written.", ) # Other parameters parser.add_argument( "--tokenizer_name", default="", type=str, required=True, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--version_2_with_negative", action="store_true", help="If true, the SQuAD examples contain some that do not have an answer.", ) parser.add_argument( "--null_score_diff_threshold", type=float, default=0.0, help="If null_score - best_non_null is greater than the threshold predict null.", ) parser.add_argument( "--max_seq_length", default=384, type=int, help=( "The maximum total input sequence length after WordPiece tokenization. Sequences " "longer than this will be truncated, and sequences shorter than this will be padded." ), ) parser.add_argument( "--doc_stride", default=128, type=int, help="When splitting up a long document into chunks, how much stride to take between chunks.", ) parser.add_argument("--per_device_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.") parser.add_argument( "--n_best_size", default=20, type=int, help="The total number of n-best predictions to generate in the nbest_predictions.json output file.", ) parser.add_argument( "--max_answer_length", default=30, type=int, help=( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ), ) parser.add_argument("--seed", type=int, default=42, help="random seed for initialization") parser.add_argument( "--dataset_name", type=str, default=None, required=True, help="The name of the dataset to use (via the datasets library).", ) parser.add_argument( "--dataset_config_name", type=str, default=None, help="The configuration name of the dataset to use (via the datasets library).", ) parser.add_argument( "--preprocessing_num_workers", type=int, default=4, help="A csv or a json file containing the training data." ) parser.add_argument("--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets") parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision instead of 32-bit", ) parser.add_argument( "--int8", action="store_true", help="Whether to use INT8", ) __A : Tuple = parser.parse_args() if args.tokenizer_name: __A : List[str] = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) logger.info("Training/evaluation parameters %s", args) __A : Any = args.per_device_eval_batch_size __A : Tuple = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties __A : str = True __A : List[str] = "temp_engine/bert-fp32.engine" if args.fpaa: __A : Union[str, Any] = "temp_engine/bert-fp16.engine" if args.inta: __A : int = "temp_engine/bert-int8.engine" # import ONNX file if not os.path.exists("temp_engine"): os.makedirs("temp_engine") __A : Any = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, "rb") as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network __A : Dict = [network.get_input(i) for i in range(network.num_inputs)] __A : Optional[Any] = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: __A : Any = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) __A : int = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) __A : str = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, "wb") as f: f.write(engine.serialize()) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _A = np.asarray(inputs['input_ids'] , dtype=np.intaa ) _A = np.asarray(inputs['attention_mask'] , dtype=np.intaa ) _A = np.asarray(inputs['token_type_ids'] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , _SCREAMING_SNAKE_CASE ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , _SCREAMING_SNAKE_CASE ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , _SCREAMING_SNAKE_CASE ) # start time _A = time.time() # Run inference context.execute_async( bindings=[int(_SCREAMING_SNAKE_CASE ) for d_inp in d_inputs] + [int(_SCREAMING_SNAKE_CASE ), int(_SCREAMING_SNAKE_CASE )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) cuda.memcpy_dtoh_async(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Synchronize the stream and take time stream.synchronize() # end time _A = time.time() _A = end_time - start_time _A = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. __A : Union[str, Any] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. __A : List[str] = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError("Evaluation requires a dataset name") # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. __A : Any = raw_datasets["validation"].column_names __A : Any = "question" if "question" in column_names else column_names[0] __A : List[Any] = "context" if "context" in column_names else column_names[1] __A : List[str] = "answers" if "answers" in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). __A : Dict = tokenizer.padding_side == "right" if args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the" f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) __A : Union[str, Any] = min(args.max_seq_length, tokenizer.model_max_length) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _A = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. _A = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='only_second' if pad_on_right else 'only_first' , max_length=_SCREAMING_SNAKE_CASE , stride=args.doc_stride , return_overflowing_tokens=_SCREAMING_SNAKE_CASE , return_offsets_mapping=_SCREAMING_SNAKE_CASE , padding='max_length' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. _A = tokenized_examples.pop('overflow_to_sample_mapping' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. _A = [] for i in range(len(tokenized_examples['input_ids'] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). _A = tokenized_examples.sequence_ids(_SCREAMING_SNAKE_CASE ) _A = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. _A = sample_mapping[i] tokenized_examples["example_id"].append(examples['id'][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. _A = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['offset_mapping'][i] ) ] return tokenized_examples __A : List[str] = raw_datasets["validation"] # Validation Feature Creation __A : List[str] = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc="Running tokenizer on validation dataset", ) __A : str = default_data_collator __A : List[Any] = eval_dataset.remove_columns(["example_id", "offset_mapping"]) __A : int = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="eval" ) -> Optional[Any]: """simple docstring""" _A = postprocess_qa_predictions( examples=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , predictions=_SCREAMING_SNAKE_CASE , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=_SCREAMING_SNAKE_CASE , ) # Format the result to the format the metric expects. if args.version_2_with_negative: _A = [ {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items() ] else: _A = [{'id': k, 'prediction_text': v} for k, v in predictions.items()] _A = [{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=_SCREAMING_SNAKE_CASE , label_ids=_SCREAMING_SNAKE_CASE ) __A : Any = load_metric("squad_v2" if args.version_2_with_negative else "squad") # Evaluation! logger.info("Loading ONNX model %s for evaluation", args.onnx_model_path) with open(engine_name, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def __lowerCAmelCase( _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" return trt.volume(engine.get_binding_shape(_SCREAMING_SNAKE_CASE ) ) * engine.get_binding_dtype(_SCREAMING_SNAKE_CASE ).itemsize # Allocate device memory for inputs and outputs. __A : List[str] = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer __A : Tuple = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) __A : Union[str, Any] = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) __A : List[str] = cuda.mem_alloc(h_outputa.nbytes) __A : Optional[Any] = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. __A : int = cuda.Stream() # Evaluation logger.info("***** Running Evaluation *****") logger.info(f" Num examples = {len(eval_dataset)}") logger.info(f" Batch size = {args.per_device_eval_batch_size}") __A : int = 0.0 __A : Optional[Any] = 0 __A : Union[str, Any] = timeit.default_timer() __A : int = None for step, batch in enumerate(eval_dataloader): __A , __A : Dict = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 __A , __A : Any = outputs __A : Any = torch.tensor(start_logits) __A : Tuple = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered __A : Optional[int] = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100) __A : Optional[Any] = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100) __A : str = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) __A : int = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if all_preds is not None: __A : Dict = nested_truncate(all_preds, len(eval_dataset)) __A : Optional[Any] = timeit.default_timer() - start_time logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info("Average Inference Time = {:.3f} ms".format(total_time * 1_000 / niter)) logger.info("Total Inference Time = {:.3f} ms".format(total_time * 1_000)) logger.info("Total Number of Inference = %d", niter) __A : Optional[Any] = post_processing_function(eval_examples, eval_dataset, all_preds) __A : Optional[int] = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f"Evaluation metrics: {eval_metric}")
27
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
'''simple docstring''' from datetime import datetime as dt import os from github import Github UpperCamelCase_ = [ "good first issue", "good second issue", "good difficult issue", "feature request", "new model", "wip", ] def lowercase__( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = Github(os.environ['GITHUB_TOKEN'] ) SCREAMING_SNAKE_CASE : Tuple = g.get_repo('huggingface/transformers' ) SCREAMING_SNAKE_CASE : List[Any] = repo.get_issues(state='open' ) for issue in open_issues: SCREAMING_SNAKE_CASE : Any = sorted([comment for comment in issue.get_comments()] ,key=lambda __UpperCamelCase : i.created_at ,reverse=__UpperCamelCase ) SCREAMING_SNAKE_CASE : Optional[int] = comments[0] if len(__UpperCamelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state='closed' ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( 'This issue has been automatically marked as stale because it has not had ' 'recent activity. If you think this still needs to be addressed ' 'please comment on this thread.\n\nPlease note that issues that do not follow the ' '[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) ' 'are likely to be ignored.' ) if __name__ == "__main__": main()
28
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
"""simple docstring""" import os import re import shutil import sys import tempfile import unittest import black A_ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, """utils""")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. A_ = """ \"\"\" Output class for the scheduler's step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \"\"\" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None """ class __lowerCamelCase ( unittest.TestCase ): def UpperCAmelCase__ ( self ): lowerCamelCase_ = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , '''schedulers/''' ) ) lowerCamelCase_ = self.diffusers_dir shutil.copy( os.path.join(UpperCAmelCase , '''src/diffusers/schedulers/scheduling_ddpm.py''' ) , os.path.join(self.diffusers_dir , '''schedulers/scheduling_ddpm.py''' ) , ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = '''src/diffusers''' shutil.rmtree(self.diffusers_dir ) def UpperCAmelCase__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None ): lowerCamelCase_ = comment + f"\nclass {class_name}(nn.Module):\n" + class_code if overwrite_result is not None: lowerCamelCase_ = comment + f"\nclass {class_name}(nn.Module):\n" + overwrite_result lowerCamelCase_ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) lowerCamelCase_ = black.format_str(UpperCAmelCase , mode=UpperCAmelCase ) lowerCamelCase_ = os.path.join(self.diffusers_dir , '''new_code.py''' ) with open(UpperCAmelCase , '''w''' , newline='''\n''' ) as f: f.write(UpperCAmelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(UpperCAmelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=UpperCAmelCase ) with open(UpperCAmelCase , '''r''' ) as f: self.assertTrue(f.read() , UpperCAmelCase ) def UpperCAmelCase__ ( self ): lowerCamelCase_ = check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput''' ) self.assertEqual(UpperCAmelCase , UpperCAmelCase ) def UpperCAmelCase__ ( self ): # Base copy consistency self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , REFERENCE_CODE + '''\n''' , ) # With no empty line at the end self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput''' , '''DDPMSchedulerOutput''' , UpperCAmelCase , ) # Copy consistency with rename self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , re.sub('''DDPM''' , '''Test''' , UpperCAmelCase ) , ) # Copy consistency with a really long name lowerCamelCase_ = '''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason''' self.check_copy_consistency( f"# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}" , f"{long_class_name}SchedulerOutput" , re.sub('''Bert''' , UpperCAmelCase , UpperCAmelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test''' , '''TestSchedulerOutput''' , UpperCAmelCase , overwrite_result=re.sub('''DDPM''' , '''Test''' , UpperCAmelCase ) , )
29
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __a = logging.get_logger(__name__) __a = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'} class __a( _a ): """simple docstring""" lowerCAmelCase = '''openai-gpt''' lowerCAmelCase = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self ,_SCREAMING_SNAKE_CASE=40_478 ,_SCREAMING_SNAKE_CASE=512 ,_SCREAMING_SNAKE_CASE=768 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE="gelu" ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=1e-5 ,_SCREAMING_SNAKE_CASE=0.02 ,_SCREAMING_SNAKE_CASE="cls_index" ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=0.1 ,**_SCREAMING_SNAKE_CASE ,) -> Optional[int]: UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : int = n_positions UpperCAmelCase_ : Dict = n_embd UpperCAmelCase_ : List[str] = n_layer UpperCAmelCase_ : Optional[int] = n_head UpperCAmelCase_ : List[Any] = afn UpperCAmelCase_ : Union[str, Any] = resid_pdrop UpperCAmelCase_ : Tuple = embd_pdrop UpperCAmelCase_ : Union[str, Any] = attn_pdrop UpperCAmelCase_ : Optional[int] = layer_norm_epsilon UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : List[str] = summary_type UpperCAmelCase_ : str = summary_use_proj UpperCAmelCase_ : List[Any] = summary_activation UpperCAmelCase_ : Optional[int] = summary_first_dropout UpperCAmelCase_ : List[Any] = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
30
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
import os def UpperCAmelCase_ ( __UpperCAmelCase : str ) -> List[str]: SCREAMING_SNAKE_CASE_ = len(grid[0] ) SCREAMING_SNAKE_CASE_ = len(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(__UpperCAmelCase ): for j in range(n_rows - 3 ): SCREAMING_SNAKE_CASE_ = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] SCREAMING_SNAKE_CASE_ = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: SCREAMING_SNAKE_CASE_ = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: SCREAMING_SNAKE_CASE_ = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) SCREAMING_SNAKE_CASE_ = max( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if max_product > largest: SCREAMING_SNAKE_CASE_ = max_product return largest def UpperCAmelCase_ ( ) -> Any: SCREAMING_SNAKE_CASE_ = [] with open(os.path.dirname(__UpperCAmelCase ) + '/grid.txt' ) as file: for line in file: grid.append(line.strip('\n' ).split(' ' ) ) SCREAMING_SNAKE_CASE_ = [[int(__UpperCAmelCase ) for i in grid[j]] for j in range(len(__UpperCAmelCase ) )] return largest_product(__UpperCAmelCase ) if __name__ == "__main__": print(solution())
31
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0
def A__ ( SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : list , SCREAMING_SNAKE_CASE_ : int ) -> list: """simple docstring""" _UpperCAmelCase = len(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase = [[0] * n for i in range(SCREAMING_SNAKE_CASE_ )] for i in range(SCREAMING_SNAKE_CASE_ ): _UpperCAmelCase = y_points[i] for i in range(2 , SCREAMING_SNAKE_CASE_ ): for j in range(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): _UpperCAmelCase = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
32
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test") self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "[UNK]", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "[UNK]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase__ : List[Any] = { """configuration_rag""": ["""RagConfig"""], """retrieval_rag""": ["""RagRetriever"""], """tokenization_rag""": ["""RagTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Optional[Any] = [ """RagModel""", """RagPreTrainedModel""", """RagSequenceForGeneration""", """RagTokenForGeneration""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase__ : Any = [ """TFRagModel""", """TFRagPreTrainedModel""", """TFRagSequenceForGeneration""", """TFRagTokenForGeneration""", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase__ : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
33
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
0
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class snake_case_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self) -> Dict: UpperCamelCase = '''ylacombe/bark-small''' UpperCamelCase = tempfile.mkdtemp() UpperCamelCase = '''en_speaker_1''' UpperCamelCase = '''This is a test string''' UpperCamelCase = '''speaker_embeddings_path.json''' UpperCamelCase = '''speaker_embeddings''' def UpperCAmelCase__ ( self , **lowerCamelCase_) -> str: return AutoTokenizer.from_pretrained(self.checkpoint , **lowerCamelCase_) def UpperCAmelCase__ ( self) -> Any: shutil.rmtree(self.tmpdirname) def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = self.get_tokenizer() UpperCamelCase = BarkProcessor(tokenizer=lowerCamelCase_) processor.save_pretrained(self.tmpdirname) UpperCamelCase = BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def UpperCAmelCase__ ( self) -> Dict: UpperCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''') UpperCamelCase = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def UpperCAmelCase__ ( self) -> int: UpperCamelCase = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) UpperCamelCase = 3_5 UpperCamelCase = 2 UpperCamelCase = 8 UpperCamelCase = { '''semantic_prompt''': np.ones(lowerCamelCase_), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len)), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset UpperCamelCase = processor(text=self.input_string , voice_preset=lowerCamelCase_) UpperCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(lowerCamelCase_ , np.array([])).tolist()) # test loading voice preset from npz file UpperCamelCase = os.path.join(self.tmpdirname , '''file.npz''') np.savez(lowerCamelCase_ , **lowerCamelCase_) UpperCamelCase = processor(text=self.input_string , voice_preset=lowerCamelCase_) UpperCamelCase = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(lowerCamelCase_ , np.array([])).tolist()) # test loading voice preset from the hub UpperCamelCase = processor(text=self.input_string , voice_preset=self.voice_preset) def UpperCAmelCase__ ( self) -> Union[str, Any]: UpperCamelCase = self.get_tokenizer() UpperCamelCase = BarkProcessor(tokenizer=lowerCamelCase_) UpperCamelCase = processor(text=self.input_string) UpperCamelCase = tokenizer( self.input_string , padding='''max_length''' , max_length=2_5_6 , add_special_tokens=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , return_token_type_ids=lowerCamelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
34
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =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_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
0
import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def a ( A__ ) -> int: '''simple docstring''' return EnvironmentCommand() def a ( A__ ) -> int: '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file ) class lowercase ( _UpperCAmelCase ): @staticmethod def lowercase__ ( _lowercase : ArgumentParser ): SCREAMING_SNAKE_CASE__ : int = parser.add_parser('''env''' ) download_parser.set_defaults(func=_lowercase ) download_parser.add_argument( '''--accelerate-config_file''' , default=_lowercase , help='''The accelerate config file to use for the default values in the launching script.''' , ) download_parser.set_defaults(func=_lowercase ) def __init__( self : Any , _lowercase : int , *_lowercase : int ): SCREAMING_SNAKE_CASE__ : Any = accelerate_config_file def lowercase__ ( self : List[str] ): SCREAMING_SNAKE_CASE__ : str = '''not installed''' if is_safetensors_available(): import safetensors SCREAMING_SNAKE_CASE__ : int = safetensors.__version__ elif importlib.util.find_spec('''safetensors''' ) is not None: import safetensors SCREAMING_SNAKE_CASE__ : Any = f"""{safetensors.__version__} but is ignored because of PyTorch version too old.""" SCREAMING_SNAKE_CASE__ : int = '''not installed''' SCREAMING_SNAKE_CASE__ : List[str] = '''not found''' if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file SCREAMING_SNAKE_CASE__ : Union[str, Any] = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(_lowercase ): SCREAMING_SNAKE_CASE__ : int = load_config_from_file(self._accelerate_config_file ).to_dict() SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( '''\n'''.join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(_lowercase , _lowercase ) else f"""\t{accelerate_config}""" ) SCREAMING_SNAKE_CASE__ : Optional[Any] = '''not installed''' SCREAMING_SNAKE_CASE__ : int = '''NA''' if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Tuple = torch.__version__ SCREAMING_SNAKE_CASE__ : int = torch.cuda.is_available() SCREAMING_SNAKE_CASE__ : List[Any] = '''not installed''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '''NA''' if is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : int = tf.__version__ try: # deprecated in v2.1 SCREAMING_SNAKE_CASE__ : Tuple = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool SCREAMING_SNAKE_CASE__ : List[Any] = bool(tf.config.list_physical_devices('''GPU''' ) ) SCREAMING_SNAKE_CASE__ : int = '''not installed''' SCREAMING_SNAKE_CASE__ : List[Any] = '''not installed''' SCREAMING_SNAKE_CASE__ : List[str] = '''not installed''' SCREAMING_SNAKE_CASE__ : int = '''NA''' if is_flax_available(): import flax import jax import jaxlib SCREAMING_SNAKE_CASE__ : Optional[int] = flax.__version__ SCREAMING_SNAKE_CASE__ : Optional[int] = jax.__version__ SCREAMING_SNAKE_CASE__ : int = jaxlib.__version__ SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.lib.xla_bridge.get_backend().platform SCREAMING_SNAKE_CASE__ : Optional[Any] = { '''`transformers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''Huggingface_hub version''': huggingface_hub.__version__, '''Safetensors version''': f"""{safetensors_version}""", '''Accelerate version''': f"""{accelerate_version}""", '''Accelerate config''': f"""{accelerate_config_str}""", '''PyTorch version (GPU?)''': f"""{pt_version} ({pt_cuda_available})""", '''Tensorflow version (GPU?)''': f"""{tf_version} ({tf_cuda_available})""", '''Flax version (CPU?/GPU?/TPU?)''': f"""{flax_version} ({jax_backend})""", '''Jax version''': f"""{jax_version}""", '''JaxLib version''': f"""{jaxlib_version}""", '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(_lowercase ) ) return info @staticmethod def lowercase__ ( _lowercase : Any ): return "\n".join([f"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
35
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
0
def lowercase ( __A : int = 100 ) -> int: '''simple docstring''' snake_case : Tuple = 0 snake_case : Tuple = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
36
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
0
import sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("""Googling.....""") UpperCamelCase : Optional[int] = """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) UpperCamelCase : Any = requests.get(url, headers={"""UserAgent""": UserAgent().random}) # res.raise_for_status() with open("""project1a.html""", """wb""") as out_file: # only for knowing the class for data in res.iter_content(1_0000): out_file.write(data) UpperCamelCase : Optional[Any] = BeautifulSoup(res.text, """html.parser""") UpperCamelCase : Dict = list(soup.select(""".eZt8xd"""))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("""href""")) else: webbrowser.open(f"""https://google.com{link.get("href")}""")
37
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
0
'''simple docstring''' import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.text import TextDatasetReader from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def UpperCamelCase__ ( __magic_name__ : Any , __magic_name__ : Any ) -> str: '''simple docstring''' assert isinstance(__magic_name__ , __magic_name__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : Optional[int] ) -> str: '''simple docstring''' snake_case__ : Optional[Any] = tmp_path / """cache""" snake_case__ : List[Any] = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): snake_case__ : List[str] = TextDatasetReader(__magic_name__ , cache_dir=__magic_name__ , keep_in_memory=__magic_name__ ).read() _check_text_dataset(__magic_name__ , __magic_name__ ) @pytest.mark.parametrize( """features""" , [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ] , ) def UpperCamelCase__ ( __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : Dict ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[int] = tmp_path / """cache""" snake_case__ : List[Any] = {"""text""": """string"""} snake_case__ : List[Any] = features.copy() if features else default_expected_features snake_case__ : Union[str, Any] = ( Features({feature: Value(__magic_name__ ) for feature, dtype in features.items()} ) if features is not None else None ) snake_case__ : Dict = TextDatasetReader(__magic_name__ , features=__magic_name__ , cache_dir=__magic_name__ ).read() _check_text_dataset(__magic_name__ , __magic_name__ ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCamelCase__ ( __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] ) -> List[str]: '''simple docstring''' snake_case__ : Tuple = tmp_path / """cache""" snake_case__ : List[Any] = {"""text""": """string"""} snake_case__ : List[str] = TextDatasetReader(__magic_name__ , cache_dir=__magic_name__ , split=__magic_name__ ).read() _check_text_dataset(__magic_name__ , __magic_name__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : int , __magic_name__ : Optional[int] ) -> Optional[int]: '''simple docstring''' if issubclass(__magic_name__ , __magic_name__ ): snake_case__ : Union[str, Any] = text_path elif issubclass(__magic_name__ , __magic_name__ ): snake_case__ : Optional[int] = [text_path] snake_case__ : str = tmp_path / """cache""" snake_case__ : Any = {"""text""": """string"""} snake_case__ : int = TextDatasetReader(__magic_name__ , cache_dir=__magic_name__ ).read() _check_text_dataset(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : List[str] , __magic_name__ : Dict=("train",) ) -> Union[str, Any]: '''simple docstring''' assert isinstance(__magic_name__ , __magic_name__ ) for split in splits: snake_case__ : Optional[Any] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 1 assert dataset.column_names == ["text"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : Any ) -> List[Any]: '''simple docstring''' snake_case__ : Any = tmp_path / """cache""" snake_case__ : str = {"""text""": """string"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): snake_case__ : Optional[Any] = TextDatasetReader({"""train""": text_path} , cache_dir=__magic_name__ , keep_in_memory=__magic_name__ ).read() _check_text_datasetdict(__magic_name__ , __magic_name__ ) @pytest.mark.parametrize( """features""" , [ None, {"""text""": """string"""}, {"""text""": """int32"""}, {"""text""": """float32"""}, ] , ) def UpperCamelCase__ ( __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case__ : Dict = tmp_path / """cache""" # CSV file loses col_1 string dtype information: default now is "int64" instead of "string" snake_case__ : Any = {"""text""": """string"""} snake_case__ : Dict = features.copy() if features else default_expected_features snake_case__ : Optional[int] = ( Features({feature: Value(__magic_name__ ) for feature, dtype in features.items()} ) if features is not None else None ) snake_case__ : str = TextDatasetReader({"""train""": text_path} , features=__magic_name__ , cache_dir=__magic_name__ ).read() _check_text_datasetdict(__magic_name__ , __magic_name__ ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def UpperCamelCase__ ( __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Dict ) -> Union[str, Any]: '''simple docstring''' if split: snake_case__ : Dict = {split: text_path} else: snake_case__ : Any = """train""" snake_case__ : Union[str, Any] = {"""train""": text_path, """test""": text_path} snake_case__ : Any = tmp_path / """cache""" snake_case__ : Optional[Any] = {"""text""": """string"""} snake_case__ : Dict = TextDatasetReader(__magic_name__ , cache_dir=__magic_name__ ).read() _check_text_datasetdict(__magic_name__ , __magic_name__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() )
38
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = {'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SEWForCTC''', '''SEWForSequenceClassification''', '''SEWModel''', '''SEWPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_sew import ( SEW_PRETRAINED_MODEL_ARCHIVE_LIST, SEWForCTC, SEWForSequenceClassification, SEWModel, SEWPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
39
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { '''shi-labs/dinat-mini-in1k-224''': '''https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json''', # See all Dinat models at https://huggingface.co/models?filter=dinat } class lowerCAmelCase_ ( a__ , a__ ): UpperCAmelCase__ : List[str] = "dinat" UpperCAmelCase__ : List[Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self, SCREAMING_SNAKE_CASE_=4, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=64, SCREAMING_SNAKE_CASE_=[3, 4, 6, 5], SCREAMING_SNAKE_CASE_=[2, 4, 8, 16], SCREAMING_SNAKE_CASE_=7, SCREAMING_SNAKE_CASE_=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]], SCREAMING_SNAKE_CASE_=3.0, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=0.1, SCREAMING_SNAKE_CASE_="gelu", SCREAMING_SNAKE_CASE_=0.02, SCREAMING_SNAKE_CASE_=1e-5, SCREAMING_SNAKE_CASE_=0.0, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, **SCREAMING_SNAKE_CASE_, ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Union[str, Any] = patch_size UpperCamelCase : Optional[Any] = num_channels UpperCamelCase : List[str] = embed_dim UpperCamelCase : List[Any] = depths UpperCamelCase : int = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Tuple = num_heads UpperCamelCase : str = kernel_size UpperCamelCase : str = dilations UpperCamelCase : Union[str, Any] = mlp_ratio UpperCamelCase : Any = qkv_bias UpperCamelCase : List[Any] = hidden_dropout_prob UpperCamelCase : Union[str, Any] = attention_probs_dropout_prob UpperCamelCase : List[str] = drop_path_rate UpperCamelCase : int = hidden_act UpperCamelCase : str = layer_norm_eps UpperCamelCase : List[str] = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCamelCase : Optional[Any] = int(embed_dim * 2 ** (len(SCREAMING_SNAKE_CASE_ ) - 1) ) UpperCamelCase : Optional[int] = layer_scale_init_value UpperCamelCase : List[Any] = ['stem'] + [F"""stage{idx}""" for idx in range(1, len(SCREAMING_SNAKE_CASE_ ) + 1 )] UpperCamelCase , UpperCamelCase : Optional[Any] = get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE_, out_indices=SCREAMING_SNAKE_CASE_, stage_names=self.stage_names )
40
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
0
'''simple docstring''' def _A ( A__ , A__ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def _A ( ): """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
41
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE_ = ProphetNetTokenizer SCREAMING_SNAKE_CASE_ = False def UpperCamelCase( self ) -> int: '''simple docstring''' super().setUp() lowerCamelCase_ = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] lowerCamelCase_ = 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 UpperCamelCase( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: '''simple docstring''' lowerCamelCase_ = 'UNwant\u00E9d,running' lowerCamelCase_ = 'unwanted, running' return input_text, output_text def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class(self.vocab_file ) lowerCamelCase_ = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [9, 6, 7, 12, 10, 11] ) def UpperCamelCase( self ) -> str: '''simple docstring''' lowerCamelCase_ = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def UpperCamelCase( self ) -> Optional[Any]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> List[str]: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , strip_accents=SCREAMING_SNAKE_CASE_ ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def UpperCamelCase( self ) -> Tuple: '''simple docstring''' lowerCamelCase_ = BasicTokenizer(do_lower_case=SCREAMING_SNAKE_CASE_ , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] lowerCamelCase_ = {} for i, token in enumerate(SCREAMING_SNAKE_CASE_ ): lowerCamelCase_ = i lowerCamelCase_ = WordpieceTokenizer(vocab=SCREAMING_SNAKE_CASE_ , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) @require_torch def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) lowerCamelCase_ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] lowerCamelCase_ = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] lowerCamelCase_ = tokenizer(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ , return_tensors='pt' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = list(batch.input_ids.numpy()[0] ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def UpperCamelCase( self ) -> Dict: '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def UpperCamelCase( self ) -> Optional[int]: '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def UpperCamelCase( self ) -> List[Any]: '''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 UpperCamelCase( self ) -> List[Any]: '''simple docstring''' lowerCamelCase_ = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' ) lowerCamelCase_ = tokenizer.encode('sequence builders' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.encode('multi-sequence build' , add_special_tokens=SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ ) lowerCamelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
42
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
0
import os import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers.models.realm.configuration_realm import RealmConfig from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer class _a ( UpperCamelCase__ ): def lowerCamelCase_ ( self: Dict ) -> List[str]: """simple docstring""" lowercase__ = tempfile.mkdtemp() lowercase__ = 5 # Realm tok lowercase__ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''test''', '''question''', '''this''', '''is''', '''the''', '''first''', '''second''', '''third''', '''fourth''', '''fifth''', '''record''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] lowercase__ = os.path.join(self.tmpdirname , '''realm_tokenizer''' ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) lowercase__ = os.path.join(UpperCamelCase_ , 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] ) ) lowercase__ = os.path.join(self.tmpdirname , '''realm_block_records''' ) os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) def lowerCamelCase_ ( self: str ) -> RealmTokenizer: """simple docstring""" return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname , '''realm_tokenizer''' ) ) def lowerCamelCase_ ( self: Optional[int] ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowerCamelCase_ ( self: List[Any] ) -> List[Any]: """simple docstring""" lowercase__ = RealmConfig(num_block_records=self.num_block_records ) return config def lowerCamelCase_ ( self: str ) -> Optional[int]: """simple docstring""" lowercase__ = Dataset.from_dict( { '''id''': ['''0''', '''1'''], '''question''': ['''foo''', '''bar'''], '''answers''': [['''Foo''', '''Bar'''], ['''Bar''']], } ) return dataset def lowerCamelCase_ ( self: int ) -> Union[str, Any]: """simple docstring""" lowercase__ = np.array( [ b'''This is the first record''', b'''This is the second record''', b'''This is the third record''', b'''This is the fourth record''', b'''This is the fifth record''', b'''This is a longer longer longer record''', ] , dtype=UpperCamelCase_ , ) return block_records def lowerCamelCase_ ( self: Optional[Any] ) -> int: """simple docstring""" lowercase__ = RealmRetriever( block_records=self.get_dummy_block_records() , tokenizer=self.get_tokenizer() , ) return retriever def lowerCamelCase_ ( self: int ) -> Dict: """simple docstring""" lowercase__ = self.get_config() lowercase__ = self.get_dummy_retriever() lowercase__ = retriever.tokenizer lowercase__ = np.array([0, 3] , dtype='''long''' ) lowercase__ = tokenizer(['''Test question'''] ).input_ids lowercase__ = tokenizer( ['''the fourth'''] , add_special_tokens=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ).input_ids lowercase__ = config.reader_seq_len lowercase__ , lowercase__ , lowercase__ , lowercase__ = retriever( UpperCamelCase_ , UpperCamelCase_ , answer_ids=UpperCamelCase_ , max_length=UpperCamelCase_ , return_tensors='''np''' ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(len(UpperCamelCase_ ) , 2 ) self.assertEqual(concat_inputs.input_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.attention_mask.shape , (2, 10) ) self.assertEqual(concat_inputs.token_type_ids.shape , (2, 10) ) self.assertEqual(concat_inputs.special_tokens_mask.shape , (2, 10) ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''first''', '''record''', '''[SEP]'''] , ) self.assertEqual( tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] ) , ['''[CLS]''', '''test''', '''question''', '''[SEP]''', '''this''', '''is''', '''the''', '''fourth''', '''record''', '''[SEP]'''] , ) def lowerCamelCase_ ( self: Tuple ) -> Union[str, Any]: """simple docstring""" lowercase__ = self.get_config() lowercase__ = self.get_dummy_retriever() lowercase__ = retriever.tokenizer lowercase__ = np.array([0, 3, 5] , dtype='''long''' ) lowercase__ = tokenizer(['''Test question'''] ).input_ids lowercase__ = tokenizer( ['''the fourth''', '''longer longer'''] , add_special_tokens=UpperCamelCase_ , return_token_type_ids=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ).input_ids lowercase__ = config.reader_seq_len lowercase__ , lowercase__ , lowercase__ , lowercase__ = retriever( UpperCamelCase_ , UpperCamelCase_ , answer_ids=UpperCamelCase_ , max_length=UpperCamelCase_ , return_tensors='''np''' ) self.assertEqual([False, True, True] , UpperCamelCase_ ) self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]] , UpperCamelCase_ ) self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]] , UpperCamelCase_ ) def lowerCamelCase_ ( self: Union[str, Any] ) -> Tuple: """simple docstring""" lowercase__ = self.get_dummy_retriever() retriever.save_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) # Test local path lowercase__ = retriever.from_pretrained(os.path.join(self.tmpdirname , '''realm_block_records''' ) ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' ) # Test mocked remote path with patch('''transformers.models.realm.retrieval_realm.hf_hub_download''' ) as mock_hf_hub_download: lowercase__ = os.path.join( os.path.join(self.tmpdirname , '''realm_block_records''' ) , _REALM_BLOCK_RECORDS_FILENAME ) lowercase__ = RealmRetriever.from_pretrained('''google/realm-cc-news-pretrained-openqa''' ) self.assertEqual(retriever.block_records[0] , b'''This is the first record''' )
43
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
'''simple docstring''' def A_ ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any , _lowerCAmelCase : int=False ): """simple docstring""" if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(_lowerCAmelCase , _lowerCAmelCase ): _lowerCamelCase : int = len(set_a.intersection(_lowerCAmelCase ) ) if alternative_union: _lowerCamelCase : str = len(_lowerCAmelCase ) + len(_lowerCAmelCase ) else: _lowerCamelCase : List[Any] = len(set_a.union(_lowerCAmelCase ) ) return intersection / union if isinstance(_lowerCAmelCase , (list, tuple) ) and isinstance(_lowerCAmelCase , (list, tuple) ): _lowerCamelCase : Dict = [element for element in set_a if element in set_b] if alternative_union: _lowerCamelCase : int = len(_lowerCAmelCase ) + len(_lowerCAmelCase ) return len(_lowerCAmelCase ) / union else: _lowerCamelCase : List[Any] = set_a + [element for element in set_b if element not in set_a] return len(_lowerCAmelCase ) / len(_lowerCAmelCase ) return len(_lowerCAmelCase ) / len(_lowerCAmelCase ) return None if __name__ == "__main__": UpperCAmelCase_ : Any = {'a', 'b', 'c', 'd', 'e'} UpperCAmelCase_ : int = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
44
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class lowerCAmelCase_ ( lowercase ): """simple docstring""" _snake_case : Tuple = ["""image_processor""", """tokenizer"""] _snake_case : int = """OwlViTImageProcessor""" _snake_case : Optional[Any] = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self :Dict , lowerCamelCase__ :Tuple=None , lowerCamelCase__ :Tuple=None , **lowerCamelCase__ :List[str] ): UpperCamelCase__ :str = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , lowerCamelCase__ , ) UpperCamelCase__ :Optional[int] = kwargs.pop("""feature_extractor""" ) UpperCamelCase__ :Union[str, Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(lowerCamelCase__ , lowerCamelCase__ ) def __call__( self :Union[str, Any] , lowerCamelCase__ :Optional[Any]=None , lowerCamelCase__ :Tuple=None , lowerCamelCase__ :Optional[int]=None , lowerCamelCase__ :Union[str, Any]="max_length" , lowerCamelCase__ :Dict="np" , **lowerCamelCase__ :Tuple ): if text is None and query_images is None and images is None: raise ValueError( """You have to specify at least one text or query image or image. All three cannot be none.""" ) if text is not None: if isinstance(lowerCamelCase__ , lowerCamelCase__ ) or (isinstance(lowerCamelCase__ , lowerCamelCase__ ) and not isinstance(text[0] , lowerCamelCase__ )): UpperCamelCase__ :Any = [self.tokenizer(lowerCamelCase__ , padding=lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ )] elif isinstance(lowerCamelCase__ , lowerCamelCase__ ) and isinstance(text[0] , lowerCamelCase__ ): UpperCamelCase__ :Any = [] # Maximum number of queries across batch UpperCamelCase__ :Dict = max([len(lowerCamelCase__ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(lowerCamelCase__ ) != max_num_queries: UpperCamelCase__ :Optional[Any] = t + [""" """] * (max_num_queries - len(lowerCamelCase__ )) UpperCamelCase__ :int = self.tokenizer(lowerCamelCase__ , padding=lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ ) encodings.append(lowerCamelCase__ ) else: raise TypeError("""Input text should be a string, a list of strings or a nested list of strings""" ) if return_tensors == "np": UpperCamelCase__ :Any = np.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) UpperCamelCase__ :Any = np.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp UpperCamelCase__ :Dict = jnp.concatenate([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) UpperCamelCase__ :Union[str, Any] = jnp.concatenate([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch UpperCamelCase__ :Optional[Any] = torch.cat([encoding["""input_ids"""] for encoding in encodings] , dim=0 ) UpperCamelCase__ :Any = torch.cat([encoding["""attention_mask"""] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf UpperCamelCase__ :Optional[int] = tf.stack([encoding["""input_ids"""] for encoding in encodings] , axis=0 ) UpperCamelCase__ :Optional[Any] = tf.stack([encoding["""attention_mask"""] for encoding in encodings] , axis=0 ) else: raise ValueError("""Target return tensor type could not be returned""" ) UpperCamelCase__ :Optional[int] = BatchEncoding() UpperCamelCase__ :List[Any] = input_ids UpperCamelCase__ :Optional[int] = attention_mask if query_images is not None: UpperCamelCase__ :List[Any] = BatchEncoding() UpperCamelCase__ :int = self.image_processor( lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ ).pixel_values UpperCamelCase__ :List[Any] = query_pixel_values if images is not None: UpperCamelCase__ :Union[str, Any] = self.image_processor(lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ ) if text is not None and images is not None: UpperCamelCase__ :int = image_features.pixel_values return encoding elif query_images is not None and images is not None: UpperCamelCase__ :Dict = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**lowerCamelCase__ ) , tensor_type=lowerCamelCase__ ) def __a ( self :List[Any] , *lowerCamelCase__ :Optional[Any] , **lowerCamelCase__ :List[str] ): return self.image_processor.post_process(*lowerCamelCase__ , **lowerCamelCase__ ) def __a ( self :List[str] , *lowerCamelCase__ :Union[str, Any] , **lowerCamelCase__ :Tuple ): return self.image_processor.post_process_object_detection(*lowerCamelCase__ , **lowerCamelCase__ ) def __a ( self :Optional[int] , *lowerCamelCase__ :Tuple , **lowerCamelCase__ :int ): return self.image_processor.post_process_image_guided_detection(*lowerCamelCase__ , **lowerCamelCase__ ) def __a ( self :int , *lowerCamelCase__ :Dict , **lowerCamelCase__ :Any ): return self.tokenizer.batch_decode(*lowerCamelCase__ , **lowerCamelCase__ ) def __a ( self :List[Any] , *lowerCamelCase__ :Optional[int] , **lowerCamelCase__ :List[Any] ): return self.tokenizer.decode(*lowerCamelCase__ , **lowerCamelCase__ ) @property def __a ( self :List[Any] ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , lowerCamelCase__ , ) return self.image_processor_class @property def __a ( self :Dict ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , lowerCamelCase__ , ) return self.image_processor
45
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
"""simple docstring""" from __future__ import annotations from typing import Any class A_ : def __init__( self: Tuple ,__lowerCAmelCase: int = 6 ): '''simple docstring''' _lowerCamelCase : Node | None = None _lowerCamelCase : Node | None = None self.create_linked_list(__lowerCAmelCase ) def _lowercase ( self: Dict ,__lowerCAmelCase: int ): '''simple docstring''' _lowerCamelCase : List[Any] = Node() _lowerCamelCase : Optional[int] = current_node _lowerCamelCase : Any = current_node _lowerCamelCase : int = current_node for _ in range(1 ,__lowerCAmelCase ): _lowerCamelCase : Union[str, Any] = Node() _lowerCamelCase : Any = current_node _lowerCamelCase : Tuple = previous_node _lowerCamelCase : Optional[Any] = current_node _lowerCamelCase : Union[str, Any] = self.front _lowerCamelCase : Any = previous_node def _lowercase ( self: Optional[Any] ): '''simple docstring''' return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _lowercase ( self: Any ): '''simple docstring''' self.check_can_perform_operation() return self.front.data if self.front else None def _lowercase ( self: List[Any] ,__lowerCAmelCase: Any ): '''simple docstring''' if self.rear is None: return self.check_is_full() if not self.is_empty(): _lowerCamelCase : List[str] = self.rear.next if self.rear: _lowerCamelCase : List[str] = data def _lowercase ( self: Union[str, Any] ): '''simple docstring''' self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: _lowerCamelCase : Any = self.front.data _lowerCamelCase : Dict = None return data _lowerCamelCase : List[Any] = self.front _lowerCamelCase : Optional[Any] = old_front.next _lowerCamelCase : str = old_front.data _lowerCamelCase : List[str] = None return data def _lowercase ( self: List[str] ): '''simple docstring''' if self.is_empty(): raise Exception("Empty Queue" ) def _lowercase ( self: Dict ): '''simple docstring''' if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class A_ : def __init__( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : Any | None = None _lowerCamelCase : Node | None = None _lowerCamelCase : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
46
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =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_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ = TypeVar('''T''') def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (position - 1) // 2 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 1 def UpperCAmelCase__ ( lowerCamelCase_ : int ): return (2 * position) + 2 class _UpperCamelCase( Generic[T] ): def __init__( self : List[str] ): '''simple docstring''' __a : list[tuple[T, int]] = [] __a : dict[T, int] = {} __a : int = 0 def __len__( self : Any ): '''simple docstring''' return self.elements def __repr__( self : Any ): '''simple docstring''' return str(self.heap ) def __lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' return self.elements == 0 def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.heap.append((elem, weight) ) __a : List[Any] = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Tuple ): '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __a , __a : Union[str, Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __a , __a : Dict = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __lowerCAmelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : List[Any] = self.position_map[elem] __a : str = (elem, weight) if position > 0: __a : Tuple = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : Dict = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : List[Any] = self.position_map[elem] if curr_pos == 0: return None __a : List[str] = get_parent_position(SCREAMING_SNAKE_CASE__ ) __a , __a : str = self.heap[curr_pos] __a , __a : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' __a : int = self.position_map[elem] __a , __a : Optional[Any] = self.heap[curr_pos] __a : Tuple = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __a , __a : str = self.heap[child_left_position] __a , __a : List[str] = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __a , __a : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __a , __a : Union[str, Any] = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __lowerCAmelCase ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Optional[Any] = self.heap[nodea_pos][0] __a : str = self.heap[nodea_pos][0] __a , __a : int = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __a : str = nodea_pos __a : Optional[int] = nodea_pos class _UpperCamelCase( Generic[T] ): def __init__( self : List[Any] ): '''simple docstring''' __a : dict[T, dict[T, int]] = {} __a : int = 0 def __repr__( self : Tuple ): '''simple docstring''' return str(self.connections ) def __len__( self : Dict ): '''simple docstring''' return self.nodes def __lowerCAmelCase ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ): '''simple docstring''' if node not in self.connections: __a : Tuple = {} self.nodes += 1 def __lowerCAmelCase ( self : Any , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = weight __a : Any = weight def UpperCAmelCase__ ( lowerCamelCase_ : GraphUndirectedWeighted[T] , ): __a : dict[T, int] = {node: maxsize for node in graph.connections} __a : dict[T, T | None] = {node: None for node in graph.connections} __a : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCamelCase_ , lowerCamelCase_ ) if priority_queue.is_empty(): return dist, parent # initialization __a : Optional[int] = priority_queue.extract_min() __a : int = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : str = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Optional[int] = node # running prim's algorithm while not priority_queue.is_empty(): __a : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __a : Tuple = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCamelCase_ , dist[neighbour] ) __a : Dict = node return dist, parent
47
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =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() = }')
59
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[Any] = { "tiiuae/falcon-40b": "https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json", "tiiuae/falcon-7b": "https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = 'falcon' snake_case__ :Optional[Any] = ['past_key_values'] def __init__( self : int , __magic_name__ : Dict=65024 , __magic_name__ : Tuple=4544 , __magic_name__ : Union[str, Any]=32 , __magic_name__ : List[Any]=71 , __magic_name__ : Tuple=1E-5 , __magic_name__ : List[str]=0.02 , __magic_name__ : Optional[Any]=True , __magic_name__ : List[str]=0.0 , __magic_name__ : Dict=0.0 , __magic_name__ : Any=None , __magic_name__ : Optional[int]=False , __magic_name__ : List[Any]=False , __magic_name__ : Optional[Any]=True , __magic_name__ : Tuple=True , __magic_name__ : int=False , __magic_name__ : Optional[Any]=11 , __magic_name__ : Dict=11 , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = vocab_size # Backward compatibility with n_embed kwarg lowerCAmelCase__ = kwargs.pop("n_embed" , __magic_name__ ) lowerCAmelCase__ = hidden_size if n_embed is None else n_embed lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_range lowerCAmelCase__ = use_cache lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = bos_token_id lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = num_attention_heads if num_kv_heads is None else num_kv_heads lowerCAmelCase__ = alibi lowerCAmelCase__ = new_decoder_architecture lowerCAmelCase__ = multi_query # Ignored when new_decoder_architecture is True lowerCAmelCase__ = parallel_attn lowerCAmelCase__ = bias super().__init__(bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return self.hidden_size // self.num_attention_heads @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return not self.alibi
48
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
"""simple docstring""" from maths.prime_factors import prime_factors def lowercase__ ( snake_case_ :int ): if not isinstance(snake_case_ , snake_case_ ): __UpperCAmelCase = F'''Input value of [number={number}] must be an integer''' raise TypeError(snake_case_ ) if number < 1: raise ValueError('''Input must be a positive integer''' ) return -1 if len(prime_factors(snake_case_ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
49
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging UpperCamelCase : Tuple = logging.get_logger(__name__) UpperCamelCase : Dict = { 'Salesforce/codegen-350M-nl': 'https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json', 'Salesforce/codegen-350M-multi': 'https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json', 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json', 'Salesforce/codegen-2B-nl': 'https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json', 'Salesforce/codegen-2B-multi': 'https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json', 'Salesforce/codegen-2B-mono': 'https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json', 'Salesforce/codegen-6B-nl': 'https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json', 'Salesforce/codegen-6B-multi': 'https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json', 'Salesforce/codegen-6B-mono': 'https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json', 'Salesforce/codegen-16B-nl': 'https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json', 'Salesforce/codegen-16B-multi': 'https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json', 'Salesforce/codegen-16B-mono': 'https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json', } class UpperCamelCase__ (a ): '''simple docstring''' _UpperCamelCase = 'codegen' _UpperCamelCase = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self ,_lowerCAmelCase=5_04_00 ,_lowerCAmelCase=20_48 ,_lowerCAmelCase=20_48 ,_lowerCAmelCase=40_96 ,_lowerCAmelCase=28 ,_lowerCAmelCase=16 ,_lowerCAmelCase=64 ,_lowerCAmelCase=None ,_lowerCAmelCase="gelu_new" ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=0.0 ,_lowerCAmelCase=1E-5 ,_lowerCAmelCase=0.02 ,_lowerCAmelCase=True ,_lowerCAmelCase=5_02_56 ,_lowerCAmelCase=5_02_56 ,_lowerCAmelCase=False ,**_lowerCAmelCase ,): lowerCamelCase__ = vocab_size lowerCamelCase__ = n_ctx lowerCamelCase__ = n_positions lowerCamelCase__ = n_embd lowerCamelCase__ = n_layer lowerCamelCase__ = n_head lowerCamelCase__ = n_inner lowerCamelCase__ = rotary_dim lowerCamelCase__ = activation_function lowerCamelCase__ = resid_pdrop lowerCamelCase__ = embd_pdrop lowerCamelCase__ = attn_pdrop lowerCamelCase__ = layer_norm_epsilon lowerCamelCase__ = initializer_range lowerCamelCase__ = use_cache lowerCamelCase__ = bos_token_id lowerCamelCase__ = eos_token_id super().__init__( bos_token_id=_lowerCAmelCase ,eos_token_id=_lowerCAmelCase ,tie_word_embeddings=_lowerCAmelCase ,**_lowerCAmelCase ) class UpperCamelCase__ (a ): '''simple docstring''' def __init__( self ,_lowerCAmelCase ,_lowerCAmelCase = "default" ,_lowerCAmelCase = None ,_lowerCAmelCase = False ,): super().__init__(_lowerCAmelCase ,task=_lowerCAmelCase ,patching_specs=_lowerCAmelCase ,use_past=_lowerCAmelCase ) if not getattr(self._config ,"""pad_token_id""" ,_lowerCAmelCase ): # TODO: how to do that better? lowerCamelCase__ = 0 @property def UpperCamelCase_ ( self ): lowerCamelCase__ = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(_lowerCAmelCase ,direction="""inputs""" ) lowerCamelCase__ = {0: """batch""", 1: """past_sequence + sequence"""} else: lowerCamelCase__ = {0: """batch""", 1: """sequence"""} return common_inputs @property def UpperCamelCase_ ( self ): return self._config.n_layer @property def UpperCamelCase_ ( self ): return self._config.n_head def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = -1 ,_lowerCAmelCase = -1 ,_lowerCAmelCase = False ,_lowerCAmelCase = None ,): lowerCamelCase__ = super(_lowerCAmelCase ,self ).generate_dummy_inputs( _lowerCAmelCase ,batch_size=_lowerCAmelCase ,seq_length=_lowerCAmelCase ,is_pair=_lowerCAmelCase ,framework=_lowerCAmelCase ) # We need to order the input in the way they appears in the forward() lowerCamelCase__ = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch lowerCamelCase__ , lowerCamelCase__ = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values lowerCamelCase__ = seqlen + 2 lowerCamelCase__ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) lowerCamelCase__ = [ (torch.zeros(_lowerCAmelCase ), torch.zeros(_lowerCAmelCase )) for _ in range(self.num_layers ) ] lowerCamelCase__ = common_inputs["""attention_mask"""] if self.use_past: lowerCamelCase__ = ordered_inputs["""attention_mask"""].dtype lowerCamelCase__ = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(_lowerCAmelCase ,_lowerCAmelCase ,dtype=_lowerCAmelCase )] ,dim=1 ) return ordered_inputs @property def UpperCamelCase_ ( self ): return 13
50
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
'''simple docstring''' from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def __snake_case ( SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> Any: """simple docstring""" if not is_accelerate_available(): return method UpperCAmelCase = version.parse(accelerate.__version__ ).base_version if version.parse(SCREAMING_SNAKE_CASE_ ) < version.parse('''0.17.0''' ): return method def wrapper(self : Tuple , *SCREAMING_SNAKE_CASE_ : List[Any] , **SCREAMING_SNAKE_CASE_ : Any ): if hasattr(self , '''_hf_hook''' ) and hasattr(self._hf_hook , '''pre_forward''' ): self._hf_hook.pre_forward(self ) return method(self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return wrapper
51
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
"""simple docstring""" import unittest import numpy as np from transformers import RobertaConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.roberta.modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, ) class __lowercase ( unittest.TestCase ): '''simple docstring''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=99 , _UpperCAmelCase=32 , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=512 , _UpperCAmelCase=16 , _UpperCAmelCase=2 , _UpperCAmelCase=0.0_2 , _UpperCAmelCase=4 , ): __a : Any = parent __a : Optional[int] = batch_size __a : str = seq_length __a : List[str] = is_training __a : Optional[Any] = use_attention_mask __a : Optional[Any] = use_token_type_ids __a : List[str] = use_labels __a : Union[str, Any] = vocab_size __a : int = hidden_size __a : Union[str, Any] = num_hidden_layers __a : Union[str, Any] = num_attention_heads __a : Dict = intermediate_size __a : List[str] = hidden_act __a : Dict = hidden_dropout_prob __a : Union[str, Any] = attention_probs_dropout_prob __a : int = max_position_embeddings __a : Tuple = type_vocab_size __a : Optional[int] = type_sequence_label_size __a : Optional[Any] = initializer_range __a : Optional[int] = num_choices def _lowerCamelCase ( self ): __a : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a : Union[str, Any] = None if self.use_attention_mask: __a : Any = random_attention_mask([self.batch_size, self.seq_length] ) __a : Optional[int] = None if self.use_token_type_ids: __a : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a : Any = RobertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_UpperCAmelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def _lowerCamelCase ( self ): __a : Dict = self.prepare_config_and_inputs() __a , __a , __a , __a : str = config_and_inputs __a : str = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def _lowerCamelCase ( self ): __a : Any = self.prepare_config_and_inputs() __a , __a , __a , __a : Union[str, Any] = config_and_inputs __a : Optional[int] = True __a : str = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowercase ( _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = True __lowerCAmelCase = ( ( FlaxRobertaModel, FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, ) if is_flax_available() else () ) def _lowerCamelCase ( self ): __a : Dict = FlaxRobertaModelTester(self ) @slow def _lowerCamelCase ( self ): for model_class_name in self.all_model_classes: __a : int = model_class_name.from_pretrained('''roberta-base''' , from_pt=_UpperCAmelCase ) __a : List[str] = model(np.ones((1, 1) ) ) self.assertIsNotNone(_UpperCAmelCase )
52
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs _snake_case : Union[str, Any] = imread(R'digital_image_processing/image_data/lena_small.jpg') _snake_case : Optional[int] = cvtColor(img, COLOR_BGR2GRAY) def a_ ( ): __lowerCAmelCase = cn.convert_to_negative(lowerCAmelCase_ ) # assert negative_img array for at least one True assert negative_img.any() def a_ ( ): with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowerCAmelCase_, 110 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def a_ ( ): __lowerCAmelCase = canny.gen_gaussian_kernel(9, sigma=1.4 ) # Assert ambiguous array assert resp.all() def a_ ( ): __lowerCAmelCase = imread('digital_image_processing/image_data/lena_small.jpg', 0 ) # assert ambiguous array for all == True assert canny_img.all() __lowerCAmelCase = canny.canny(lowerCAmelCase_ ) # assert canny array for at least one True assert canny_array.any() def a_ ( ): assert gg.gaussian_filter(lowerCAmelCase_, 5, sigma=0.9 ).all() def a_ ( ): # laplace diagonals __lowerCAmelCase = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) __lowerCAmelCase = conv.img_convolve(lowerCAmelCase_, lowerCAmelCase_ ).astype(lowerCAmelCase_ ) assert res.any() def a_ ( ): assert med.median_filter(lowerCAmelCase_, 3 ).any() def a_ ( ): __lowerCAmelCase , __lowerCAmelCase = sob.sobel_filter(lowerCAmelCase_ ) assert grad.any() and theta.any() def a_ ( ): __lowerCAmelCase = sp.make_sepia(lowerCAmelCase_, 20 ) assert sepia.all() def a_ ( lowerCAmelCase_ : str = "digital_image_processing/image_data/lena_small.jpg" ): __lowerCAmelCase = bs.Burkes(imread(lowerCAmelCase_, 1 ), 120 ) burkes.process() assert burkes.output_img.any() def a_ ( lowerCAmelCase_ : str = "digital_image_processing/image_data/lena_small.jpg", ): __lowerCAmelCase = rs.NearestNeighbour(imread(lowerCAmelCase_, 1 ), 400, 200 ) nn.process() assert nn.output.any() def a_ ( ): __lowerCAmelCase = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. __lowerCAmelCase = imread(lowerCAmelCase_, 0 ) # Test for get_neighbors_pixel function() return not None __lowerCAmelCase = 0 __lowerCAmelCase = 0 __lowerCAmelCase = image[x_coordinate][y_coordinate] __lowerCAmelCase = lbp.get_neighbors_pixel( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image __lowerCAmelCase = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0, image.shape[0] ): for j in range(0, image.shape[1] ): __lowerCAmelCase = lbp.local_binary_value(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) assert lbp_image.any()
53
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) __lowercase : Dict ={ """configuration_blip""": [ """BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BlipConfig""", """BlipTextConfig""", """BlipVisionConfig""", ], """processing_blip""": ["""BlipProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Any =["""BlipImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] =[ """BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """BlipModel""", """BlipPreTrainedModel""", """BlipForConditionalGeneration""", """BlipForQuestionAnswering""", """BlipVisionModel""", """BlipTextModel""", """BlipForImageTextRetrieval""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : List[Any] =[ """TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBlipModel""", """TFBlipPreTrainedModel""", """TFBlipForConditionalGeneration""", """TFBlipForQuestionAnswering""", """TFBlipVisionModel""", """TFBlipTextModel""", """TFBlipForImageTextRetrieval""", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys __lowercase : Union[str, Any] =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
54
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test") self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "[UNK]", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "[UNK]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = ( "This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image." "It takes two arguments named `image` which should be the original image, and `label` which should be a text " "describing the elements what should be identified in the segmentation mask. The tool returns the mask." ) snake_case_ = "CIDAS/clipseg-rd64-refined" snake_case_ = "image_segmenter" snake_case_ = CLIPSegForImageSegmentation snake_case_ = ["image", "text"] snake_case_ = ["image"] def __init__( self : List[Any] ,*A : List[Any] ,**A : Dict ): requires_backends(self ,["vision"] ) super().__init__(*A ,**A ) def UpperCamelCase_ ( self : int ,A : "Image" ,A : str ): return self.pre_processor(text=[label] ,images=[image] ,padding=A ,return_tensors="pt" ) def UpperCamelCase_ ( self : str ,A : List[Any] ): with torch.no_grad(): __A = self.model(**A ).logits return logits def UpperCamelCase_ ( self : List[str] ,A : str ): __A = outputs.cpu().detach().numpy() __A = 0 __A = 1 return Image.fromarray((array * 2_55).astype(np.uinta ) )
55
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _a : List[Any] = logging.get_logger(__name__) _a : str = { "Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json", } class _lowercase ( __lowercase ): _SCREAMING_SNAKE_CASE : Any = "instructblip_vision_model" def __init__( self : int , SCREAMING_SNAKE_CASE_ : Optional[Any]=1408 , SCREAMING_SNAKE_CASE_ : str=6144 , SCREAMING_SNAKE_CASE_ : List[Any]=39 , SCREAMING_SNAKE_CASE_ : List[str]=16 , SCREAMING_SNAKE_CASE_ : Optional[int]=224 , SCREAMING_SNAKE_CASE_ : List[str]=14 , SCREAMING_SNAKE_CASE_ : Dict="gelu" , SCREAMING_SNAKE_CASE_ : Any=1e-6 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE_ : Any=1e-10 , SCREAMING_SNAKE_CASE_ : Any=True , **SCREAMING_SNAKE_CASE_ : List[Any] , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) __snake_case = hidden_size __snake_case = intermediate_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = patch_size __snake_case = image_size __snake_case = initializer_range __snake_case = attention_dropout __snake_case = layer_norm_eps __snake_case = hidden_act __snake_case = qkv_bias @classmethod def a ( cls : Any , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : List[str] ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) __snake_case , __snake_case = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __snake_case = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class _lowercase ( __lowercase ): _SCREAMING_SNAKE_CASE : Union[str, Any] = "instructblip_qformer" def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[Any]=3_0522 , SCREAMING_SNAKE_CASE_ : str=768 , SCREAMING_SNAKE_CASE_ : List[str]=12 , SCREAMING_SNAKE_CASE_ : Optional[Any]=12 , SCREAMING_SNAKE_CASE_ : Dict=3072 , SCREAMING_SNAKE_CASE_ : Dict="gelu" , SCREAMING_SNAKE_CASE_ : int=0.1 , SCREAMING_SNAKE_CASE_ : List[Any]=0.1 , SCREAMING_SNAKE_CASE_ : List[str]=512 , SCREAMING_SNAKE_CASE_ : Optional[int]=0.0_2 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=1e-12 , SCREAMING_SNAKE_CASE_ : int=0 , SCREAMING_SNAKE_CASE_ : int="absolute" , SCREAMING_SNAKE_CASE_ : Tuple=2 , SCREAMING_SNAKE_CASE_ : str=1408 , **SCREAMING_SNAKE_CASE_ : List[str] , ) -> Any: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __snake_case = vocab_size __snake_case = hidden_size __snake_case = num_hidden_layers __snake_case = num_attention_heads __snake_case = hidden_act __snake_case = intermediate_size __snake_case = hidden_dropout_prob __snake_case = attention_probs_dropout_prob __snake_case = max_position_embeddings __snake_case = initializer_range __snake_case = layer_norm_eps __snake_case = position_embedding_type __snake_case = cross_attention_frequency __snake_case = encoder_hidden_size @classmethod def a ( cls : List[Any] , SCREAMING_SNAKE_CASE_ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE_ : Dict ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) __snake_case , __snake_case = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": __snake_case = config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class _lowercase ( __lowercase ): _SCREAMING_SNAKE_CASE : Dict = "instructblip" _SCREAMING_SNAKE_CASE : str = True def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Optional[Any]=None , SCREAMING_SNAKE_CASE_ : str=None , SCREAMING_SNAKE_CASE_ : List[str]=None , SCREAMING_SNAKE_CASE_ : List[str]=32 , **SCREAMING_SNAKE_CASE_ : str ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) if vision_config is None: __snake_case = {} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: __snake_case = {} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: __snake_case = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) __snake_case = InstructBlipVisionConfig(**SCREAMING_SNAKE_CASE_ ) __snake_case = InstructBlipQFormerConfig(**SCREAMING_SNAKE_CASE_ ) __snake_case = text_config['model_type'] if 'model_type' in text_config else 'opt' __snake_case = CONFIG_MAPPING[text_model_type](**SCREAMING_SNAKE_CASE_ ) __snake_case = self.text_config.tie_word_embeddings __snake_case = self.text_config.is_encoder_decoder __snake_case = num_query_tokens __snake_case = self.vision_config.hidden_size __snake_case = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES __snake_case = 1.0 __snake_case = 0.0_2 @classmethod def a ( cls : Union[str, Any] , SCREAMING_SNAKE_CASE_ : InstructBlipVisionConfig , SCREAMING_SNAKE_CASE_ : InstructBlipQFormerConfig , SCREAMING_SNAKE_CASE_ : PretrainedConfig , **SCREAMING_SNAKE_CASE_ : Tuple , ) -> Optional[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **SCREAMING_SNAKE_CASE_ , ) def a ( self : Optional[int] ) -> Any: __snake_case = copy.deepcopy(self.__dict__ ) __snake_case = self.vision_config.to_dict() __snake_case = self.qformer_config.to_dict() __snake_case = self.text_config.to_dict() __snake_case = self.__class__.model_type return output
56
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =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_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
0
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer A_ : Optional[int] = logging.get_logger(__name__) A_ : Optional[Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} A_ : Dict = { 'vocab_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json' }, 'merges_file': { 'allegro/herbert-base-cased': 'https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt' }, } A_ : Optional[Any] = {'allegro/herbert-base-cased': 514} A_ : Dict = {} class _lowerCAmelCase( UpperCAmelCase_ ): """simple docstring""" a : str =VOCAB_FILES_NAMES a : Tuple =PRETRAINED_VOCAB_FILES_MAP a : Optional[Any] =PRETRAINED_INIT_CONFIGURATION a : List[Any] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : Optional[Any] =HerbertTokenizer def __init__( self , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase="<s>" , _lowerCamelCase="<unk>" , _lowerCamelCase="<pad>" , _lowerCamelCase="<mask>" , _lowerCamelCase="</s>" , **_lowerCamelCase , ): super().__init__( _lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sep_token=_lowerCamelCase , **_lowerCamelCase , ) def _a ( self , _lowerCamelCase , _lowerCamelCase = None ): UpperCamelCase_: List[str] = [self.cls_token_id] UpperCamelCase_: List[str] = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _a ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def _a ( self , _lowerCamelCase , _lowerCamelCase = None ): UpperCamelCase_: Any = [self.sep_token_id] UpperCamelCase_: Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _a ( self , _lowerCamelCase , _lowerCamelCase = None ): UpperCamelCase_: Union[str, Any] = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
57
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __lowerCAmelCase : int = logging.get_logger(__name__) __lowerCAmelCase : List[Any] = { '''google/bit-50''': '''https://huggingface.co/google/bit-50/resolve/main/config.json''', } class _lowerCAmelCase ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): """simple docstring""" _lowerCamelCase = '''bit''' _lowerCamelCase = ['''preactivation''', '''bottleneck'''] _lowerCamelCase = ['''SAME''', '''VALID'''] def __init__( self , _lowercase=3 , _lowercase=6_4 , _lowercase=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , _lowercase=[3, 4, 6, 3] , _lowercase="preactivation" , _lowercase="relu" , _lowercase=None , _lowercase=3_2 , _lowercase=0.0 , _lowercase=False , _lowercase=3_2 , _lowercase=1 , _lowercase=None , _lowercase=None , **_lowercase , ) -> Dict: '''simple docstring''' super().__init__(**_lowercase ) if layer_type not in self.layer_types: raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types )}' ) if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case_ : Optional[Any] = global_padding.upper() else: raise ValueError(f'Padding strategy {global_padding} not supported' ) snake_case_ : str = num_channels snake_case_ : Tuple = embedding_size snake_case_ : Any = hidden_sizes snake_case_ : int = depths snake_case_ : Tuple = layer_type snake_case_ : List[Any] = hidden_act snake_case_ : int = global_padding snake_case_ : List[Any] = num_groups snake_case_ : Any = drop_path_rate snake_case_ : Optional[int] = embedding_dynamic_padding snake_case_ : int = output_stride snake_case_ : Tuple = width_factor snake_case_ : Optional[Any] = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(_lowercase ) + 1 )] snake_case_ , snake_case_ : Tuple = get_aligned_output_features_output_indices( out_features=_lowercase , out_indices=_lowercase , stage_names=self.stage_names )
58
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase_ = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase_ = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys lowerCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
60
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json', 'Salesforce/blip-vqa-capfit-large': ( 'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-base': ( 'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json' ), 'Salesforce/blip-image-captioning-large': ( 'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json' ), 'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json', 'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json', 'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json', 'Salesforce/blip-itm-large-flikr': ( 'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json' ), } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip_text_model" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_524 , SCREAMING_SNAKE_CASE__ : Optional[int]=768 , SCREAMING_SNAKE_CASE__ : Any=768 , SCREAMING_SNAKE_CASE__ : Any=3_072 , SCREAMING_SNAKE_CASE__ : Dict=768 , SCREAMING_SNAKE_CASE__ : int=12 , SCREAMING_SNAKE_CASE__ : int=8 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=512 , SCREAMING_SNAKE_CASE__ : Dict="gelu" , SCREAMING_SNAKE_CASE__ : Dict=1e-1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : str=0.02 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30_522 , SCREAMING_SNAKE_CASE__ : str=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : int=102 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : int=True , **SCREAMING_SNAKE_CASE__ : int , ) -> Dict: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , sep_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = encoder_hidden_size lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = hidden_act lowerCAmelCase__ = initializer_range lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = is_decoder lowerCAmelCase__ = use_cache @classmethod def a ( cls : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : Any ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the text config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": lowerCAmelCase__ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip_vision_model" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Dict=768 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_072 , SCREAMING_SNAKE_CASE__ : Optional[int]=512 , SCREAMING_SNAKE_CASE__ : Optional[int]=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : str=384 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=16 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=1e-5 , SCREAMING_SNAKE_CASE__ : Any=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-1_0 , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = patch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = hidden_act @classmethod def a ( cls : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : str ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ , lowerCAmelCase__ = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": lowerCAmelCase__ = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "blip" snake_case__ = True def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Any=512 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2.6_592 , SCREAMING_SNAKE_CASE__ : Tuple=256 , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) if text_config is None: lowerCAmelCase__ = {} logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values." ) if vision_config is None: lowerCAmelCase__ = {} logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values." ) lowerCAmelCase__ = BlipTextConfig(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = BlipVisionConfig(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.vision_config.hidden_size lowerCAmelCase__ = projection_dim lowerCAmelCase__ = logit_scale_init_value lowerCAmelCase__ = 1.0 lowerCAmelCase__ = 0.02 lowerCAmelCase__ = image_text_hidden_size @classmethod def a ( cls : Union[str, Any] , SCREAMING_SNAKE_CASE__ : BlipTextConfig , SCREAMING_SNAKE_CASE__ : BlipVisionConfig , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Optional[int]: lowerCAmelCase__ = copy.deepcopy(self.__dict__ ) lowerCAmelCase__ = self.text_config.to_dict() lowerCAmelCase__ = self.vision_config.to_dict() lowerCAmelCase__ = self.__class__.model_type return output
61
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
0
import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Dict=True , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = parent SCREAMING_SNAKE_CASE : Dict = config_class SCREAMING_SNAKE_CASE : Optional[Any] = has_text_modality SCREAMING_SNAKE_CASE : List[str] = kwargs SCREAMING_SNAKE_CASE : List[Any] = common_properties def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : int = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE : Dict = ( ["hidden_size", "num_attention_heads", "num_hidden_layers"] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["vocab_size"] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase_ , UpperCAmelCase_ ) , msg=f'''`{prop}` does not exist''' ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase_ ): try: setattr(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.parent.assertEqual( getattr(UpperCAmelCase_ , UpperCAmelCase_ ) , UpperCAmelCase_ , msg=f'''`{name} value {idx} expected, but was {getattr(UpperCAmelCase_ , UpperCAmelCase_ )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase_ ): try: SCREAMING_SNAKE_CASE : List[str] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase_ , UpperCAmelCase_ ) , UpperCAmelCase_ , msg=f'''`{name} value {idx} expected, but was {getattr(UpperCAmelCase_ , UpperCAmelCase_ )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[int] = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE : Any = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Dict = os.path.join(UpperCAmelCase_ , "config.json" ) config_first.to_json_file(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.config_class.from_json_file(UpperCAmelCase_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Tuple = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self.config_class.from_pretrained(UpperCAmelCase_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE : Dict = "test" with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) config_first.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.config_class.from_pretrained(UpperCAmelCase_ , subfolder=UpperCAmelCase_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) SCREAMING_SNAKE_CASE : List[Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _A ( self : str ): if self.config_class.is_composition: return SCREAMING_SNAKE_CASE : Optional[int] = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self.config_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("torch_dtype", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase_ , UpperCAmelCase_ ) != value: wrong_values.append((key, getattr(UpperCAmelCase_ , UpperCAmelCase_ ), value) ) if len(UpperCAmelCase_ ) > 0: SCREAMING_SNAKE_CASE : Any = "\n".join([f'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values] ) raise ValueError(f'''The following keys were not properly set in the config:\n{errors}''' ) def _A ( self : Tuple ): self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
62
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
0
from __future__ import annotations import numpy as np def lowerCamelCase__ ( __lowerCamelCase : list[float] ): return np.maximum(0 , __lowerCamelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
63
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
0
def A__ ( snake_case_ : list ): if len(snake_case_ ) <= 1: return [tuple(snake_case_ )] SCREAMING_SNAKE_CASE__: Union[str, Any]= [] def generate(snake_case_ : int , snake_case_ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , snake_case_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Union[str, Any]= arr[k - 1], arr[i] else: # k is odd SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__: Optional[int]= arr[k - 1], arr[0] generate(k - 1 , snake_case_ ) generate(len(snake_case_ ) , snake_case_ ) return res if __name__ == "__main__": lowercase_ : Any = input('Enter numbers separated by a comma:\n').strip() lowercase_ : str = [int(item) for item in user_input.split(',')] print(heaps(arr))
64
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
"""simple docstring""" from __future__ import annotations def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ): '''simple docstring''' if (stress, tangential_force, area).count(0 ) != 1: raise ValueError("""You cannot supply more or less than 2 values""" ) elif stress < 0: raise ValueError("""Stress cannot be negative""" ) elif tangential_force < 0: raise ValueError("""Tangential Force cannot be negative""" ) elif area < 0: raise ValueError("""Area cannot be negative""" ) elif stress == 0: return ( "stress", tangential_force / area, ) elif tangential_force == 0: return ( "tangential_force", stress * area, ) else: return ( "area", tangential_force / stress, ) if __name__ == "__main__": import doctest doctest.testmod()
65
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
0
import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase_ ( __snake_case , unittest.TestCase ): _UpperCamelCase : Dict = None _UpperCamelCase : str = BloomTokenizerFast _UpperCamelCase : int = BloomTokenizerFast _UpperCamelCase : List[str] = True _UpperCamelCase : Union[str, Any] = False _UpperCamelCase : int = "tokenizer_file" _UpperCamelCase : str = {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"} def __a ( self ): super().setUp() _lowercase : List[str] = BloomTokenizerFast.from_pretrained('bigscience/tokenizer' ) tokenizer.save_pretrained(self.tmpdirname ) def __a ( self , **_lowerCAmelCase ): kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def __a ( self ): _lowercase : int = self.get_rust_tokenizer() _lowercase : Any = ['The quick brown fox</s>', 'jumps over the lazy dog</s>'] _lowercase : str = [[2_1_7_5, 2_3_7_1_4, 7_3_1_7_3, 1_4_4_2_5_2, 2], [7_7, 1_3_2_6_1_9, 3_4_7_8, 3_6_8, 1_0_9_5_8_6, 3_5_4_3_3, 2]] _lowercase : Dict = tokenizer.batch_encode_plus(_lowerCAmelCase )['input_ids'] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) _lowercase : Optional[int] = tokenizer.batch_decode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def __a ( self , _lowerCAmelCase=6 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): _lowercase : Any = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input _lowercase : int = 'This is a simple input' _lowercase : Union[str, Any] = ['This is a simple input 1', 'This is a simple input 2'] _lowercase : Union[str, Any] = ('This is a simple input', 'This is a pair') _lowercase : Optional[int] = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests try: tokenizer_r.encode(_lowerCAmelCase , max_length=_lowerCAmelCase ) tokenizer_r.encode_plus(_lowerCAmelCase , max_length=_lowerCAmelCase ) tokenizer_r.batch_encode_plus(_lowerCAmelCase , max_length=_lowerCAmelCase ) tokenizer_r.encode(_lowerCAmelCase , max_length=_lowerCAmelCase ) tokenizer_r.batch_encode_plus(_lowerCAmelCase , max_length=_lowerCAmelCase ) except ValueError: self.fail('Bloom Tokenizer should be able to deal with padding' ) _lowercase : Any = None # Hotfixing padding = None self.assertRaises(_lowerCAmelCase , tokenizer_r.encode , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' ) # Simple input self.assertRaises(_lowerCAmelCase , tokenizer_r.encode_plus , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' ) # Simple input self.assertRaises( _lowerCAmelCase , tokenizer_r.batch_encode_plus , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' , ) # Pair input self.assertRaises(_lowerCAmelCase , tokenizer_r.encode , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' ) # Pair input self.assertRaises(_lowerCAmelCase , tokenizer_r.encode_plus , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' ) # Pair input self.assertRaises( _lowerCAmelCase , tokenizer_r.batch_encode_plus , _lowerCAmelCase , max_length=_lowerCAmelCase , padding='max_length' , ) def __a ( self ): _lowercase : List[str] = self.get_rust_tokenizer() _lowercase : List[Any] = load_dataset('xnli' , 'all_languages' , split='test' , streaming=_lowerCAmelCase ) _lowercase : Union[str, Any] = next(iter(_lowerCAmelCase ) )['premise'] # pick up one data _lowercase : Optional[int] = list(sample_data.values() ) _lowercase : str = list(map(tokenizer.encode , _lowerCAmelCase ) ) _lowercase : Union[str, Any] = [tokenizer.decode(_lowerCAmelCase , clean_up_tokenization_spaces=_lowerCAmelCase ) for x in output_tokens] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def __a ( self ): # The test has to be overriden because BLOOM uses ALiBi positional embeddings that does not have # any sequence length constraints. This test of the parent class will fail since it relies on the # maximum sequence length of the positoonal embeddings. self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
66
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( """The `image_to_image.py` script is outdated. Please use directly `from diffusers import""" """ StableDiffusionImg2ImgPipeline` instead.""" )
67
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_funnel import FunnelTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = [ "small", "small-base", "medium", "medium-base", "intermediate", "intermediate-base", "large", "large-base", "xlarge", "xlarge-base", ] __A = { "vocab_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt", "funnel-transformer/small-base": "https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt", "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt", "funnel-transformer/large-base": "https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt", "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt" ), }, "tokenizer_file": { "funnel-transformer/small": "https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json", "funnel-transformer/small-base": ( "https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json" ), "funnel-transformer/medium": "https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json", "funnel-transformer/medium-base": ( "https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate": ( "https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json" ), "funnel-transformer/intermediate-base": ( "https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json" ), "funnel-transformer/large": "https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json", "funnel-transformer/large-base": ( "https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json" ), "funnel-transformer/xlarge": "https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json", "funnel-transformer/xlarge-base": ( "https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json" ), }, } __A = {F"""funnel-transformer/{name}""": 5_12 for name in _model_names} __A = {F"""funnel-transformer/{name}""": {"do_lower_case": True} for name in _model_names} class _A ( UpperCamelCase ): """simple docstring""" lowerCamelCase : Optional[Any] = VOCAB_FILES_NAMES lowerCamelCase : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION lowerCamelCase : Tuple = FunnelTokenizer lowerCamelCase : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase : int = 2 def __init__( self : List[Any] , __SCREAMING_SNAKE_CASE : str=None , __SCREAMING_SNAKE_CASE : Any=None , __SCREAMING_SNAKE_CASE : int=True , __SCREAMING_SNAKE_CASE : Optional[int]="<unk>" , __SCREAMING_SNAKE_CASE : Any="<sep>" , __SCREAMING_SNAKE_CASE : Optional[int]="<pad>" , __SCREAMING_SNAKE_CASE : Optional[Any]="<cls>" , __SCREAMING_SNAKE_CASE : List[str]="<mask>" , __SCREAMING_SNAKE_CASE : Dict="<s>" , __SCREAMING_SNAKE_CASE : Any="</s>" , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Optional[int]=None , __SCREAMING_SNAKE_CASE : Dict="##" , **__SCREAMING_SNAKE_CASE : Tuple , ) -> List[Any]: super().__init__( __SCREAMING_SNAKE_CASE , tokenizer_file=__SCREAMING_SNAKE_CASE , do_lower_case=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , sep_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , cls_token=__SCREAMING_SNAKE_CASE , mask_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , clean_text=__SCREAMING_SNAKE_CASE , tokenize_chinese_chars=__SCREAMING_SNAKE_CASE , strip_accents=__SCREAMING_SNAKE_CASE , wordpieces_prefix=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) __UpperCAmelCase =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get("""strip_accents""" , __SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): __UpperCAmelCase =getattr(__SCREAMING_SNAKE_CASE , normalizer_state.pop("""type""" ) ) __UpperCAmelCase =do_lower_case __UpperCAmelCase =strip_accents __UpperCAmelCase =tokenize_chinese_chars __UpperCAmelCase =normalizer_class(**__SCREAMING_SNAKE_CASE ) __UpperCAmelCase =do_lower_case def _a ( self : str , __SCREAMING_SNAKE_CASE : List[Any] , __SCREAMING_SNAKE_CASE : Union[str, Any]=None ) -> Any: __UpperCAmelCase =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _a ( self : str , __SCREAMING_SNAKE_CASE : List[int] , __SCREAMING_SNAKE_CASE : Optional[List[int]] = None ) -> List[int]: __UpperCAmelCase =[self.sep_token_id] __UpperCAmelCase =[self.cls_token_id] if token_ids_a is None: return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] return len(cls ) * [self.cls_token_type_id] + len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _a ( self : Any , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[str] = None ) -> Tuple[str]: __UpperCAmelCase =self._tokenizer.model.save(__SCREAMING_SNAKE_CASE , name=__SCREAMING_SNAKE_CASE ) return tuple(__SCREAMING_SNAKE_CASE )
68
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Dict ): """simple docstring""" __snake_case = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) __snake_case = get_activation("gelu" ) self.assertTrue(torch.allclose(gelu_python(a_ ) , torch_builtin(a_ ) ) ) self.assertFalse(torch.allclose(gelu_python(a_ ) , gelu_new(a_ ) ) ) def A ( self : List[Any] ): """simple docstring""" __snake_case = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) __snake_case = get_activation("gelu" ) __snake_case = get_activation("gelu_10" ) __snake_case = torch_builtin(a_ ) __snake_case = geluaa(a_ ) __snake_case = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(a_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def A ( self : Tuple ): """simple docstring""" get_activation("gelu" ) get_activation("gelu_10" ) get_activation("gelu_fast" ) get_activation("gelu_new" ) get_activation("gelu_python" ) get_activation("gelu_pytorch_tanh" ) get_activation("linear" ) get_activation("mish" ) get_activation("quick_gelu" ) get_activation("relu" ) get_activation("sigmoid" ) get_activation("silu" ) get_activation("swish" ) get_activation("tanh" ) with self.assertRaises(a_ ): get_activation("bogus" ) with self.assertRaises(a_ ): get_activation(a_ ) def A ( self : str ): """simple docstring""" __snake_case = get_activation("gelu" ) __snake_case = 1 __snake_case = get_activation("gelu" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(a_ ): __snake_case = acta.a
69
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =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_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCamelCase : str = logging.get_logger(__name__) class A( UpperCamelCase ): '''simple docstring''' def __init__( self : str , A_ : int , A_ : int , A_ : float , **A_ : str ) -> Optional[Any]: """simple docstring""" lowerCamelCase_ = feature_size lowerCamelCase_ = sampling_rate lowerCamelCase_ = padding_value lowerCamelCase_ = kwargs.pop('padding_side' , 'right' ) lowerCamelCase_ = kwargs.pop('return_attention_mask' , A_ ) super().__init__(**A_ ) def a__ ( self : Tuple , A_ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , A_ : Union[bool, str, PaddingStrategy] = True , A_ : Optional[int] = None , A_ : bool = False , A_ : Optional[int] = None , A_ : Optional[bool] = None , A_ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: """simple docstring""" if isinstance(A_ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): lowerCamelCase_ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f""" to this method that includes {self.model_input_names[0]}, but you provided""" f""" {list(processed_features.keys() )}""" ) lowerCamelCase_ = processed_features[self.model_input_names[0]] lowerCamelCase_ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(A_ ) == 0: if return_attention_mask: lowerCamelCase_ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch lowerCamelCase_ = required_input[0] if isinstance(A_ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. lowerCamelCase_ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(A_ ): lowerCamelCase_ = required_input[index][0] if return_tensors is None: if is_tf_tensor(A_ ): lowerCamelCase_ = 'tf' elif is_torch_tensor(A_ ): lowerCamelCase_ = 'pt' elif isinstance(A_ , (int, float, list, tuple, np.ndarray) ): lowerCamelCase_ = 'np' else: raise ValueError( f"""type of {first_element} unknown: {type(A_ )}. """ 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): lowerCamelCase_ = to_numpy(A_ ) else: lowerCamelCase_ = [to_numpy(A_ ) for v in value] # Convert padding_strategy in PaddingStrategy lowerCamelCase_ = self._get_padding_strategies(padding=A_ , max_length=A_ ) lowerCamelCase_ = processed_features[self.model_input_names[0]] lowerCamelCase_ = len(A_ ) if not all(len(A_ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) lowerCamelCase_ = [] for i in range(A_ ): lowerCamelCase_ = {k: v[i] for k, v in processed_features.items()} # truncation lowerCamelCase_ = self._truncate( A_ , max_length=A_ , pad_to_multiple_of=A_ , truncation=A_ , ) truncated_inputs.append(A_ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length lowerCamelCase_ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) lowerCamelCase_ = PaddingStrategy.MAX_LENGTH lowerCamelCase_ = {} for i in range(A_ ): # padding lowerCamelCase_ = self._pad( truncated_inputs[i] , max_length=A_ , padding_strategy=A_ , pad_to_multiple_of=A_ , return_attention_mask=A_ , ) for key, value in outputs.items(): if key not in batch_outputs: lowerCamelCase_ = [] if value.dtype is np.dtype(np.floataa ): lowerCamelCase_ = value.astype(np.floataa ) batch_outputs[key].append(A_ ) return BatchFeature(A_ , tensor_type=A_ ) def a__ ( self : Any , A_ : Union[Dict[str, np.ndarray], BatchFeature] , A_ : Optional[int] = None , A_ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , A_ : Optional[int] = None , A_ : Optional[bool] = None , ) -> dict: """simple docstring""" lowerCamelCase_ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: lowerCamelCase_ = len(A_ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): lowerCamelCase_ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of lowerCamelCase_ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(A_ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: lowerCamelCase_ = np.ones(len(A_ ) , dtype=np.intaa ) if needs_to_be_padded: lowerCamelCase_ = max_length - len(A_ ) if self.padding_side == "right": if return_attention_mask: lowerCamelCase_ = np.pad( processed_features['attention_mask'] , (0, difference) ) lowerCamelCase_ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) lowerCamelCase_ = np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: lowerCamelCase_ = np.pad( processed_features['attention_mask'] , (difference, 0) ) lowerCamelCase_ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) lowerCamelCase_ = np.pad( A_ , A_ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def a__ ( self : Optional[Any] , A_ : Union[Dict[str, np.ndarray], BatchFeature] , A_ : Optional[int] = None , A_ : Optional[int] = None , A_ : Optional[bool] = None , ) -> Any: """simple docstring""" if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) lowerCamelCase_ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): lowerCamelCase_ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of lowerCamelCase_ = len(A_ ) > max_length if needs_to_be_truncated: lowerCamelCase_ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: lowerCamelCase_ = processed_features['attention_mask'][:max_length] return processed_features def a__ ( self : Optional[Any] , A_ : Optional[int]=False , A_ : Any=None ) -> Optional[Any]: """simple docstring""" if padding is not False: if padding is True: lowerCamelCase_ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(A_ , A_ ): lowerCamelCase_ = PaddingStrategy(A_ ) elif isinstance(A_ , A_ ): lowerCamelCase_ = padding else: lowerCamelCase_ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined""" ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
70
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =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() = }')
59
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase = { """configuration_ctrl""": ["""CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CTRLConfig"""], """tokenization_ctrl""": ["""CTRLTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ """CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """CTRLForSequenceClassification""", """CTRLLMHeadModel""", """CTRLModel""", """CTRLPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ """TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCTRLForSequenceClassification""", """TFCTRLLMHeadModel""", """TFCTRLModel""", """TFCTRLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
71
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
'''simple docstring''' class __magic_name__ : def __init__( self , snake_case_ , snake_case_ ): lowercase =name lowercase =val def __str__( self ): return f'{self.__class__.__name__}({self.name}, {self.val})' def __lt__( self , snake_case_ ): return self.val < other.val class __magic_name__ : def __init__( self , snake_case_ ): lowercase ={} lowercase ={} lowercase =self.build_heap(snake_case_ ) def __getitem__( self , snake_case_ ): return self.get_value(snake_case_ ) def _A( self , snake_case_ ): return (idx - 1) // 2 def _A( self , snake_case_ ): return idx * 2 + 1 def _A( self , snake_case_ ): return idx * 2 + 2 def _A( self , snake_case_ ): return self.heap_dict[key] def _A( self , snake_case_ ): lowercase =len(snake_case_ ) - 1 lowercase =self.get_parent_idx(snake_case_ ) for idx, i in enumerate(snake_case_ ): lowercase =idx lowercase =i.val for i in range(snake_case_ , -1 , -1 ): self.sift_down(snake_case_ , snake_case_ ) return array def _A( self , snake_case_ , snake_case_ ): while True: lowercase =self.get_left_child_idx(snake_case_ ) # noqa: E741 lowercase =self.get_right_child_idx(snake_case_ ) lowercase =idx if l < len(snake_case_ ) and array[l] < array[idx]: lowercase =l if r < len(snake_case_ ) and array[r] < array[smallest]: lowercase =r if smallest != idx: lowercase , lowercase =array[smallest], array[idx] ( ( lowercase ) , ( lowercase ) , ) =( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) lowercase =smallest else: break def _A( self , snake_case_ ): lowercase =self.get_parent_idx(snake_case_ ) while p >= 0 and self.heap[p] > self.heap[idx]: lowercase , lowercase =self.heap[idx], self.heap[p] lowercase , lowercase =( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) lowercase =p lowercase =self.get_parent_idx(snake_case_ ) def _A( self ): return self.heap[0] def _A( self ): lowercase , lowercase =self.heap[-1], self.heap[0] lowercase , lowercase =( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) lowercase =self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def _A( self , snake_case_ ): self.heap.append(snake_case_ ) lowercase =len(self.heap ) - 1 lowercase =node.val self.sift_up(len(self.heap ) - 1 ) def _A( self ): return len(self.heap ) == 0 def _A( self , snake_case_ , snake_case_ ): assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" lowercase =new_value lowercase =new_value self.sift_up(self.idx_of_element[node] ) _UpperCAmelCase : Any = Node('''R''', -1) _UpperCAmelCase : Optional[int] = Node('''B''', 6) _UpperCAmelCase : Tuple = Node('''A''', 3) _UpperCAmelCase : Union[str, Any] = Node('''X''', 1) _UpperCAmelCase : List[str] = Node('''E''', 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array _UpperCAmelCase : Union[str, Any] = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print('''Min Heap - before decrease key''') for i in my_min_heap.heap: print(i) print('''Min Heap - After decrease key of node [B -> -17]''') my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
72
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax.numpy as jnp from jax import random from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .scheduling_utils_flax import FlaxSchedulerMixin @flax.struct.dataclass class _snake_case : # setable values _lowercase : Optional[int] = None _lowercase : Optional[jnp.ndarray] = None _lowercase : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def SCREAMING_SNAKE_CASE__ ( cls) -> int: return cls() @dataclass class _snake_case ( A__ ): _lowercase : jnp.ndarray _lowercase : jnp.ndarray _lowercase : KarrasVeSchedulerState class _snake_case ( A__ , A__ ): @property def SCREAMING_SNAKE_CASE__ ( self) -> Optional[int]: return True @register_to_config def __init__( self , a = 0.02 , a = 100 , a = 1.0_07 , a = 80 , a = 0.05 , a = 50 , ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: return KarrasVeSchedulerState.create() def SCREAMING_SNAKE_CASE__ ( self , a , a , a = ()) -> KarrasVeSchedulerState: SCREAMING_SNAKE_CASE = jnp.arange(0 , a)[::-1].copy() SCREAMING_SNAKE_CASE = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in timesteps ] return state.replace( num_inference_steps=a , schedule=jnp.array(a , dtype=jnp.floataa) , timesteps=a , ) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , ) -> Tuple[jnp.ndarray, float]: if self.config.s_min <= sigma <= self.config.s_max: SCREAMING_SNAKE_CASE = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1) else: SCREAMING_SNAKE_CASE = 0 # sample eps ~ N(0, S_noise^2 * I) SCREAMING_SNAKE_CASE = random.split(a , num=1) SCREAMING_SNAKE_CASE = self.config.s_noise * random.normal(key=a , shape=sample.shape) SCREAMING_SNAKE_CASE = sigma + gamma * sigma SCREAMING_SNAKE_CASE = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: SCREAMING_SNAKE_CASE = sample_hat + sigma_hat * model_output SCREAMING_SNAKE_CASE = (sample_hat - pred_original_sample) / sigma_hat SCREAMING_SNAKE_CASE = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a , derivative=a , state=a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a , a , a , a , a = True , ) -> Union[FlaxKarrasVeOutput, Tuple]: SCREAMING_SNAKE_CASE = sample_prev + sigma_prev * model_output SCREAMING_SNAKE_CASE = (sample_prev - pred_original_sample) / sigma_prev SCREAMING_SNAKE_CASE = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=a , derivative=a , state=a) def SCREAMING_SNAKE_CASE__ ( self , a , a , a , a) -> int: raise NotImplementedError()
73
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" lowerCAmelCase_ = '''wavlm''' def __init__( self : Optional[Any] , _A : List[Any]=32 , _A : List[Any]=768 , _A : Optional[int]=12 , _A : Optional[int]=12 , _A : List[str]=3072 , _A : List[Any]="gelu" , _A : Tuple=0.1 , _A : Dict=0.1 , _A : int=0.1 , _A : Optional[int]=0.0 , _A : Optional[int]=0.1 , _A : Any=0.1 , _A : List[Any]=0.02 , _A : Tuple=1e-5 , _A : Union[str, Any]="group" , _A : Optional[Any]="gelu" , _A : List[str]=(512, 512, 512, 512, 512, 512, 512) , _A : List[str]=(5, 2, 2, 2, 2, 2, 2) , _A : str=(10, 3, 3, 3, 3, 2, 2) , _A : Union[str, Any]=False , _A : Union[str, Any]=128 , _A : str=16 , _A : Union[str, Any]=320 , _A : Optional[int]=800 , _A : Dict=False , _A : Optional[int]=True , _A : Any=0.05 , _A : List[Any]=10 , _A : Tuple=2 , _A : Tuple=0.0 , _A : str=10 , _A : str=320 , _A : Any=2 , _A : Optional[Any]=0.1 , _A : Optional[int]=100 , _A : Union[str, Any]=256 , _A : Optional[Any]=256 , _A : Tuple=0.1 , _A : Union[str, Any]="mean" , _A : str=False , _A : Any=False , _A : List[str]=256 , _A : str=(512, 512, 512, 512, 1500) , _A : Any=(5, 3, 3, 1, 1) , _A : List[str]=(1, 2, 3, 1, 1) , _A : List[Any]=512 , _A : List[Any]=80 , _A : Optional[Any]=0 , _A : str=1 , _A : str=2 , _A : Union[str, Any]=False , _A : List[str]=3 , _A : Any=2 , _A : str=3 , _A : Optional[Any]=None , **_A : Any , ): """simple docstring""" super().__init__(**_A , pad_token_id=_A , bos_token_id=_A , eos_token_id=_A ) __SCREAMING_SNAKE_CASE : Tuple = hidden_size __SCREAMING_SNAKE_CASE : int = feat_extract_norm __SCREAMING_SNAKE_CASE : Optional[Any] = feat_extract_activation __SCREAMING_SNAKE_CASE : Dict = list(_A ) __SCREAMING_SNAKE_CASE : int = list(_A ) __SCREAMING_SNAKE_CASE : Dict = list(_A ) __SCREAMING_SNAKE_CASE : Dict = conv_bias __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[Any] = max_bucket_distance __SCREAMING_SNAKE_CASE : List[Any] = num_conv_pos_embeddings __SCREAMING_SNAKE_CASE : str = num_conv_pos_embedding_groups __SCREAMING_SNAKE_CASE : Optional[int] = len(self.conv_dim ) __SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : int = intermediate_size __SCREAMING_SNAKE_CASE : Tuple = hidden_act __SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads __SCREAMING_SNAKE_CASE : str = hidden_dropout __SCREAMING_SNAKE_CASE : List[Any] = attention_dropout __SCREAMING_SNAKE_CASE : List[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Any = feat_proj_dropout __SCREAMING_SNAKE_CASE : Union[str, Any] = final_dropout __SCREAMING_SNAKE_CASE : List[str] = layerdrop __SCREAMING_SNAKE_CASE : str = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = initializer_range __SCREAMING_SNAKE_CASE : Optional[Any] = num_ctc_classes __SCREAMING_SNAKE_CASE : Dict = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = do_stable_layer_norm __SCREAMING_SNAKE_CASE : str = use_weighted_layer_sum __SCREAMING_SNAKE_CASE : Union[str, Any] = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' F''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' F''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __SCREAMING_SNAKE_CASE : Tuple = apply_spec_augment __SCREAMING_SNAKE_CASE : Tuple = mask_time_prob __SCREAMING_SNAKE_CASE : int = mask_time_length __SCREAMING_SNAKE_CASE : Optional[int] = mask_time_min_masks __SCREAMING_SNAKE_CASE : Optional[int] = mask_feature_prob __SCREAMING_SNAKE_CASE : Optional[Any] = mask_feature_length # parameters for pretraining with codevector quantized representations __SCREAMING_SNAKE_CASE : Optional[int] = num_codevectors_per_group __SCREAMING_SNAKE_CASE : Dict = num_codevector_groups __SCREAMING_SNAKE_CASE : Tuple = contrastive_logits_temperature __SCREAMING_SNAKE_CASE : int = num_negatives __SCREAMING_SNAKE_CASE : Union[str, Any] = codevector_dim __SCREAMING_SNAKE_CASE : List[str] = proj_codevector_dim __SCREAMING_SNAKE_CASE : Tuple = diversity_loss_weight # ctc loss __SCREAMING_SNAKE_CASE : str = ctc_loss_reduction __SCREAMING_SNAKE_CASE : Tuple = ctc_zero_infinity # adapter __SCREAMING_SNAKE_CASE : Optional[int] = add_adapter __SCREAMING_SNAKE_CASE : Dict = adapter_kernel_size __SCREAMING_SNAKE_CASE : Union[str, Any] = adapter_stride __SCREAMING_SNAKE_CASE : List[str] = num_adapter_layers __SCREAMING_SNAKE_CASE : Optional[int] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE : Optional[int] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __SCREAMING_SNAKE_CASE : List[Any] = list(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = list(_A ) __SCREAMING_SNAKE_CASE : Tuple = list(_A ) __SCREAMING_SNAKE_CASE : Optional[int] = xvector_output_dim @property def UpperCAmelCase__ ( self : int ): """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
74
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class lowerCamelCase_ ( unittest.TestCase ): def lowercase_ ( self : str ): '''simple docstring''' UpperCAmelCase__ : List[str] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCAmelCase__ : List[Any] = get_activation('''gelu''' ) self.assertTrue(torch.allclose(gelu_python(_A ) , torch_builtin(_A ) ) ) self.assertFalse(torch.allclose(gelu_python(_A ) , gelu_new(_A ) ) ) def lowercase_ ( self : Dict ): '''simple docstring''' UpperCAmelCase__ : List[Any] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) UpperCAmelCase__ : Any = get_activation('''gelu''' ) UpperCAmelCase__ : List[Any] = get_activation('''gelu_10''' ) UpperCAmelCase__ : Tuple = torch_builtin(_A ) UpperCAmelCase__ : List[str] = geluaa(_A ) UpperCAmelCase__ : Any = torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_A ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def lowercase_ ( self : List[Any] ): '''simple docstring''' get_activation('''gelu''' ) get_activation('''gelu_10''' ) get_activation('''gelu_fast''' ) get_activation('''gelu_new''' ) get_activation('''gelu_python''' ) get_activation('''gelu_pytorch_tanh''' ) get_activation('''linear''' ) get_activation('''mish''' ) get_activation('''quick_gelu''' ) get_activation('''relu''' ) get_activation('''sigmoid''' ) get_activation('''silu''' ) get_activation('''swish''' ) get_activation('''tanh''' ) with self.assertRaises(_A ): get_activation('''bogus''' ) with self.assertRaises(_A ): get_activation(_A ) def lowercase_ ( self : List[Any] ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = get_activation('''gelu''' ) UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : Any = get_activation('''gelu''' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_A ): UpperCAmelCase__ : str = acta.a
75
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
"""simple docstring""" a_ = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' a_ = [{'type': 'code', 'content': INSTALL_CONTENT}] a_ = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
76
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0
"""simple docstring""" def _UpperCamelCase ( UpperCamelCase , UpperCamelCase ) -> str: """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) __UpperCAmelCase : Optional[Any] = str(bin(UpperCamelCase ) )[2:] # remove the leading "0b" __UpperCAmelCase : int = str(bin(UpperCamelCase ) )[2:] # remove the leading "0b" __UpperCAmelCase : Tuple = max(len(UpperCamelCase ) , len(UpperCamelCase ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(UpperCamelCase ) , b_binary.zfill(UpperCamelCase ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
77
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test") self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "[UNK]", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "[UNK]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
0
'''simple docstring''' import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class __A ( UpperCamelCase__ ): a__ : int = """MCTCTFeatureExtractor""" a__ : int = """AutoTokenizer""" def __init__(self : Dict , __a : Tuple , __a : Optional[Any] ): super().__init__(__a , __a ) UpperCAmelCase_ = self.feature_extractor UpperCAmelCase_ = False def __call__(self : Dict , *__a : int , **__a : str ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__a , **__a ) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." ) UpperCAmelCase_ = kwargs.pop("raw_speech" ) else: UpperCAmelCase_ = kwargs.pop("audio" , __a ) UpperCAmelCase_ = kwargs.pop("sampling_rate" , __a ) UpperCAmelCase_ = kwargs.pop("text" , __a ) if len(__a ) > 0: UpperCAmelCase_ = args[0] UpperCAmelCase_ = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if audio is not None: UpperCAmelCase_ = self.feature_extractor(__a , *__a , sampling_rate=__a , **__a ) if text is not None: UpperCAmelCase_ = self.tokenizer(__a , **__a ) if text is None: return inputs elif audio is None: return encodings else: UpperCAmelCase_ = encodings["input_ids"] return inputs def _lowercase (self : List[Any] , *__a : List[Any] , **__a : int ): return self.tokenizer.batch_decode(*__a , **__a ) def _lowercase (self : Optional[int] , *__a : str , **__a : List[Any] ): # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*__a , **__a ) UpperCAmelCase_ = kwargs.pop("input_features" , __a ) UpperCAmelCase_ = kwargs.pop("labels" , __a ) if len(__a ) > 0: UpperCAmelCase_ = args[0] UpperCAmelCase_ = args[1:] if input_features is not None: UpperCAmelCase_ = self.feature_extractor.pad(__a , *__a , **__a ) if labels is not None: UpperCAmelCase_ = self.tokenizer.pad(__a , **__a ) if labels is None: return input_features elif input_features is None: return labels else: UpperCAmelCase_ = labels["input_ids"] return input_features def _lowercase (self : Optional[int] , *__a : List[Any] , **__a : Tuple ): return self.tokenizer.decode(*__a , **__a ) @contextmanager def _lowercase (self : Any ): warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call." ) UpperCAmelCase_ = True UpperCAmelCase_ = self.tokenizer yield UpperCAmelCase_ = self.feature_extractor UpperCAmelCase_ = False
78
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
0
from typing import Any class UpperCAmelCase_ : def __init__( self , _lowerCAmelCase ): UpperCAmelCase__ : Tuple = data UpperCAmelCase__ : str = None def __repr__( self ): return f"Node({self.data})" class UpperCAmelCase_ : def __init__( self ): UpperCAmelCase__ : Union[str, Any] = None def __iter__( self ): UpperCAmelCase__ : List[str] = self.head while node: yield node.data UpperCAmelCase__ : List[str] = node.next def __len__( self ): return sum(1 for _ in self ) def __repr__( self ): return "->".join([str(_lowerCAmelCase ) for item in self] ) def __getitem__( self , _lowerCAmelCase ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self , _lowerCAmelCase , _lowerCAmelCase ): if not 0 <= index < len(self ): raise ValueError("""list index out of range.""" ) UpperCAmelCase__ : Optional[int] = self.head for _ in range(_lowerCAmelCase ): UpperCAmelCase__ : Any = current.next UpperCAmelCase__ : Dict = data def __UpperCAmelCase ( self , _lowerCAmelCase ): self.insert_nth(len(self ) , _lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase ): self.insert_nth(0 , _lowerCAmelCase ) def __UpperCAmelCase ( self , _lowerCAmelCase , _lowerCAmelCase ): if not 0 <= index <= len(self ): raise IndexError("""list index out of range""" ) UpperCAmelCase__ : Union[str, Any] = Node(_lowerCAmelCase ) if self.head is None: UpperCAmelCase__ : int = new_node elif index == 0: UpperCAmelCase__ : str = self.head # link new_node to head UpperCAmelCase__ : Dict = new_node else: UpperCAmelCase__ : List[Any] = self.head for _ in range(index - 1 ): UpperCAmelCase__ : List[str] = temp.next UpperCAmelCase__ : Optional[int] = temp.next UpperCAmelCase__ : Dict = new_node def __UpperCAmelCase ( self ): # print every node data print(self ) def __UpperCAmelCase ( self ): return self.delete_nth(0 ) def __UpperCAmelCase ( self ): # delete from tail return self.delete_nth(len(self ) - 1 ) def __UpperCAmelCase ( self , _lowerCAmelCase = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("""List index out of range.""" ) UpperCAmelCase__ : List[Any] = self.head # default first node if index == 0: UpperCAmelCase__ : Union[str, Any] = self.head.next else: UpperCAmelCase__ : Optional[Any] = self.head for _ in range(index - 1 ): UpperCAmelCase__ : Optional[Any] = temp.next UpperCAmelCase__ : Union[str, Any] = temp.next UpperCAmelCase__ : List[Any] = temp.next.next return delete_node.data def __UpperCAmelCase ( self ): return self.head is None def __UpperCAmelCase ( self ): UpperCAmelCase__ : int = None UpperCAmelCase__ : Optional[Any] = self.head while current: # Store the current node's next node. UpperCAmelCase__ : List[Any] = current.next # Make the current node's next point backwards UpperCAmelCase__ : Optional[Any] = prev # Make the previous node be the current node UpperCAmelCase__ : int = current # Make the current node the next node (to progress iteration) UpperCAmelCase__ : Dict = next_node # Return prev in order to put the head at the end UpperCAmelCase__ : str = prev def _lowerCamelCase ( ) -> None: '''simple docstring''' UpperCAmelCase__ : Dict = LinkedList() assert linked_list.is_empty() is True assert str(__lowerCamelCase ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(__lowerCamelCase ) == i linked_list.insert_nth(__lowerCamelCase , i + 1 ) assert str(__lowerCamelCase ) == "->".join(str(__lowerCamelCase ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(__lowerCamelCase ) == "->".join(str(__lowerCamelCase ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(__lowerCamelCase ) == 9 assert str(__lowerCamelCase ) == "->".join(str(__lowerCamelCase ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): UpperCAmelCase__ : Any = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(__lowerCamelCase ) == "->".join(str(__lowerCamelCase ) for i in range(-8 , 1 ) ) def _lowerCamelCase ( ) -> None: '''simple docstring''' UpperCAmelCase__ : Any = [ -9, 100, Node(7734_5112 ), """dlrow olleH""", 7, 5555, 0, -192.55_555, """Hello, world!""", 77.9, Node(10 ), None, None, 12.20, ] UpperCAmelCase__ : List[str] = LinkedList() for i in test_input: linked_list.insert_tail(__lowerCamelCase ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(__lowerCamelCase ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head UpperCAmelCase__ : Any = linked_list.delete_head() assert result == -9 assert ( str(__lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail UpperCAmelCase__ : Tuple = linked_list.delete_tail() assert result == 12.2 assert ( str(__lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list UpperCAmelCase__ : str = linked_list.delete_nth(10 ) assert result is None assert ( str(__lowerCamelCase ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("""Hello again, world!""" ) ) assert ( str(__lowerCamelCase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(__lowerCamelCase ) assert ( str(__lowerCamelCase ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(__lowerCamelCase ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def _lowerCamelCase ( ) -> List[str]: '''simple docstring''' from doctest import testmod testmod() UpperCAmelCase__ : Optional[Any] = LinkedList() linked_list.insert_head(input("""Inserting 1st at head """ ).strip() ) linked_list.insert_head(input("""Inserting 2nd at head """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() linked_list.insert_tail(input("""\nInserting 1st at tail """ ).strip() ) linked_list.insert_tail(input("""Inserting 2nd at tail """ ).strip() ) print("""\nPrint list:""" ) linked_list.print_list() print("""\nDelete head""" ) linked_list.delete_head() print("""Delete tail""" ) linked_list.delete_tail() print("""\nPrint list:""" ) linked_list.print_list() print("""\nReverse linked list""" ) linked_list.reverse() print("""\nPrint list:""" ) linked_list.print_list() print("""\nString representation of linked list:""" ) print(__lowerCamelCase ) print("""\nReading/changing Node data using indexing:""" ) print(F"Element at Position 1: {linked_list[1]}" ) UpperCAmelCase__ : List[Any] = input("""Enter New Value: """ ).strip() print("""New list:""" ) print(__lowerCamelCase ) print(F"length of linked_list is : {len(__lowerCamelCase )}" ) if __name__ == "__main__": main()
79
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =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_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCamelCase : Tuple = logging.get_logger(__name__) __UpperCamelCase : List[Any] = { """EleutherAI/gpt-neox-20b""": """https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json""", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class __UpperCamelCase ( _lowerCAmelCase ): __snake_case :Dict = 'gpt_neox' def __init__( self : Optional[int] , _lowerCAmelCase : str=5_0432 , _lowerCAmelCase : Optional[Any]=6144 , _lowerCAmelCase : List[Any]=44 , _lowerCAmelCase : Union[str, Any]=64 , _lowerCAmelCase : List[str]=2_4576 , _lowerCAmelCase : List[Any]="gelu" , _lowerCAmelCase : str=0.25 , _lowerCAmelCase : List[Any]=1_0000 , _lowerCAmelCase : str=0.0 , _lowerCAmelCase : Any=0.0 , _lowerCAmelCase : int=0.1 , _lowerCAmelCase : List[str]=2048 , _lowerCAmelCase : Union[str, Any]=0.02 , _lowerCAmelCase : List[str]=1e-5 , _lowerCAmelCase : List[Any]=True , _lowerCAmelCase : List[str]=0 , _lowerCAmelCase : Dict=2 , _lowerCAmelCase : List[str]=False , _lowerCAmelCase : List[Any]=True , _lowerCAmelCase : Dict=None , **_lowerCAmelCase : str , ) -> Optional[Any]: """simple docstring""" super().__init__(bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , **_lowerCAmelCase ) __lowercase = vocab_size __lowercase = max_position_embeddings __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = rotary_pct __lowercase = rotary_emb_base __lowercase = attention_dropout __lowercase = hidden_dropout __lowercase = classifier_dropout __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = use_cache __lowercase = tie_word_embeddings __lowercase = use_parallel_residual __lowercase = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( """The hidden size is not divisble by the number of attention heads! Make sure to update them!""" ) def _a ( self : Any ) -> int: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _lowerCAmelCase ) 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}' ) __lowercase = self.rope_scaling.get("""type""" , _lowerCAmelCase ) __lowercase = self.rope_scaling.get("""factor""" , _lowerCAmelCase ) 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(_lowerCAmelCase , _lowerCAmelCase ) or rope_scaling_factor <= 1.0: raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}' )
80
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _snake_case : Optional[int] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = XGLMTokenizer __UpperCAmelCase : Union[str, Any] = XGLMTokenizerFast __UpperCAmelCase : List[Any] = True __UpperCAmelCase : Optional[Any] = True def __snake_case ( self : str ) -> int: super().setUp() # We have a SentencePiece fixture for testing __snake_case : Optional[int] = XGLMTokenizer(lowerCamelCase , keep_accents=lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : Optional[int] = "<pad>" __snake_case : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase ) , lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int ) -> Any: __snake_case : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(len(lowerCamelCase ) , 1008 ) def __snake_case ( self : str ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[int] ) -> Any: __snake_case : Any = XGLMTokenizer(lowerCamelCase , keep_accents=lowerCamelCase ) __snake_case : Dict = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __snake_case : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) __snake_case : Any = tokenizer.convert_tokens_to_ids(lowerCamelCase ) self.assertListEqual( lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __snake_case : Dict = tokenizer.convert_ids_to_tokens(lowerCamelCase ) self.assertListEqual( lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def __snake_case ( self : List[Any] ) -> Optional[int]: return XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) def __snake_case ( self : Optional[int] ) -> Optional[Any]: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCamelCase , f.name ) __snake_case : int = XGLMTokenizer(f.name , keep_accents=lowerCamelCase ) __snake_case : List[str] = pickle.dumps(lowerCamelCase ) pickle.loads(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> List[str]: if not self.test_rust_tokenizer: return __snake_case : Any = self.get_tokenizer() __snake_case : List[str] = self.get_rust_tokenizer() __snake_case : Optional[Any] = "I was born in 92000, and this is falsé." __snake_case : Optional[int] = tokenizer.tokenize(lowerCamelCase ) __snake_case : List[str] = rust_tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) __snake_case : List[Any] = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) __snake_case : Any = rust_tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) __snake_case : int = self.get_rust_tokenizer() __snake_case : Optional[int] = tokenizer.encode(lowerCamelCase ) __snake_case : List[Any] = rust_tokenizer.encode(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) @slow def __snake_case ( self : Optional[Any] ) -> List[str]: __snake_case : List[str] = "Hello World!" __snake_case : str = [2, 31227, 4447, 35] self.assertListEqual(lowerCamelCase , self.big_tokenizer.encode(lowerCamelCase ) ) @slow def __snake_case ( self : Any ) -> List[Any]: __snake_case : Optional[int] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off __snake_case : Any = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(lowerCamelCase , self.big_tokenizer.encode(lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> int: # fmt: off __snake_case : List[str] = { "input_ids": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase , model_name="facebook/xglm-564M" , padding=lowerCamelCase , )
81
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
0
"""simple docstring""" class lowercase__ : '''simple docstring''' def __init__( self : str ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = "" UpperCAmelCase_ = "" UpperCAmelCase_ = [] def lowercase__ ( self : List[Any] , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> int: '''simple docstring''' if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: UpperCAmelCase_ = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: UpperCAmelCase_ = self.__min_dist_top_down_dp(_UpperCAmelCase , n - 1 ) UpperCAmelCase_ = self.__min_dist_top_down_dp(m - 1 , _UpperCAmelCase ) UpperCAmelCase_ = self.__min_dist_top_down_dp(m - 1 , n - 1 ) UpperCAmelCase_ = 1 + min(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return self.dp[m][n] def lowercase__ ( self : str , _UpperCAmelCase : str , _UpperCAmelCase : str ) -> int: '''simple docstring''' UpperCAmelCase_ = worda UpperCAmelCase_ = worda UpperCAmelCase_ = [[-1 for _ in range(len(_UpperCAmelCase ) )] for _ in range(len(_UpperCAmelCase ) )] return self.__min_dist_top_down_dp(len(_UpperCAmelCase ) - 1 , len(_UpperCAmelCase ) - 1 ) def lowercase__ ( self : int , _UpperCAmelCase : str , _UpperCAmelCase : str ) -> int: '''simple docstring''' UpperCAmelCase_ = worda UpperCAmelCase_ = worda UpperCAmelCase_ = len(_UpperCAmelCase ) UpperCAmelCase_ = len(_UpperCAmelCase ) UpperCAmelCase_ = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty UpperCAmelCase_ = j elif j == 0: # second string is empty UpperCAmelCase_ = i elif worda[i - 1] == worda[j - 1]: # last characters are equal UpperCAmelCase_ = self.dp[i - 1][j - 1] else: UpperCAmelCase_ = self.dp[i][j - 1] UpperCAmelCase_ = self.dp[i - 1][j] UpperCAmelCase_ = self.dp[i - 1][j - 1] UpperCAmelCase_ = 1 + min(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return self.dp[m][n] if __name__ == "__main__": lowerCamelCase = EditDistance() print("""****************** Testing Edit Distance DP Algorithm ******************""") print() lowerCamelCase = input("""Enter the first string: """).strip() lowerCamelCase = input("""Enter the second string: """).strip() print() print(F"The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}") print(F"The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}") print() print("""*************** End of Testing Edit Distance DP Algorithm ***************""")
82
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
0
"""simple docstring""" from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class __snake_case ( _lowercase): def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = SMALL_MODEL_IDENTIFIER _lowerCamelCase : Union[str, Any] = '''pt''' _lowerCamelCase : Optional[int] = '''tf''' def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Any = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Optional[Any] ): """simple docstring""" _lowerCamelCase : Tuple = TFAutoModel.from_pretrained(self.test_model , from_pt=__lowerCAmelCase ) model_tf.save_pretrained(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Dict = '''mock_framework''' # Framework provided - return whatever the user provides _lowerCamelCase : str = FeaturesManager.determine_framework(self.test_model , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCAmelCase ) _lowerCamelCase : List[Any] = FeaturesManager.determine_framework(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCAmelCase ) _lowerCamelCase : int = FeaturesManager.determine_framework(__lowerCAmelCase , __lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(__lowerCAmelCase ) _lowerCamelCase : List[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) self.assertEqual(__lowerCAmelCase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Optional[Any] = FeaturesManager.determine_framework(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" _lowerCamelCase : List[str] = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ): _lowerCamelCase : Optional[int] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow _lowerCamelCase : List[str] = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): _lowerCamelCase : Optional[int] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_tf ) # Both in environment -> use PyTorch _lowerCamelCase : Optional[int] = MagicMock(return_value=__lowerCAmelCase ) _lowerCamelCase : Dict = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): _lowerCamelCase : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(__lowerCAmelCase , self.framework_pt ) # Both not in environment -> raise error _lowerCamelCase : Union[str, Any] = MagicMock(return_value=__lowerCAmelCase ) _lowerCamelCase : Tuple = MagicMock(return_value=__lowerCAmelCase ) with patch('''transformers.onnx.features.is_tf_available''' , __lowerCAmelCase ), patch( '''transformers.onnx.features.is_torch_available''' , __lowerCAmelCase ): with self.assertRaises(__lowerCAmelCase ): _lowerCamelCase : Any = FeaturesManager.determine_framework(self.test_model )
83
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self ): lowercase = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowercase = get_activation('gelu' ) self.assertTrue(torch.allclose(gelu_python(snake_case ) , torch_builtin(snake_case ) ) ) self.assertFalse(torch.allclose(gelu_python(snake_case ) , gelu_new(snake_case ) ) ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowercase = get_activation('gelu' ) lowercase = get_activation('gelu_10' ) lowercase = torch_builtin(snake_case ) lowercase = geluaa(snake_case ) lowercase = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(snake_case ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def SCREAMING_SNAKE_CASE__ ( self ): get_activation('gelu' ) get_activation('gelu_10' ) get_activation('gelu_fast' ) get_activation('gelu_new' ) get_activation('gelu_python' ) get_activation('gelu_pytorch_tanh' ) get_activation('linear' ) get_activation('mish' ) get_activation('quick_gelu' ) get_activation('relu' ) get_activation('sigmoid' ) get_activation('silu' ) get_activation('swish' ) get_activation('tanh' ) with self.assertRaises(snake_case ): get_activation('bogus' ) with self.assertRaises(snake_case ): get_activation(snake_case ) def SCREAMING_SNAKE_CASE__ ( self ): lowercase = get_activation('gelu' ) lowercase = 1 lowercase = get_activation('gelu' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(snake_case ): lowercase = acta.a
84
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
0
SCREAMING_SNAKE_CASE__ : Optional[int] = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
85
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
0
from __future__ import annotations __a :List[Any] = list[list[int]] # assigning initial values to the grid __a :Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution __a :Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def __snake_case ( __UpperCamelCase : Matrix ,__UpperCamelCase : int ,__UpperCamelCase : int ,__UpperCamelCase : int ): """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" if location := find_empty_location(__UpperCamelCase ): A_ , A_ = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 ,10 ): if is_safe(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ): A_ = digit if sudoku(__UpperCamelCase ) is not None: return grid A_ = 0 return None def __snake_case ( __UpperCamelCase : Matrix ): """simple docstring""" for row in grid: for cell in row: print(__UpperCamelCase ,end=" " ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print('\nExample grid:\n' + '=' * 20) print_solution(example_grid) print('\nExample grid solution:') __a :int = sudoku(example_grid) if solution is not None: print_solution(solution) else: print('Cannot find a solution.')
86
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class UpperCamelCase_ ( UpperCAmelCase__ ): '''simple docstring''' UpperCAmelCase__ = (PNDMScheduler,) UpperCAmelCase__ = (('''num_inference_steps''', 50),) def SCREAMING_SNAKE_CASE ( self : Dict , **UpperCAmelCase__ : Optional[int]) ->Optional[Any]: '''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 SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : int=0 , **UpperCAmelCase__ : str) ->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 SCREAMING_SNAKE_CASE ( self : int) ->Optional[int]: '''simple docstring''' pass def SCREAMING_SNAKE_CASE ( self : int , UpperCAmelCase__ : Union[str, Any]=0 , **UpperCAmelCase__ : Union[str, Any]) ->List[str]: '''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 SCREAMING_SNAKE_CASE ( self : Any , **UpperCAmelCase__ : Optional[int]) ->Union[str, Any]: '''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 SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->str: '''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 SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Any: '''simple docstring''' for timesteps in [100, 1_000]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Tuple) ->Optional[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 SCREAMING_SNAKE_CASE ( self : Any) ->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 SCREAMING_SNAKE_CASE ( self : Optional[Any]) ->Tuple: '''simple docstring''' for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Dict) ->Dict: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : str) ->Optional[int]: '''simple docstring''' for t in [1, 5, 10]: self.check_over_forward(time_step=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->str: '''simple docstring''' for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100]): self.check_over_forward(num_inference_steps=UpperCAmelCase__) def SCREAMING_SNAKE_CASE ( self : str) ->int: '''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 SCREAMING_SNAKE_CASE ( self : str) ->List[Any]: '''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 SCREAMING_SNAKE_CASE ( self : Optional[int]) ->List[Any]: '''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 SCREAMING_SNAKE_CASE ( self : Any) ->Any: '''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 SCREAMING_SNAKE_CASE ( self : str) ->Optional[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() - 230.0399) < 1e-2 assert abs(result_mean.item() - 0.2995) < 1e-3 def SCREAMING_SNAKE_CASE ( 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
87
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
0
"""simple docstring""" from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ : def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=10 , SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=None , ) -> Any: _lowerCamelCase : Dict = parent _lowerCamelCase : Dict = batch_size _lowerCamelCase : Optional[Any] = image_size _lowerCamelCase : Any = num_channels _lowerCamelCase : Any = embeddings_size _lowerCamelCase : Optional[int] = hidden_sizes _lowerCamelCase : Tuple = depths _lowerCamelCase : List[Any] = is_training _lowerCamelCase : int = use_labels _lowerCamelCase : str = hidden_act _lowerCamelCase : Dict = num_labels _lowerCamelCase : int = scope _lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) _lowerCamelCase : Dict = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_labels) _lowerCamelCase : Tuple = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self) -> Dict: 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 UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> Any: _lowerCamelCase : Optional[int] = TFRegNetModel(config=SCREAMING_SNAKE_CASE) _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCamelCase_ ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) -> int: _lowerCamelCase : Optional[Any] = self.num_labels _lowerCamelCase : List[str] = TFRegNetForImageClassification(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : Optional[int] = self.prepare_config_and_inputs() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = config_and_inputs _lowerCamelCase : Tuple = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowercase__ ( A_ ,A_ ,unittest.TestCase ): __UpperCAmelCase = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () __UpperCAmelCase = ( {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def UpperCamelCase_ ( self) -> List[str]: _lowerCamelCase : str = TFRegNetModelTester(self) _lowerCamelCase : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , has_text_modality=SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Optional[Any]: return @unittest.skip(reason="""RegNet does not use inputs_embeds""") def UpperCamelCase_ ( self) -> List[str]: 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 UpperCamelCase_ ( self) -> List[str]: super().test_keras_fit() @unittest.skip(reason="""RegNet does not support input and output embeddings""") def UpperCamelCase_ ( self) -> Optional[Any]: pass def UpperCamelCase_ ( self) -> Dict: _lowerCamelCase , _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCamelCase : Dict = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = inspect.signature(model.call) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCamelCase : Any = [*signature.parameters.keys()] _lowerCamelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): _lowerCamelCase : int = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) , training=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _lowerCamelCase : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE) , 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] , ) _lowerCamelCase , _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() _lowerCamelCase : Any = ["""basic""", """bottleneck"""] for model_class in self.all_model_classes: for layer_type in layers_type: _lowerCamelCase : Union[str, Any] = layer_type _lowerCamelCase : List[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _lowerCamelCase : Tuple = True check_hidden_states_output(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) def UpperCamelCase_ ( self) -> Union[str, Any]: _lowerCamelCase , _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE={}): _lowerCamelCase : int = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = model(SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE).to_tuple() def recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): if isinstance(SCREAMING_SNAKE_CASE , (List, Tuple)): for tuple_iterable_value, dict_iterable_value in zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE): recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE)) , msg=( """Tuple and dict output are not equal. Difference:""" F' {tf.math.reduce_max(tf.abs(tuple_object - dict_object))}' ) , ) recursive_check(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) for model_class in self.all_model_classes: _lowerCamelCase : Tuple = model_class(SCREAMING_SNAKE_CASE) _lowerCamelCase : str = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[int] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) _lowerCamelCase : int = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) _lowerCamelCase : Any = self._prepare_for_class(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , return_labels=SCREAMING_SNAKE_CASE) check_equivalence(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , {"""output_hidden_states""": True}) def UpperCamelCase_ ( self) -> Optional[int]: _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE) @slow def UpperCamelCase_ ( self) -> int: for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : List[str] = TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE) self.assertIsNotNone(SCREAMING_SNAKE_CASE) def _snake_case ( ): """simple docstring""" _lowerCamelCase : str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowercase__ ( unittest.TestCase ): @cached_property def UpperCamelCase_ ( self) -> Any: return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self) -> List[Any]: _lowerCamelCase : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]) _lowerCamelCase : Optional[int] = self.default_image_processor _lowerCamelCase : int = prepare_img() _lowerCamelCase : List[Any] = image_processor(images=SCREAMING_SNAKE_CASE , return_tensors="""tf""") # forward pass _lowerCamelCase : Dict = model(**SCREAMING_SNAKE_CASE , training=SCREAMING_SNAKE_CASE) # verify the logits _lowerCamelCase : Tuple = tf.TensorShape((1, 1000)) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE) _lowerCamelCase : Optional[Any] = tf.constant([-0.41_80, -1.50_51, -3.48_36]) tf.debugging.assert_near(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE , atol=1e-4)
88
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
import math SCREAMING_SNAKE_CASE : Union[str, Any] = 10 SCREAMING_SNAKE_CASE : Dict = 7 SCREAMING_SNAKE_CASE : List[str] = BALLS_PER_COLOUR * NUM_COLOURS def UpperCamelCase_( lowerCamelCase_ = 20 ) -> str: _lowercase : List[Any] = math.comb(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : Optional[int] = math.comb(NUM_BALLS - BALLS_PER_COLOUR , lowerCamelCase_ ) _lowercase : int = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(20))
89
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor __UpperCAmelCase = random.Random() def _snake_case ( A , A=1.0 , A=None , A=None ) -> int: if rng is None: lowerCAmelCase__ = global_rng lowerCAmelCase__ = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class a__ ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowerCamelCase_ , lowerCamelCase_=7 , lowerCamelCase_=4_00 , lowerCamelCase_=20_00 , lowerCamelCase_=24 , lowerCamelCase_=24 , lowerCamelCase_=0.0 , lowerCamelCase_=1_60_00 , lowerCamelCase_=True , lowerCamelCase_=True , ) -> Any: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = min_seq_length lowerCAmelCase__ = max_seq_length lowerCAmelCase__ = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowerCAmelCase__ = feature_size lowerCAmelCase__ = num_mel_bins lowerCAmelCase__ = padding_value lowerCAmelCase__ = sampling_rate lowerCAmelCase__ = return_attention_mask lowerCAmelCase__ = do_normalize def __SCREAMING_SNAKE_CASE ( self ) -> int: return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_=False , lowerCamelCase_=False ) -> List[str]: def _flatten(lowerCamelCase_ ): return list(itertools.chain(*lowerCamelCase_ ) ) if equal_length: lowerCAmelCase__ = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowerCAmelCase__ = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: lowerCAmelCase__ = [np.asarray(lowerCamelCase_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class a__ ( a__ , unittest.TestCase ): '''simple docstring''' lowercase__ : str = SpeechaTextFeatureExtractor if is_speech_available() else None def __SCREAMING_SNAKE_CASE ( self ) -> str: lowerCAmelCase__ = SpeechaTextFeatureExtractionTester(self ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Tuple: self.assertTrue(np.all(np.mean(lowerCamelCase_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(lowerCamelCase_ , axis=0 ) - 1 ) < 1e-3 ) ) def __SCREAMING_SNAKE_CASE ( self ) -> List[str]: # Tests that all call wrap to encode_plus and batch_encode_plus lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = [np.asarray(lowerCamelCase_ ) for speech_input in speech_inputs] # Test feature size lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input lowerCAmelCase__ = feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features lowerCAmelCase__ = feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) # Test batched lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , return_tensors='''np''' ).input_features lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. lowerCAmelCase__ = [floats_list((1, x) )[0] for x in (8_00, 8_00, 8_00)] lowerCAmelCase__ = np.asarray(lowerCamelCase_ ) lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , return_tensors='''np''' ).input_features lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(lowerCamelCase_ , lowerCamelCase_ ): self.assertTrue(np.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = ['''longest''', '''max_length''', '''do_not_pad'''] lowerCAmelCase__ = [None, 16, None] for max_length, padding in zip(lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase__ = feature_extractor( lowerCamelCase_ , padding=lowerCamelCase_ , max_length=lowerCamelCase_ , return_attention_mask=lowerCamelCase_ ) lowerCAmelCase__ = inputs.input_features lowerCAmelCase__ = inputs.attention_mask lowerCAmelCase__ = [np.sum(lowerCamelCase_ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = ['''longest''', '''max_length''', '''do_not_pad'''] lowerCAmelCase__ = [None, 16, None] for max_length, padding in zip(lowerCamelCase_ , lowerCamelCase_ ): lowerCAmelCase__ = feature_extractor( lowerCamelCase_ , max_length=lowerCamelCase_ , padding=lowerCamelCase_ , return_tensors='''np''' , return_attention_mask=lowerCamelCase_ ) lowerCAmelCase__ = inputs.input_features lowerCAmelCase__ = inputs.attention_mask lowerCAmelCase__ = [np.sum(lowerCamelCase_ ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def __SCREAMING_SNAKE_CASE ( self ) -> int: lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = feature_extractor( lowerCamelCase_ , padding='''max_length''' , max_length=4 , truncation=lowerCamelCase_ , return_tensors='''np''' , return_attention_mask=lowerCamelCase_ , ) lowerCAmelCase__ = inputs.input_features lowerCAmelCase__ = inputs.attention_mask lowerCAmelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def __SCREAMING_SNAKE_CASE ( self ) -> Dict: lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = feature_extractor( lowerCamelCase_ , padding='''longest''' , max_length=4 , truncation=lowerCamelCase_ , return_tensors='''np''' , return_attention_mask=lowerCamelCase_ , ) lowerCAmelCase__ = inputs.input_features lowerCAmelCase__ = inputs.attention_mask lowerCAmelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 24) ) lowerCAmelCase__ = [floats_list((1, x) )[0] for x in range(8_00 , 14_00 , 2_00 )] lowerCAmelCase__ = feature_extractor( lowerCamelCase_ , padding='''longest''' , max_length=16 , truncation=lowerCamelCase_ , return_tensors='''np''' , return_attention_mask=lowerCamelCase_ , ) lowerCAmelCase__ = inputs.input_features lowerCAmelCase__ = inputs.attention_mask lowerCAmelCase__ = np.sum(attention_mask == 1 , axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 24) ) def __SCREAMING_SNAKE_CASE ( self ) -> Any: import torch lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = np.random.rand(1_00 , 32 ).astype(np.floataa ) lowerCAmelCase__ = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowerCAmelCase__ = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) lowerCAmelCase__ = feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ ) -> Dict: from datasets import load_dataset lowerCAmelCase__ = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech lowerCAmelCase__ = ds.sort('''id''' ).select(range(lowerCamelCase_ ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def __SCREAMING_SNAKE_CASE ( self ) -> Dict: # fmt: off lowerCAmelCase__ = np.array([ -1.5_745, -1.7_713, -1.7_020, -1.6_069, -1.2_250, -1.1_105, -0.9_072, -0.8_241, -1.2_310, -0.8_098, -0.3_320, -0.4_101, -0.7_985, -0.4_996, -0.8_213, -0.9_128, -1.0_420, -1.1_286, -1.0_440, -0.7_999, -0.8_405, -1.2_275, -1.5_443, -1.4_625, ] ) # fmt: on lowerCAmelCase__ = self._load_datasamples(1 ) lowerCAmelCase__ = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowerCAmelCase__ = feature_extractor(lowerCamelCase_ , return_tensors='''pt''' ).input_features self.assertEquals(input_features.shape , (1, 5_84, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30] , lowerCamelCase_ , atol=1e-4 ) )
90
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
"""simple docstring""" import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel _lowercase = { '''text_branch''': '''text_model''', '''audio_branch''': '''audio_model.audio_encoder''', '''attn''': '''attention.self''', '''self.proj''': '''output.dense''', '''attention.self_mask''': '''attn_mask''', '''mlp.fc1''': '''intermediate.dense''', '''mlp.fc2''': '''output.dense''', '''norm1''': '''layernorm_before''', '''norm2''': '''layernorm_after''', '''bn0''': '''batch_norm''', } _lowercase = AutoFeatureExtractor.from_pretrained('''laion/clap-htsat-unfused''', truncation='''rand_trunc''') def _snake_case ( snake_case__ : List[str] , snake_case__ : Dict=False ): A , A = create_model( 'HTSAT-tiny' , 'roberta' , snake_case__ , precision='fp32' , device='cuda:0' if torch.cuda.is_available() else 'cpu' , enable_fusion=snake_case__ , fusion_type='aff_2d' if enable_fusion else None , ) return model, model_cfg def _snake_case ( snake_case__ : Dict ): A = {} A = r'.*sequential.(\d+).*' A = r'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: A = key.replace(snake_case__ , snake_case__ ) if re.match(snake_case__ , snake_case__ ): # replace sequential layers with list A = re.match(snake_case__ , snake_case__ ).group(1 ) A = key.replace(F'sequential.{sequential_layer}.' , F'layers.{int(snake_case__ )//3}.linear.' ) elif re.match(snake_case__ , snake_case__ ): A = int(re.match(snake_case__ , snake_case__ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... A = 1 if projecton_layer == 0 else 2 A = key.replace(F'_projection.{projecton_layer}.' , F'_projection.linear{transformers_projection_layer}.' ) if "audio" and "qkv" in key: # split qkv into query key and value A = value A = mixed_qkv.size(0 ) // 3 A = mixed_qkv[:qkv_dim] A = mixed_qkv[qkv_dim : qkv_dim * 2] A = mixed_qkv[qkv_dim * 2 :] A = query_layer A = key_layer A = value_layer else: A = value return model_state_dict def _snake_case ( snake_case__ : Optional[Any] , snake_case__ : Optional[Any] , snake_case__ : str , snake_case__ : str=False ): A , A = init_clap(snake_case__ , enable_fusion=snake_case__ ) clap_model.eval() A = clap_model.state_dict() A = rename_state_dict(snake_case__ ) A = ClapConfig() A = enable_fusion A = ClapModel(snake_case__ ) # ignore the spectrogram embedding layer model.load_state_dict(snake_case__ , strict=snake_case__ ) model.save_pretrained(snake_case__ ) transformers_config.save_pretrained(snake_case__ ) if __name__ == "__main__": _lowercase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument('''--enable_fusion''', action='''store_true''', help='''Whether to enable fusion or not''') _lowercase = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
91
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =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_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): UpperCamelCase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right UpperCamelCase_ = 128022 UpperCamelCase_ = 128028 @require_sentencepiece class __SCREAMING_SNAKE_CASE ( lowercase__ , unittest.TestCase ): lowerCamelCase_ = MaMaaaTokenizer lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = True def lowerCamelCase_ ( self : Dict ): '''simple docstring''' super().setUp() lowercase : Dict =['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>'''] lowercase : List[Any] =dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) lowercase : List[Any] =Path(self.tmpdirname ) save_json(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''vocab_file'''] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(UpperCAmelCase__ , save_dir / VOCAB_FILES_NAMES['''spm_file'''] ) lowercase : Tuple =MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase_ ( self : Any , **UpperCAmelCase__ : int ): '''simple docstring''' return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Dict ): '''simple docstring''' return ( "This is a test", "This is a test", ) def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : Tuple ='''</s>''' lowercase : Union[str, Any] =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 : List[str] ): '''simple docstring''' lowercase : List[Any] =self.get_tokenizer() lowercase : Optional[Any] =list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''</s>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''<s>''' ) self.assertEqual(len(UpperCAmelCase__ ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip('''Skip this test while all models are still to be uploaded.''' ) def lowerCamelCase_ ( self : Optional[int] ): '''simple docstring''' pass def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' lowercase : Union[str, Any] =self.get_tokenizer() lowercase : str =tokenizer.tokenize('''This is a test''' ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [2, 3, 4, 5, 6] , ) lowercase : Optional[int] =tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(UpperCAmelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) lowercase : Tuple =tokenizer.convert_tokens_to_string(UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , '''This is a test''' ) @slow def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' # fmt: off lowercase : int ={'''input_ids''': [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase__ , model_name='''facebook/m2m100_418M''' , revision='''c168bae485c864188cf9aa0e4108b0b6934dc91e''' , ) @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): lowerCamelCase_ = 'facebook/m2m100_418M' lowerCamelCase_ = [ 'In my opinion, there are two levels of response from the French government.', 'NSA Affair Emphasizes Complete Lack of Debate on Intelligence', ] lowerCamelCase_ = [ 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', ] # fmt: off lowerCamelCase_ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2] @classmethod def lowerCamelCase_ ( cls : Optional[Any] ): '''simple docstring''' lowercase : MaMaaaTokenizer =MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en''' , tgt_lang='''fr''' ) lowercase : Optional[int] =1 return cls def lowerCamelCase_ ( self : List[Any] ): '''simple docstring''' self.assertEqual(self.tokenizer.get_lang_id('''ar''' ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id('''en''' ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id('''ro''' ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id('''mr''' ) , 128063 ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : List[str] =self.tokenizer.get_vocab() self.assertEqual(len(UpperCAmelCase__ ) , self.tokenizer.vocab_size ) self.assertEqual(vocab['''<unk>'''] , 3 ) self.assertIn(self.tokenizer.get_lang_token('''en''' ) , UpperCAmelCase__ ) def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : List[Any] ='''en''' lowercase : Optional[Any] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' self.assertIn(UpperCAmelCase__ , self.tokenizer.all_special_ids ) # fmt: off lowercase : str =[FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on lowercase : Optional[Any] =self.tokenizer.decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) lowercase : Optional[Any] =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertNotIn(self.tokenizer.eos_token , UpperCAmelCase__ ) def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Any =tempfile.mkdtemp() lowercase : Tuple =self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(UpperCAmelCase__ ) lowercase : Union[str, Any] =MaMaaaTokenizer.from_pretrained(UpperCAmelCase__ ) self.assertDictEqual(new_tok.lang_token_to_id , UpperCAmelCase__ ) @require_torch def lowerCamelCase_ ( self : List[str] ): '''simple docstring''' lowercase : List[str] ='''en''' lowercase : int ='''fr''' lowercase : Union[str, Any] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=UpperCAmelCase__ , return_tensors='''pt''' ) lowercase : str =shift_tokens_right( batch['''labels'''] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: lowercase : int =batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def lowerCamelCase_ ( self : int ): '''simple docstring''' lowercase : Optional[int] ='''mr''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) lowercase : Union[str, Any] ='''zh''' self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def lowerCamelCase_ ( self : Union[str, Any] ): '''simple docstring''' lowercase : int ='''mr''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''mr''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) lowercase : Optional[Any] ='''zh''' self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('''zh''' )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def lowerCamelCase_ ( self : Any ): '''simple docstring''' lowercase : Optional[Any] =self.tokenizer._build_translation_inputs('''A test''' , return_tensors='''pt''' , src_lang='''en''' , tgt_lang='''ar''' ) self.assertEqual( nested_simplify(UpperCAmelCase__ ) , { # en_XX, A, test, EOS '''input_ids''': [[128022, 58, 4183, 2]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 128006, } , )
92
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =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() = }')
59
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Dict = tempfile.mkdtemp() # fmt: off lowerCAmelCase__ :List[str] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on lowerCAmelCase__ :Tuple = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) ) lowerCAmelCase__ :int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] lowerCAmelCase__ :List[Any] = {'unk_token': '<unk>'} lowerCAmelCase__ :Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCAmelCase__ :Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(__UpperCAmelCase ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(__UpperCAmelCase ) ) lowerCAmelCase__ :str = { 'do_resize': True, 'size': 2_0, 'do_center_crop': True, 'crop_size': 1_8, 'do_normalize': True, 'image_mean': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], 'image_std': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } lowerCAmelCase__ :Optional[Any] = os.path.join(self.tmpdirname , __UpperCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return CLIPTokenizer.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self , **__UpperCAmelCase ): '''simple docstring''' return ViTImageProcessor.from_pretrained(self.tmpdirname , **__UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] lowerCAmelCase__ :Optional[Any] = [Image.fromarray(np.moveaxis(__UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_tokenizer() lowerCAmelCase__ :str = self.get_rust_tokenizer() lowerCAmelCase__ :Optional[Any] = self.get_image_processor() lowerCAmelCase__ :Optional[Any] = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :Tuple = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=__UpperCAmelCase ) lowerCAmelCase__ :int = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :List[Any] = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , __UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Tuple = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ :str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCAmelCase__ :Optional[Any] = self.get_image_processor(do_normalize=__UpperCAmelCase , padding_value=1.0 ) lowerCAmelCase__ :str = CLIPSegProcessor.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 , __UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __UpperCAmelCase ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :List[str] = self.get_image_processor() lowerCAmelCase__ :Union[str, Any] = self.get_tokenizer() lowerCAmelCase__ :Tuple = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Any = self.prepare_image_inputs() lowerCAmelCase__ :int = image_processor(__UpperCAmelCase , return_tensors='np' ) lowerCAmelCase__ :Optional[Any] = processor(images=__UpperCAmelCase , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.get_image_processor() lowerCAmelCase__ :Dict = self.get_tokenizer() lowerCAmelCase__ :Tuple = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Any = 'lower newer' lowerCAmelCase__ :Any = processor(text=__UpperCAmelCase ) lowerCAmelCase__ :int = tokenizer(__UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = self.get_image_processor() lowerCAmelCase__ :int = self.get_tokenizer() lowerCAmelCase__ :Any = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = 'lower newer' lowerCAmelCase__ :Tuple = self.prepare_image_inputs() lowerCAmelCase__ :Any = processor(text=__UpperCAmelCase , images=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_image_processor() lowerCAmelCase__ :Union[str, Any] = self.get_tokenizer() lowerCAmelCase__ :Any = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = self.prepare_image_inputs() lowerCAmelCase__ :int = self.prepare_image_inputs() lowerCAmelCase__ :Dict = processor(images=__UpperCAmelCase , visual_prompt=__UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'conditional_pixel_values'] ) # test if it raises when no input is passed with pytest.raises(__UpperCAmelCase ): processor() def snake_case ( self ): '''simple docstring''' lowerCAmelCase__ :Optional[Any] = self.get_image_processor() lowerCAmelCase__ :Any = self.get_tokenizer() lowerCAmelCase__ :Dict = CLIPSegProcessor(tokenizer=__UpperCAmelCase , image_processor=__UpperCAmelCase ) lowerCAmelCase__ :int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase__ :List[Any] = processor.batch_decode(__UpperCAmelCase ) lowerCAmelCase__ :Optional[Any] = tokenizer.batch_decode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
93
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
'''simple docstring''' from __future__ import annotations import time from collections.abc import Sequence from random import randint from matplotlib import pyplot as plt def lowercase_ ( __A : Sequence[float] , __A : int , __A : int ) -> tuple[int | None, int | None, float]: """simple docstring""" if not arr: return None, None, 0 if low == high: return low, high, arr[low] lowercase : Dict =(low + high) // 2 lowercase , lowercase , lowercase : List[Any] =max_subarray(__A , __A , __A ) lowercase , lowercase , lowercase : int =max_subarray(__A , mid + 1 , __A ) lowercase , lowercase , lowercase : List[Any] =max_cross_sum(__A , __A , __A , __A ) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum return cross_left, cross_right, cross_sum def lowercase_ ( __A : Sequence[float] , __A : int , __A : int , __A : int ) -> tuple[int, int, float]: """simple docstring""" lowercase , lowercase : Any =float('''-inf''' ), -1 lowercase , lowercase : int =float('''-inf''' ), -1 lowercase : int | float =0 for i in range(__A , low - 1 , -1 ): summ += arr[i] if summ > left_sum: lowercase : str =summ lowercase : Tuple =i lowercase : Optional[Any] =0 for i in range(mid + 1 , high + 1 ): summ += arr[i] if summ > right_sum: lowercase : List[str] =summ lowercase : Tuple =i return max_left, max_right, (left_sum + right_sum) def lowercase_ ( __A : int ) -> float: """simple docstring""" lowercase : List[str] =[randint(1 , __A ) for _ in range(__A )] lowercase : str =time.time() max_subarray(__A , 0 , input_size - 1 ) lowercase : List[str] =time.time() return end - start def lowercase_ ( ) -> None: """simple docstring""" lowercase : Union[str, Any] =[1_0, 1_0_0, 1_0_0_0, 1_0_0_0_0, 5_0_0_0_0, 1_0_0_0_0_0, 2_0_0_0_0_0, 3_0_0_0_0_0, 4_0_0_0_0_0, 5_0_0_0_0_0] lowercase : Dict =[time_max_subarray(__A ) for input_size in input_sizes] print('''No of Inputs\t\tTime Taken''' ) for input_size, runtime in zip(__A , __A ): print(__A , '''\t\t''' , __A ) plt.plot(__A , __A ) plt.xlabel('''Number of Inputs''' ) plt.ylabel('''Time taken in seconds''' ) plt.show() if __name__ == "__main__": from doctest import testmod testmod()
94
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
"""simple docstring""" def snake_case ( A__ ,A__ ): UpperCAmelCase_ : int = len(A__ ) UpperCAmelCase_ : List[str] = [] for i in range(len(A__ ) - pat_len + 1 ): UpperCAmelCase_ : Union[str, Any] = True for j in range(A__ ): if s[i + j] != pattern[j]: UpperCAmelCase_ : int = False break if match_found: position.append(A__ ) return position if __name__ == "__main__": assert naive_pattern_search('''ABCDEFG''', '''DE''') == [3] print(naive_pattern_search('''ABAAABCDBBABCDDEBCABC''', '''ABC'''))
95
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
"""simple docstring""" from __future__ import annotations def a ( __UpperCAmelCase : list[float] ) -> bool: if len(__UpperCAmelCase ) < 2: raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" ) if any(i <= 0 for i in nums ): raise ValueError("""All values must be greater than 0""" ) __magic_name__: List[Any] = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
96
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
import requests def a ( snake_case__: str , snake_case__: str ): '''simple docstring''' lowercase_ = {'''Content-Type''': '''application/json'''} lowercase_ = requests.post(snake_case__ , json={'''text''': message_body} , headers=snake_case__ ) if response.status_code != 200: lowercase_ = ( '''Request to slack returned an error ''' F'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(snake_case__ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
97
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
'''simple docstring''' # Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def a__ ( lowercase : List[Any], lowercase : Optional[int], lowercase : Any ) -> Dict: """simple docstring""" _UpperCamelCase = { '''en''': '''Machine learning is great, isn\'t it?''', '''ru''': '''Машинное обучение - это здорово, не так ли?''', '''de''': '''Maschinelles Lernen ist großartig, oder?''', } # BLUE scores as follows: # "pair": [fairseq, transformers] _UpperCamelCase = { '''ru-en''': ['''[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)''', '''39.20'''], '''en-ru''': ['''[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)''', '''33.47'''], '''en-de''': ['''[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)''', '''42.83'''], '''de-en''': ['''[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)''', '''41.35'''], } _UpperCamelCase = F"""{src_lang}-{tgt_lang}""" _UpperCamelCase = F""" --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt19 - facebook license: apache-2.0 datasets: - wmt19 metrics: - bleu --- # FSMT ## Model description This is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}. For more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616). The abbreviation FSMT stands for FairSeqMachineTranslation All four models are available: * [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) * [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en) * [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de) * [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = \"facebook/wmt19-{src_lang}-{tgt_lang}\" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = \"{texts[src_lang]}\" input_ids = tokenizer.encode(input, return_tensors=\"pt\") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias - The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981) ## Training data Pretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616). ## Eval results pair | fairseq | transformers -------|---------|---------- {pair} | {scores[pair][0]} | {scores[pair][1]} The score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support: - model ensemble, therefore the best performing checkpoint was ported (``model4.pt``). - re-ranking The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=15 mkdir -p $DATA_DIR sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` note: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`. ## Data Sources - [training, etc.](http://www.statmt.org/wmt19/) - [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561) ### BibTeX entry and citation info ```bibtex @inproceedings{{..., year={{2020}}, title={{Facebook FAIR's WMT19 News Translation Task Submission}}, author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}}, booktitle={{Proc. of WMT}}, }} ``` ## TODO - port model ensemble (fairseq uses 4 model checkpoints) """ os.makedirs(lowercase, exist_ok=lowercase ) _UpperCamelCase = os.path.join(lowercase, '''README.md''' ) print(F"""Generating {path}""" ) with open(lowercase, '''w''', encoding='''utf-8''' ) as f: f.write(lowercase ) # make sure we are under the root of the project lowercase__ : Tuple = Path(__file__).resolve().parent.parent.parent lowercase__ : List[Any] = repo_dir / 'model_cards' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowercase__ , lowercase__ , lowercase__ : Tuple = model_name.split('-') lowercase__ : int = model_cards_dir / 'facebook' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
98
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } SCREAMING_SNAKE_CASE = { 'vocab_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json'}, 'merges_file': {'ctrl': 'https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt'}, } SCREAMING_SNAKE_CASE = { 'ctrl': 2_5_6, } SCREAMING_SNAKE_CASE = { 'Pregnancy': 1_6_8_6_2_9, 'Christianity': 7_6_7_5, 'Explain': 1_0_6_4_2_3, 'Fitness': 6_3_4_4_0, 'Saving': 6_3_1_6_3, 'Ask': 2_7_1_7_1, 'Ass': 9_5_9_8_5, 'Joke': 1_6_3_5_0_9, 'Questions': 4_5_6_2_2, 'Thoughts': 4_9_6_0_5, 'Retail': 5_2_3_4_2, 'Feminism': 1_6_4_3_3_8, 'Writing': 1_1_9_9_2, 'Atheism': 1_9_2_2_6_3, 'Netflix': 4_8_6_1_6, 'Computing': 3_9_6_3_9, 'Opinion': 4_3_2_1_3, 'Alone': 4_4_9_6_7, 'Funny': 5_8_9_1_7, 'Gaming': 4_0_3_5_8, 'Human': 4_0_8_8, 'India': 1_3_3_1, 'Joker': 7_7_1_3_8, 'Diet': 3_6_2_0_6, 'Legal': 1_1_8_5_9, 'Norman': 4_9_3_9, 'Tip': 7_2_6_8_9, 'Weight': 5_2_3_4_3, 'Movies': 4_6_2_7_3, 'Running': 2_3_4_2_5, 'Science': 2_0_9_0, 'Horror': 3_7_7_9_3, 'Confession': 6_0_5_7_2, 'Finance': 1_2_2_5_0, 'Politics': 1_6_3_6_0, 'Scary': 1_9_1_9_8_5, 'Support': 1_2_6_5_4, 'Technologies': 3_2_5_1_6, 'Teenage': 6_6_1_6_0, 'Event': 3_2_7_6_9, 'Learned': 6_7_4_6_0, 'Notion': 1_8_2_7_7_0, 'Wikipedia': 3_7_5_8_3, 'Books': 6_6_6_5, 'Extract': 7_6_0_5_0, 'Confessions': 1_0_2_7_0_1, 'Conspiracy': 7_5_9_3_2, 'Links': 6_3_6_7_4, 'Narcissus': 1_5_0_4_2_5, 'Relationship': 5_4_7_6_6, 'Relationships': 1_3_4_7_9_6, 'Reviews': 4_1_6_7_1, 'News': 4_2_5_6, 'Translation': 2_6_8_2_0, 'multilingual': 1_2_8_4_0_6, } def a (lowerCAmelCase__ ): __a = set() __a = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __a = char __a = set(lowerCAmelCase__ ) return pairs class __UpperCAmelCase ( __A ): """simple docstring""" _lowerCamelCase = VOCAB_FILES_NAMES _lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase = CONTROL_CODES def __init__( self , __A , __A , __A="<unk>" , **__A ): super().__init__(unk_token=__A , **__A ) with open(__A , encoding="""utf-8""" ) as vocab_handle: __a = json.load(__A ) __a = {v: k for k, v in self.encoder.items()} with open(__A , encoding="""utf-8""" ) as merges_handle: __a = merges_handle.read().split("""\n""" )[1:-1] __a = [tuple(merge.split() ) for merge in merges] __a = dict(zip(__A , range(len(__A ) ) ) ) __a = {} @property def snake_case_ ( self ): return len(self.encoder ) def snake_case_ ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def snake_case_ ( self , __A ): if token in self.cache: return self.cache[token] __a = tuple(__A ) __a = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) __a = get_pairs(__A ) if not pairs: return token while True: __a = min(__A , key=lambda __A : self.bpe_ranks.get(__A , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break __a , __a = bigram __a = [] __a = 0 while i < len(__A ): try: __a = word.index(__A , __A ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __a = j if word[i] == first and i < len(__A ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __a = tuple(__A ) __a = new_word if len(__A ) == 1: break else: __a = get_pairs(__A ) __a = """@@ """.join(__A ) __a = word[:-4] __a = word return word def snake_case_ ( self , __A ): __a = [] __a = re.findall(R"""\S+\n?""" , __A ) for token in words: split_tokens.extend(list(self.bpe(__A ).split(""" """ ) ) ) return split_tokens def snake_case_ ( self , __A ): return self.encoder.get(__A , self.encoder.get(self.unk_token ) ) def snake_case_ ( self , __A ): return self.decoder.get(__A , self.unk_token ) def snake_case_ ( self , __A ): __a = """ """.join(__A ).replace("""@@ """ , """""" ).strip() return out_string def snake_case_ ( self , __A , __A = None ): if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __a = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __a = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(__A , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__A , ensure_ascii=__A ) + """\n""" ) __a = 0 with open(__A , """w""" , encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __A : kv[1] ): if index != token_index: logger.warning( f'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' """ Please check that the tokenizer is not corrupted!""" ) __a = token_index writer.write(""" """.join(__A ) + """\n""" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
99
import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowercase_ = XLMProphetNetTokenizer lowercase_ = False lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase__: Any =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) tokenizer.save_pretrained(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' lowerCamelCase__: List[Any] ="[PAD]" lowerCamelCase__: Tuple =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCAmelCase_) , UpperCAmelCase_) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCAmelCase_) , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Dict) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "[PAD]") self.assertEqual(vocab_keys[1] , "[CLS]") self.assertEqual(vocab_keys[-1] , "j") self.assertEqual(len(UpperCAmelCase_) , 1_012) def SCREAMING_SNAKE_CASE_ (self : Dict) ->Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_012) def SCREAMING_SNAKE_CASE_ (self : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =XLMProphetNetTokenizer(UpperCAmelCase_ , keep_accents=UpperCAmelCase_) lowerCamelCase__: Tuple =tokenizer.tokenize("This is a test") self.assertListEqual(UpperCAmelCase_ , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCAmelCase_) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase__: Optional[Any] =tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase__: Any =tokenizer.convert_tokens_to_ids(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) lowerCamelCase__: Any =tokenizer.convert_ids_to_tokens(UpperCAmelCase_) self.assertListEqual( UpperCAmelCase_ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "[UNK]", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "[UNK]", ".", ] , ) @cached_property def SCREAMING_SNAKE_CASE_ (self : Any) ->int: '''simple docstring''' return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased") @slow def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[str]: '''simple docstring''' lowerCamelCase__: Optional[int] ="Hello World!" lowerCamelCase__: Dict =[35_389, 6_672, 49, 2] self.assertListEqual(UpperCAmelCase_ , self.big_tokenizer.encode(UpperCAmelCase_)) @slow def SCREAMING_SNAKE_CASE_ (self : int) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: Any ={"input_ids": [[11_073, 82_783, 18, 26, 82_783, 549, 51_540, 248, 17_209, 1_301, 217, 20, 215_186, 1_325, 147, 17_209, 1_301, 217, 20, 56_370, 53, 122_020, 20, 16_477, 27, 87_355, 4_548, 20, 4_728, 78_392, 17, 159_969, 18, 26, 24_491, 629, 15, 538, 22_704, 5_439, 15, 2_788, 24_491, 9_885, 15, 43_534, 605, 15, 814, 18_403, 33_200, 29, 15, 43_534, 24_458, 12_410, 111, 24_966, 83_669, 9_637, 144_068, 26, 850, 22_346, 27, 147, 24_966, 83_669, 83_490, 26, 39_113, 735, 27, 689, 656, 2_800, 1_339, 4_600, 53, 122_020, 115_785, 34, 816, 1_339, 46_887, 18, 147, 53_905, 1_951, 42_238, 41_170, 17_732, 834, 436, 15, 27_523, 98_733, 217, 147, 5_542, 4_981, 930, 17_347, 16, 2], [20_091, 629, 94, 82_786, 58, 490, 20, 1_528, 84, 53_905, 344, 80_592, 110_128, 18_822, 5_267, 1_306, 62, 152_537, 308, 7_997, 401, 124_427, 549, 35_442, 225, 109, 15_055, 25_748, 147, 7_119, 43_712, 34, 767, 135_366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63_784, 119_466, 17, 147_808, 88_214, 18, 656, 81, 32, 3_296, 10_280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCAmelCase_ , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
59
0
def __snake_case ( ) -> int: return 1 def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else ten_pence(x - 1_0 ) + five_pence(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else twenty_pence(x - 2_0 ) + ten_pence(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else fifty_pence(x - 5_0 ) + twenty_pence(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else one_pound(x - 1_0_0 ) + fifty_pence(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ ) -> int: return 0 if x < 0 else two_pound(x - 2_0_0 ) + one_pound(lowerCAmelCase_ ) def __snake_case ( lowerCAmelCase_ = 2_0_0 ) -> int: return two_pound(lowerCAmelCase_ ) if __name__ == "__main__": print(solution(int(input().strip())))
100
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : List[str]) ->str: '''simple docstring''' lowerCamelCase__: Union[str, Any] ="ylacombe/bark-small" lowerCamelCase__: Tuple =tempfile.mkdtemp() lowerCamelCase__: Tuple ="en_speaker_1" lowerCamelCase__: Optional[int] ="This is a test string" lowerCamelCase__: List[str] ="speaker_embeddings_path.json" lowerCamelCase__: int ="speaker_embeddings" def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , **UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' return AutoTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Union[str, Any]: '''simple docstring''' shutil.rmtree(self.tmpdirname) def SCREAMING_SNAKE_CASE_ (self : int) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =self.get_tokenizer() lowerCamelCase__: List[str] =BarkProcessor(tokenizer=UpperCAmelCase_) processor.save_pretrained(self.tmpdirname) lowerCamelCase__: Dict =BarkProcessor.from_pretrained(self.tmpdirname) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab()) @slow def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: Tuple =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowerCamelCase__: Dict =self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)") lowerCamelCase__: Any =BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="(BOS)" , eos_token="(EOS)" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab()) def SCREAMING_SNAKE_CASE_ (self : List[Any]) ->int: '''simple docstring''' lowerCamelCase__: Any =BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowerCamelCase__: List[str] =35 lowerCamelCase__: Optional[Any] =2 lowerCamelCase__: Optional[Any] =8 lowerCamelCase__: Optional[int] ={ "semantic_prompt": np.ones(UpperCAmelCase_), "coarse_prompt": np.ones((nb_codebooks_coarse, seq_len)), "fine_prompt": np.ones((nb_codebooks_total, seq_len)), } # test providing already loaded voice_preset lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: int =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from npz file lowerCamelCase__: Union[str, Any] =os.path.join(self.tmpdirname , "file.npz") np.savez(UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: Tuple =processor(text=self.input_string , voice_preset=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =inputs["history_prompt"] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(UpperCAmelCase_ , np.array([])).tolist()) # test loading voice preset from the hub lowerCamelCase__: Any =processor(text=self.input_string , voice_preset=self.voice_preset) def SCREAMING_SNAKE_CASE_ (self : Tuple) ->Union[str, Any]: '''simple docstring''' lowerCamelCase__: str =self.get_tokenizer() lowerCamelCase__: Dict =BarkProcessor(tokenizer=UpperCAmelCase_) lowerCamelCase__: List[Any] =processor(text=self.input_string) lowerCamelCase__: Optional[int] =tokenizer( self.input_string , padding="max_length" , max_length=256 , add_special_tokens=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist())
59
0
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowercase : """simple docstring""" def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=1_3 , lowerCAmelCase__=3 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=2_2_4 , lowerCAmelCase__=1_0_0_0 , lowerCAmelCase__=[3, 3, 6, 4] , lowerCAmelCase__=[4_8, 5_6, 1_1_2, 2_2_0] , ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = parent SCREAMING_SNAKE_CASE_ : Optional[int] = batch_size SCREAMING_SNAKE_CASE_ : Optional[int] = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = is_training SCREAMING_SNAKE_CASE_ : str = use_labels SCREAMING_SNAKE_CASE_ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE_ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE_ : int = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = image_size SCREAMING_SNAKE_CASE_ : Optional[Any] = layer_depths SCREAMING_SNAKE_CASE_ : List[Any] = embed_dims def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE_ : Dict = self.get_config() return config, pixel_values, labels def UpperCamelCase__ ( self ): """simple docstring""" return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='gelu' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowerCAmelCase__ , layer_scale_init_value=1E-5 , ) def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = SwiftFormerModel(config=lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() SCREAMING_SNAKE_CASE_ : int = model(lowerCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = self.num_labels SCREAMING_SNAKE_CASE_ : str = SwiftFormerForImageClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() SCREAMING_SNAKE_CASE_ : Optional[int] = model(lowerCAmelCase__ , labels=lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) SCREAMING_SNAKE_CASE_ : Tuple = SwiftFormerForImageClassification(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() SCREAMING_SNAKE_CASE_ : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE_ : str = model(lowerCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ ( self ): """simple docstring""" ((SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_) , (SCREAMING_SNAKE_CASE_)) : Optional[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ : str = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __lowercase (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _UpperCAmelCase = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () _UpperCAmelCase = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = SwiftFormerModelTester(self ) SCREAMING_SNAKE_CASE_ : str = ConfigTester( self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ , hidden_size=3_7 , num_attention_heads=1_2 , num_hidden_layers=1_2 , ) def UpperCamelCase__ ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='SwiftFormer does not use inputs_embeds' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : str = model_class(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCAmelCase__ , nn.Linear ) ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : int = model_class(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ ) @slow def UpperCamelCase__ ( self ): """simple docstring""" for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : Optional[int] = SwiftFormerModel.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) @unittest.skip(reason='SwiftFormer does not output attentions' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def UpperCamelCase__ ( self ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : Tuple = model_class(lowerCAmelCase__ ) model.to(lowerCAmelCase__ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) ) SCREAMING_SNAKE_CASE_ : List[str] = outputs.hidden_states SCREAMING_SNAKE_CASE_ : Any = 8 self.assertEqual(len(lowerCAmelCase__ ) , lowerCAmelCase__ ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowerCAmelCase__ ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : str = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : Dict = True check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) def UpperCamelCase__ ( self ): """simple docstring""" def _config_zero_init(lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : List[str] = copy.deepcopy(lowerCAmelCase__ ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowerCAmelCase__ , lowerCAmelCase__ , 1E-10 ) if isinstance(getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE_ : int = _config_zero_init(getattr(lowerCAmelCase__ , lowerCAmelCase__ ) ) setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return configs_no_init SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE_ : List[Any] = _config_zero_init(lowerCAmelCase__ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : str = model_class(config=lowerCAmelCase__ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def UpperCamelCase__ ( self ): """simple docstring""" pass def a__ ( ): SCREAMING_SNAKE_CASE_ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __lowercase (unittest.TestCase ): """simple docstring""" @cached_property def UpperCamelCase__ ( self ): """simple docstring""" return ViTImageProcessor.from_pretrained('MBZUAI/swiftformer-xs' ) if is_vision_available() else None @slow def UpperCamelCase__ ( self ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = SwiftFormerForImageClassification.from_pretrained('MBZUAI/swiftformer-xs' ).to(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE_ : Any = prepare_img() SCREAMING_SNAKE_CASE_ : List[str] = image_processor(images=lowerCAmelCase__ , return_tensors='pt' ).to(lowerCAmelCase__ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[str] = model(**lowerCAmelCase__ ) # verify the logits SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ : str = torch.tensor([[-2.1_703E00, 2.1_107E00, -2.0_811E00]] ).to(lowerCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4 ) )
101
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "CLIPImageProcessor" lowercase_ = ("XLMRobertaTokenizer", "XLMRobertaTokenizerFast") def __init__(self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : List[str]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =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_ , ) lowerCamelCase__: int =kwargs.pop("feature_extractor") lowerCamelCase__: int =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) def __call__(self : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , **UpperCAmelCase_ : Any) ->Union[str, Any]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: List[Any] =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: int =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: str =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[Any]) ->Dict: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , *UpperCAmelCase_ : int , **UpperCAmelCase_ : Any) ->Optional[Any]: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.tokenizer.model_input_names lowerCamelCase__: str =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
59
0
"""simple docstring""" import heapq import sys import numpy as np __magic_name__ : Optional[int] = tuple[int, int] class lowercase__ : """simple docstring""" def __init__( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = [] UpperCamelCase : str = set() def _a ( self ): '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float("""inf""" ) def _a ( self ): '''simple docstring''' return len(self.elements ) == 0 def _a ( self , _A , _A ): '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(_A ) else: # update # print("update", item) UpperCamelCase : int = [] ((UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((UpperCamelCase) , (UpperCamelCase)) : Any = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def _a ( self , _A ): '''simple docstring''' if item in self.set: self.set.remove(_A ) UpperCamelCase : int = [] ((UpperCamelCase) , (UpperCamelCase)) : Optional[Any] = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((UpperCamelCase) , (UpperCamelCase)) : Any = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def _a ( self ): '''simple docstring''' return self.elements[0][1] def _a ( self ): '''simple docstring''' ((UpperCamelCase) , (UpperCamelCase)) : List[str] = heapq.heappop(self.elements ) self.set.remove(_A ) return (priority, item) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # euclidean distance UpperCamelCase : Tuple = np.array(SCREAMING_SNAKE_CASE ) UpperCamelCase : Dict = np.array(SCREAMING_SNAKE_CASE ) return np.linalg.norm(a - b ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # integer division by time variable return consistent_heuristic(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) // t def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Union[str, Any] = g_function[start] + Wa * heuristics[i](SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return ans def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : List[Any] = np.chararray((n, n) ) for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): UpperCamelCase : Dict = """*""" for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): if (j, (n - 1) - i) in blocks: UpperCamelCase : Any = """#""" UpperCamelCase : Tuple = """-""" UpperCamelCase : str = back_pointer[goal] while x != start: ((UpperCamelCase) , (UpperCamelCase)) : Any = x # print(x) UpperCamelCase : Any = """-""" UpperCamelCase : Optional[Any] = back_pointer[x] UpperCamelCase : List[str] = """-""" for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): if (i, j) == (0, n - 1): print(grid[i][j] , end=""" """ ) print("""<-- End position""" , end=""" """ ) else: print(grid[i][j] , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) print("""PATH TAKEN BY THE ALGORITHM IS:-""" ) UpperCamelCase : Union[str, Any] = back_pointer[goal] while x != start: print(SCREAMING_SNAKE_CASE , end=""" """ ) UpperCamelCase : Optional[Any] = back_pointer[x] print(SCREAMING_SNAKE_CASE ) sys.exit() def UpperCamelCase (SCREAMING_SNAKE_CASE ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ): for itera in range(SCREAMING_SNAKE_CASE ): open_list[itera].remove_element(SCREAMING_SNAKE_CASE ) # print("s", s) # print("j", j) ((UpperCamelCase) , (UpperCamelCase)) : List[Any] = s UpperCamelCase : Tuple = (x - 1, y) UpperCamelCase : Union[str, Any] = (x + 1, y) UpperCamelCase : int = (x, y + 1) UpperCamelCase : Tuple = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(SCREAMING_SNAKE_CASE ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(SCREAMING_SNAKE_CASE ) UpperCamelCase : Dict = -1 UpperCamelCase : Union[str, Any] = float("""inf""" ) if valid(SCREAMING_SNAKE_CASE ) and g_function[neighbours] > g_function[s] + 1: UpperCamelCase : Optional[int] = g_function[s] + 1 UpperCamelCase : Optional[int] = s if neighbours not in close_list_anchor: open_list[0].put(SCREAMING_SNAKE_CASE , key(SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) if neighbours not in close_list_inad: for var in range(1 , SCREAMING_SNAKE_CASE ): if key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) <= Wa * key( SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): open_list[j].put( SCREAMING_SNAKE_CASE , key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) def UpperCamelCase (): UpperCamelCase : Optional[Any] = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list __magic_name__ : Optional[int] = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} __magic_name__ : Tuple = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (1_0, 1), (1_1, 1), (1_2, 1), (1_3, 1), (1_4, 1), (1_5, 1), (1_6, 1), (1_7, 1), (1_8, 1), (1_9, 1), ] __magic_name__ : Tuple = make_common_ground() __magic_name__ : List[Any] = blocks_blk # hyper parameters __magic_name__ : Union[str, Any] = 1 __magic_name__ : Tuple = 1 __magic_name__ : int = 2_0 __magic_name__ : Tuple = 3 # one consistent and two other inconsistent # start and end destination __magic_name__ : Any = (0, 0) __magic_name__ : Optional[int] = (n - 1, n - 1) __magic_name__ : List[Any] = 1 def UpperCamelCase (SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): UpperCamelCase : Any = {start: 0, goal: float("""inf""" )} UpperCamelCase : List[str] = {start: -1, goal: -1} UpperCamelCase : Tuple = [] UpperCamelCase : Dict = set() for i in range(SCREAMING_SNAKE_CASE ): open_list.append(PriorityQueue() ) open_list[i].put(SCREAMING_SNAKE_CASE , key(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) UpperCamelCase : list[int] = [] UpperCamelCase : list[int] = [] while open_list[0].minkey() < float("""inf""" ): for i in range(1 , SCREAMING_SNAKE_CASE ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("""inf""" ): do_something(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: UpperCamelCase , UpperCamelCase : Any = open_list[i].top_show() visited.add(SCREAMING_SNAKE_CASE ) expand_state( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) close_list_inad.append(SCREAMING_SNAKE_CASE ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("""inf""" ): do_something(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) else: UpperCamelCase : List[Any] = open_list[0].top_show() visited.add(SCREAMING_SNAKE_CASE ) expand_state( SCREAMING_SNAKE_CASE , 0 , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) close_list_anchor.append(SCREAMING_SNAKE_CASE ) print("""No path found to goal""" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(SCREAMING_SNAKE_CASE ): if (j, i) in blocks: print("""#""" , end=""" """ ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("""*""" , end=""" """ ) else: print("""-""" , end=""" """ ) else: print("""*""" , end=""" """ ) if (j, i) == (n - 1, n - 1): print("""<-- End position""" , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
102
from datetime import datetime import matplotlib.pyplot as plt import torch def lowerCAmelCase_ ( __a ) -> Any: """simple docstring""" for param in module.parameters(): lowerCamelCase__: Tuple =False def lowerCAmelCase_ ( ) -> Optional[int]: """simple docstring""" lowerCamelCase__: List[str] ="cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCamelCase__: str ="mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" lowerCamelCase__: Union[str, Any] =plt.imshow(__a ) fig.axes.get_xaxis().set_visible(__a ) fig.axes.get_yaxis().set_visible(__a ) plt.show() def lowerCAmelCase_ ( ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: List[str] =datetime.now() lowerCamelCase__: str =current_time.strftime("%H:%M:%S" ) return timestamp
59
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self : List[str] ): """simple docstring""" # test for the above condition self.test() def __UpperCAmelCase ( self : List[Any] ): """simple docstring""" _snake_case = 0 _snake_case = False while not completed: if counter == 1: self.reset() _snake_case = self.advance() if not self.does_advance(__lowerCamelCase ): raise Exception( '''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' ) _snake_case , _snake_case , _snake_case = self.update(__lowerCamelCase ) counter += 1 if counter > 1_0_0_0_0: raise Exception('''update() does not fulfill the constraint.''' ) if self.remaining() != 0: raise Exception('''Custom Constraint is not defined correctly.''' ) @abstractmethod def __UpperCAmelCase ( self : Tuple ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self : Tuple , __lowerCamelCase : int ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : int ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self : int ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self : int ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def __UpperCAmelCase ( self : Any , __lowerCamelCase : Optional[Any]=False ): """simple docstring""" raise NotImplementedError( f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self : Dict , __lowerCamelCase : List[int] ): """simple docstring""" super(__lowerCamelCase , self ).__init__() if not isinstance(__lowerCamelCase , __lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(f"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(__lowerCamelCase , __lowerCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(f"""Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.""" ) _snake_case = token_ids _snake_case = len(self.token_ids ) _snake_case = -1 # the index of the currently fulfilled step _snake_case = False def __UpperCAmelCase ( self : str ): """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def __UpperCAmelCase ( self : int , __lowerCamelCase : int ): """simple docstring""" if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : int ): """simple docstring""" if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(f"""`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) _snake_case = False _snake_case = False _snake_case = False if self.does_advance(__lowerCamelCase ): self.fulfilled_idx += 1 _snake_case = True if self.fulfilled_idx == (self.seqlen - 1): _snake_case = True _snake_case = completed else: # failed to make progress. _snake_case = True self.reset() return stepped, completed, reset def __UpperCAmelCase ( self : List[str] ): """simple docstring""" _snake_case = False _snake_case = 0 def __UpperCAmelCase ( self : Dict ): """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : str=False ): """simple docstring""" _snake_case = PhrasalConstraint(self.token_ids ) if stateful: _snake_case = self.seqlen _snake_case = self.fulfilled_idx _snake_case = self.completed return new_constraint class UpperCAmelCase : def __init__( self : Optional[Any] , __lowerCamelCase : List[List[int]] , __lowerCamelCase : Optional[Any]=True ): """simple docstring""" _snake_case = max([len(__lowerCamelCase ) for one in nested_token_ids] ) _snake_case = {} for token_ids in nested_token_ids: _snake_case = root for tidx, token_id in enumerate(__lowerCamelCase ): if token_id not in level: _snake_case = {} _snake_case = level[token_id] if no_subsets and self.has_subsets(__lowerCamelCase , __lowerCamelCase ): raise ValueError( '''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is''' f""" {nested_token_ids}.""" ) _snake_case = root def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : Dict ): """simple docstring""" _snake_case = self.trie for current_token in current_seq: _snake_case = start[current_token] _snake_case = list(start.keys() ) return next_tokens def __UpperCAmelCase ( self : List[str] , __lowerCamelCase : Optional[Any] ): """simple docstring""" _snake_case = self.next_tokens(__lowerCamelCase ) return len(__lowerCamelCase ) == 0 def __UpperCAmelCase ( self : Union[str, Any] , __lowerCamelCase : int ): """simple docstring""" _snake_case = list(root.values() ) if len(__lowerCamelCase ) == 0: return 1 else: return sum([self.count_leaves(__lowerCamelCase ) for nn in next_nodes] ) def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : str ): """simple docstring""" _snake_case = self.count_leaves(__lowerCamelCase ) return len(__lowerCamelCase ) != leaf_count class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): def __init__( self : int , __lowerCamelCase : List[List[int]] ): """simple docstring""" super(__lowerCamelCase , self ).__init__() if not isinstance(__lowerCamelCase , __lowerCamelCase ) or len(__lowerCamelCase ) == 0: raise ValueError(f"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(__lowerCamelCase , __lowerCamelCase ) for token_ids in nested_token_ids ): raise ValueError(f"""`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.""" ) if any( any((not isinstance(__lowerCamelCase , __lowerCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f"""Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.""" ) _snake_case = DisjunctiveTrie(__lowerCamelCase ) _snake_case = nested_token_ids _snake_case = self.trie.max_height _snake_case = [] _snake_case = False def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = self.trie.next_tokens(self.current_seq ) if len(__lowerCamelCase ) == 0: return None else: return token_list def __UpperCAmelCase ( self : Optional[Any] , __lowerCamelCase : int ): """simple docstring""" if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) _snake_case = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def __UpperCAmelCase ( self : List[Any] , __lowerCamelCase : int ): """simple docstring""" if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(f"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCamelCase )}""" ) _snake_case = False _snake_case = False _snake_case = False if self.does_advance(__lowerCamelCase ): self.current_seq.append(__lowerCamelCase ) _snake_case = True else: _snake_case = True self.reset() _snake_case = self.trie.reached_leaf(self.current_seq ) _snake_case = completed return stepped, completed, reset def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = False _snake_case = [] def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def __UpperCAmelCase ( self : Optional[int] , __lowerCamelCase : Optional[int]=False ): """simple docstring""" _snake_case = DisjunctiveConstraint(self.token_ids ) if stateful: _snake_case = self.seqlen _snake_case = self.current_seq _snake_case = self.completed return new_constraint class UpperCAmelCase : def __init__( self : Optional[int] , __lowerCamelCase : List[Constraint] ): """simple docstring""" _snake_case = constraints # max # of steps required to fulfill a given constraint _snake_case = max([c.seqlen for c in constraints] ) _snake_case = len(__lowerCamelCase ) _snake_case = False self.init_state() def __UpperCAmelCase ( self : Optional[Any] ): """simple docstring""" _snake_case = [] _snake_case = None _snake_case = [constraint.copy(stateful=__lowerCamelCase ) for constraint in self.constraints] def __UpperCAmelCase ( self : Union[str, Any] ): """simple docstring""" _snake_case = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def __UpperCAmelCase ( self : int ): """simple docstring""" _snake_case = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" _snake_case = constraint.advance() if isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.extend(__lowerCamelCase ) else: _snake_case = self.inprogress_constraint.advance() if isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.append(__lowerCamelCase ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): token_list.extend(__lowerCamelCase ) if len(__lowerCamelCase ) == 0: return None else: return token_list def __UpperCAmelCase ( self : int , __lowerCamelCase : Optional[List[int]] ): """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint _snake_case , _snake_case = self.add(__lowerCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def __UpperCAmelCase ( self : Any , __lowerCamelCase : int ): """simple docstring""" if not isinstance(__lowerCamelCase , __lowerCamelCase ): raise ValueError(f"""`token_id` should be an `int`, but is `{token_id}`.""" ) _snake_case , _snake_case = False, False if self.completed: _snake_case = True _snake_case = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state _snake_case , _snake_case , _snake_case = self.inprogress_constraint.update(__lowerCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCamelCase ) ) _snake_case = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) _snake_case = None if len(self.pending_constraints ) == 0: # we're done! _snake_case = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(__lowerCamelCase ): _snake_case , _snake_case , _snake_case = pending_constraint.update(__lowerCamelCase ) if not stepped: raise Exception( '''`constraint.update(token_id)` is not yielding incremental progress, ''' '''even though `constraint.does_advance(token_id)` is true.''' ) if complete: self.complete_constraints.append(__lowerCamelCase ) _snake_case = None if not complete and stepped: _snake_case = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". _snake_case = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. _snake_case = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def __UpperCAmelCase ( self : Dict , __lowerCamelCase : Union[str, Any]=True ): """simple docstring""" _snake_case = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: _snake_case = [ constraint.copy(stateful=__lowerCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: _snake_case = self.inprogress_constraint.copy(stateful=__lowerCamelCase ) _snake_case = [constraint.copy() for constraint in self.pending_constraints] return new_state
103
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __A = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
59
0
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings UpperCamelCase = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__ ) class UpperCamelCase__ ( _lowerCAmelCase ): """simple docstring""" A__ : bool = field(default=_lowerCAmelCase , metadata={"help": "Whether to use SortishSampler or not."} ) A__ : bool = field( default=_lowerCAmelCase , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) A__ : Optional[int] = field( default=_lowerCAmelCase , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) A__ : Optional[int] = field( default=_lowerCAmelCase , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) A__ : Optional[Union[str, Path, GenerationConfig]] = field( default=_lowerCAmelCase , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def snake_case__ ( self ) -> List[Any]: A__ = super().to_dict() for k, v in d.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A__ = v.to_dict() return d
104
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __A = logging.get_logger(__name__) __A = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} __A = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } __A = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } __A = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = PRETRAINED_INIT_CONFIGURATION lowercase_ = ["input_ids", "attention_mask"] lowercase_ = DistilBertTokenizer def __init__(self : Tuple , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[Any]="[UNK]" , UpperCAmelCase_ : Dict="[SEP]" , UpperCAmelCase_ : Dict="[PAD]" , UpperCAmelCase_ : Optional[int]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : List[str]=None , **UpperCAmelCase_ : List[str] , ) ->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_ , ) lowerCamelCase__: Union[str, Any] =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 ): lowerCamelCase__: List[str] =getattr(UpperCAmelCase_ , normalizer_state.pop("type")) lowerCamelCase__: Optional[int] =do_lower_case lowerCamelCase__: int =strip_accents lowerCamelCase__: Any =tokenize_chinese_chars lowerCamelCase__: Any =normalizer_class(**UpperCAmelCase_) lowerCamelCase__: str =do_lower_case def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : Union[str, Any]=None) ->Dict: '''simple docstring''' lowerCamelCase__: str =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None) ->List[int]: '''simple docstring''' lowerCamelCase__: str =[self.sep_token_id] lowerCamelCase__: str =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None) ->Tuple[str]: '''simple docstring''' lowerCamelCase__: str =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_) return tuple(UpperCAmelCase_)
59
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 lowerCAmelCase_ ( lowerCamelCase_ ): def snake_case ( self ): SCREAMING_SNAKE_CASE_ : List[str] = SMALL_MODEL_IDENTIFIER SCREAMING_SNAKE_CASE_ : Optional[Any] = 'pt' SCREAMING_SNAKE_CASE_ : int = 'tf' def snake_case ( self ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(snake_case__ ) def snake_case ( self ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Optional[Any] = TFAutoModel.from_pretrained(self.test_model ,from_pt=snake_case__ ) model_tf.save_pretrained(snake_case__ ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Optional[Any] = 'mock_framework' # Framework provided - return whatever the user provides SCREAMING_SNAKE_CASE_ : List[str] = FeaturesManager.determine_framework(self.test_model ,snake_case__ ) self.assertEqual(snake_case__ ,snake_case__ ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = FeaturesManager.determine_framework(snake_case__ ,snake_case__ ) self.assertEqual(snake_case__ ,snake_case__ ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case__ ) SCREAMING_SNAKE_CASE_ : List[str] = FeaturesManager.determine_framework(snake_case__ ,snake_case__ ) self.assertEqual(snake_case__ ,snake_case__ ) def snake_case ( self ): # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case__ ) SCREAMING_SNAKE_CASE_ : List[Any] = FeaturesManager.determine_framework(snake_case__ ) self.assertEqual(snake_case__ ,self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case__ ) SCREAMING_SNAKE_CASE_ : Any = FeaturesManager.determine_framework(snake_case__ ) self.assertEqual(snake_case__ ,self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(snake_case__ ): SCREAMING_SNAKE_CASE_ : str = FeaturesManager.determine_framework(snake_case__ ) def snake_case ( self ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ ,self.framework_pt ) # PyTorch not in environment -> use TensorFlow SCREAMING_SNAKE_CASE_ : int = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_torch_available' ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Tuple = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ ,self.framework_tf ) # Both in environment -> use PyTorch SCREAMING_SNAKE_CASE_ : List[str] = MagicMock(return_value=snake_case__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' ,snake_case__ ), patch( 'transformers.onnx.features.is_torch_available' ,snake_case__ ): SCREAMING_SNAKE_CASE_ : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case__ ,self.framework_pt ) # Both not in environment -> raise error SCREAMING_SNAKE_CASE_ : int = MagicMock(return_value=snake_case__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = MagicMock(return_value=snake_case__ ) with patch('transformers.onnx.features.is_tf_available' ,snake_case__ ), patch( 'transformers.onnx.features.is_torch_available' ,snake_case__ ): with self.assertRaises(snake_case__ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = FeaturesManager.determine_framework(self.test_model )
105
import operator as op def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" lowerCamelCase__: Optional[Any] =[] lowerCamelCase__: Tuple =lambda __a , __a : int(x / y ) # noqa: E731 integer division operation lowerCamelCase__: Tuple ={ "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(12 ) , "Stack" , sep=" | " ) print("-" * (30 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) else: lowerCamelCase__: List[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) lowerCamelCase__: Optional[Any] =stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(12 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(12 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __A = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
59
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : List[str] , __UpperCamelCase : Any , __UpperCamelCase : List[Any]=7 , __UpperCamelCase : Dict=3 , __UpperCamelCase : str=30 , __UpperCamelCase : int=400 , __UpperCamelCase : Dict=True , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : int=True , __UpperCamelCase : Optional[Any]=1 / 255 , __UpperCamelCase : Dict=True , __UpperCamelCase : Any=[0.5, 0.5, 0.5] , __UpperCamelCase : Tuple=[0.5, 0.5, 0.5] , __UpperCamelCase : Tuple=True , ) -> List[Any]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1_333} A = parent A = batch_size A = num_channels A = min_resolution A = max_resolution A = do_resize A = size A = do_rescale A = rescale_factor A = do_normalize A = image_mean A = image_std A = do_pad def __UpperCamelCase ( self : List[str] ) -> str: return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __UpperCamelCase ( self : Any , __UpperCamelCase : Optional[int] , __UpperCamelCase : Dict=False ) -> Union[str, Any]: if not batched: A = image_inputs[0] if isinstance(__UpperCamelCase , Image.Image ): A , A = image.size else: A , A = image.shape[1], image.shape[2] if w < h: A = int(self.size['shortest_edge'] * h / w ) A = self.size['shortest_edge'] elif w > h: A = self.size['shortest_edge'] A = int(self.size['shortest_edge'] * w / h ) else: A = self.size['shortest_edge'] A = self.size['shortest_edge'] else: A = [] for image in image_inputs: A , A = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A = max(__UpperCamelCase , key=lambda __UpperCamelCase : item[0] )[0] A = max(__UpperCamelCase , key=lambda __UpperCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase__ ( _lowerCamelCase , unittest.TestCase ): A_ : int = DetrImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : int ) -> Any: A = DetrImageProcessingTester(self ) @property def __UpperCamelCase ( self : Optional[int] ) -> List[str]: return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : int ) -> Tuple: 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_rescale' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'rescale_factor' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'do_resize' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'size' ) ) self.assertTrue(hasattr(__UpperCamelCase , 'do_pad' ) ) def __UpperCamelCase ( self : Optional[int] ) -> Any: A = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1_333} ) self.assertEqual(image_processor.do_pad , __UpperCamelCase ) A = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__UpperCamelCase ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , __UpperCamelCase ) def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: pass def __UpperCamelCase ( self : List[Any] ) -> str: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCamelCase ) for image in image_inputs: self.assertIsInstance(__UpperCamelCase , Image.Image ) # Test not batched input A = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase , batched=__UpperCamelCase ) A = image_processing(__UpperCamelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase ( self : Tuple ) -> Optional[int]: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCamelCase , numpify=__UpperCamelCase ) for image in image_inputs: self.assertIsInstance(__UpperCamelCase , np.ndarray ) # Test not batched input A = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A = image_processing(__UpperCamelCase , return_tensors='pt' ).pixel_values A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase , batched=__UpperCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase ( self : List[Any] ) -> Optional[Any]: # Initialize image_processing A = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCamelCase , torchify=__UpperCamelCase ) for image in image_inputs: self.assertIsInstance(__UpperCamelCase , torch.Tensor ) # Test not batched input A = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A = image_processing(__UpperCamelCase , return_tensors='pt' ).pixel_values A , A = self.image_processor_tester.get_expected_values(__UpperCamelCase , batched=__UpperCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCamelCase ( self : List[str] ) -> Any: # prepare image and target A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A = json.loads(f.read() ) A = {'image_id': 39_769, 'annotations': target} # encode them A = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50' ) A = image_processing(images=__UpperCamelCase , annotations=__UpperCamelCase , return_tensors='pt' ) # verify pixel values A = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['pixel_values'].shape , __UpperCamelCase ) A = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __UpperCamelCase , atol=1e-4 ) ) # verify area A = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __UpperCamelCase ) ) # verify boxes A = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , __UpperCamelCase ) A = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __UpperCamelCase , atol=1e-3 ) ) # verify image_id A = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __UpperCamelCase ) ) # verify is_crowd A = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __UpperCamelCase ) ) # verify class_labels A = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __UpperCamelCase ) ) # verify orig_size A = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __UpperCamelCase ) ) # verify size A = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __UpperCamelCase ) ) @slow def __UpperCamelCase ( self : Optional[Any] ) -> Dict: # prepare image, target and masks_path A = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A = json.loads(f.read() ) A = {'file_name': '000000039769.png', 'image_id': 39_769, 'segments_info': target} A = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A = DetrImageProcessor.from_pretrained('facebook/detr-resnet-50-panoptic' ) A = image_processing(images=__UpperCamelCase , annotations=__UpperCamelCase , masks_path=__UpperCamelCase , return_tensors='pt' ) # verify pixel values A = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['pixel_values'].shape , __UpperCamelCase ) A = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __UpperCamelCase , atol=1e-4 ) ) # verify area A = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __UpperCamelCase ) ) # verify boxes A = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , __UpperCamelCase ) A = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __UpperCamelCase , atol=1e-3 ) ) # verify image_id A = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __UpperCamelCase ) ) # verify is_crowd A = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __UpperCamelCase ) ) # verify class_labels A = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __UpperCamelCase ) ) # verify masks A = 822_873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __UpperCamelCase ) # verify orig_size A = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __UpperCamelCase ) ) # verify size A = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __UpperCamelCase ) )
106
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : List[Any] , **UpperCAmelCase_ : Any) ->Any: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") requires_backends(self , "torch") if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""") self.check_model_type(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' lowerCamelCase__: Optional[int] ={} lowerCamelCase__: Tuple ={} lowerCamelCase__: str ={} # preprocess args if "points_per_batch" in kwargs: lowerCamelCase__: Optional[Any] =kwargs["points_per_batch"] if "points_per_crop" in kwargs: lowerCamelCase__: int =kwargs["points_per_crop"] if "crops_n_layers" in kwargs: lowerCamelCase__: Any =kwargs["crops_n_layers"] if "crop_overlap_ratio" in kwargs: lowerCamelCase__: Tuple =kwargs["crop_overlap_ratio"] if "crop_n_points_downscale_factor" in kwargs: lowerCamelCase__: List[Any] =kwargs["crop_n_points_downscale_factor"] # postprocess args if "pred_iou_thresh" in kwargs: lowerCamelCase__: List[str] =kwargs["pred_iou_thresh"] if "stability_score_offset" in kwargs: lowerCamelCase__: int =kwargs["stability_score_offset"] if "mask_threshold" in kwargs: lowerCamelCase__: Optional[int] =kwargs["mask_threshold"] if "stability_score_thresh" in kwargs: lowerCamelCase__: str =kwargs["stability_score_thresh"] if "crops_nms_thresh" in kwargs: lowerCamelCase__: Any =kwargs["crops_nms_thresh"] if "output_rle_mask" in kwargs: lowerCamelCase__: List[Any] =kwargs["output_rle_mask"] if "output_bboxes_mask" in kwargs: lowerCamelCase__: List[str] =kwargs["output_bboxes_mask"] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__(self : int , UpperCAmelCase_ : Dict , *UpperCAmelCase_ : Dict , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[Any]: '''simple docstring''' return super().__call__(UpperCAmelCase_ , *UpperCAmelCase_ , num_workers=UpperCAmelCase_ , batch_size=UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : float = 512 / 1_500 , UpperCAmelCase_ : Optional[int] = 32 , UpperCAmelCase_ : Optional[int] = 1 , ) ->Dict: '''simple docstring''' lowerCamelCase__: Dict =load_image(UpperCAmelCase_) lowerCamelCase__: List[str] =self.image_processor.size["longest_edge"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Union[str, Any] =self.image_processor.generate_crop_boxes( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: str =self.image_processor(images=UpperCAmelCase_ , return_tensors="pt") with self.device_placement(): if self.framework == "pt": lowerCamelCase__: str =self.get_inference_context() with inference_context(): lowerCamelCase__: Union[str, Any] =self._ensure_tensor_on_device(UpperCAmelCase_ , device=self.device) lowerCamelCase__: Optional[Any] =self.model.get_image_embeddings(model_inputs.pop("pixel_values")) lowerCamelCase__: str =image_embeddings lowerCamelCase__: int =grid_points.shape[1] lowerCamelCase__: int =points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. " "To return all points at once, set points_per_batch to None") for i in range(0 , UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: int =grid_points[:, i : i + points_per_batch, :, :] lowerCamelCase__: Optional[Any] =input_labels[:, i : i + points_per_batch] lowerCamelCase__: Dict =i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=0.88 , UpperCAmelCase_ : Optional[Any]=0.95 , UpperCAmelCase_ : Tuple=0 , UpperCAmelCase_ : Any=1 , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =model_inputs.pop("input_boxes") lowerCamelCase__: Dict =model_inputs.pop("is_last") lowerCamelCase__: int =model_inputs.pop("original_sizes").tolist() lowerCamelCase__: Union[str, Any] =model_inputs.pop("reshaped_input_sizes").tolist() lowerCamelCase__: Union[str, Any] =self.model(**UpperCAmelCase_) # post processing happens here in order to avoid CPU GPU copies of ALL the masks lowerCamelCase__: Optional[int] =model_outputs["pred_masks"] lowerCamelCase__: Union[str, Any] =self.image_processor.post_process_masks( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , binarize=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =model_outputs["iou_scores"] lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=False , UpperCAmelCase_ : Optional[int]=0.7 , ) ->Tuple: '''simple docstring''' lowerCamelCase__: Any =[] lowerCamelCase__: Optional[int] =[] lowerCamelCase__: List[str] =[] for model_output in model_outputs: all_scores.append(model_output.pop("iou_scores")) all_masks.extend(model_output.pop("masks")) all_boxes.append(model_output.pop("boxes")) lowerCamelCase__: str =torch.cat(UpperCAmelCase_) lowerCamelCase__: List[str] =torch.cat(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Dict =self.image_processor.post_process_for_mask_generation( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: List[str] =defaultdict(UpperCAmelCase_) for output in model_outputs: for k, v in output.items(): extra[k].append(UpperCAmelCase_) lowerCamelCase__: Any ={} if output_rle_mask: lowerCamelCase__: Union[str, Any] =rle_mask if output_bboxes_mask: lowerCamelCase__: int =bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
59
0
'''simple docstring''' import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class lowercase_ ( unittest.TestCase , _UpperCamelCase ): """simple docstring""" def __UpperCAmelCase ( self : List[str] ) -> Union[str, Any]: _A = load_tool('text-classification' ) self.tool.setup() _A = load_tool('text-classification', remote=UpperCamelCase__ ) def __UpperCAmelCase ( self : Any ) -> List[str]: _A = self.tool('That\'s quite cool', ['positive', 'negative'] ) self.assertEqual(UpperCamelCase__, 'positive' ) def __UpperCAmelCase ( self : Union[str, Any] ) -> str: _A = self.remote_tool('That\'s quite cool', ['positive', 'negative'] ) self.assertEqual(UpperCamelCase__, 'positive' ) def __UpperCAmelCase ( self : List[Any] ) -> str: _A = self.tool(text='That\'s quite cool', labels=['positive', 'negative'] ) self.assertEqual(UpperCamelCase__, 'positive' ) def __UpperCAmelCase ( self : Any ) -> List[str]: _A = self.remote_tool(text='That\'s quite cool', labels=['positive', 'negative'] ) self.assertEqual(UpperCamelCase__, 'positive' )
107
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = CustomTokenizer pass
59
0
__a: List[Any] = { '''Pillow''': '''Pillow''', '''accelerate''': '''accelerate>=0.11.0''', '''compel''': '''compel==0.1.8''', '''black''': '''black~=23.1''', '''datasets''': '''datasets''', '''filelock''': '''filelock''', '''flax''': '''flax>=0.4.1''', '''hf-doc-builder''': '''hf-doc-builder>=0.3.0''', '''huggingface-hub''': '''huggingface-hub>=0.13.2''', '''requests-mock''': '''requests-mock==1.10.0''', '''importlib_metadata''': '''importlib_metadata''', '''invisible-watermark''': '''invisible-watermark''', '''isort''': '''isort>=5.5.4''', '''jax''': '''jax>=0.2.8,!=0.3.2''', '''jaxlib''': '''jaxlib>=0.1.65''', '''Jinja2''': '''Jinja2''', '''k-diffusion''': '''k-diffusion>=0.0.12''', '''torchsde''': '''torchsde''', '''note_seq''': '''note_seq''', '''librosa''': '''librosa''', '''numpy''': '''numpy''', '''omegaconf''': '''omegaconf''', '''parameterized''': '''parameterized''', '''protobuf''': '''protobuf>=3.20.3,<4''', '''pytest''': '''pytest''', '''pytest-timeout''': '''pytest-timeout''', '''pytest-xdist''': '''pytest-xdist''', '''ruff''': '''ruff>=0.0.241''', '''safetensors''': '''safetensors''', '''sentencepiece''': '''sentencepiece>=0.1.91,!=0.1.92''', '''scipy''': '''scipy''', '''onnx''': '''onnx''', '''regex''': '''regex!=2019.12.17''', '''requests''': '''requests''', '''tensorboard''': '''tensorboard''', '''torch''': '''torch>=1.4''', '''torchvision''': '''torchvision''', '''transformers''': '''transformers>=4.25.1''', '''urllib3''': '''urllib3<=2.0.0''', }
108
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ (self : Dict) ->Optional[int]: '''simple docstring''' lowerCamelCase__: List[Any] =inspect.getfile(accelerate.test_utils) lowerCamelCase__: List[Any] =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_script.py"]) lowerCamelCase__: Any =os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ["scripts", "test_distributed_data_loop.py"]) lowerCamelCase__: Tuple =os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ["scripts", "test_ops.py"]) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->str: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Union[str, Any] =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : List[str]) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices.""") lowerCamelCase__: Dict =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(F"""Command: {cmd}""") with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : Dict) ->Tuple: '''simple docstring''' lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' print(F"""Found {torch.cuda.device_count()} devices, using 2 devices only""") lowerCamelCase__: int =["torchrun", F"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1"): execute_subprocess_async(UpperCAmelCase_ , env=os.environ.copy()) if __name__ == "__main__": __A = Accelerator() __A = (accelerator.state.process_index + 2, 10) __A = torch.randint(0, 10, shape).to(accelerator.device) __A = "" __A = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __A = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __A = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
0
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer a = ["gpt2"] a = "gpt2" if is_tf_available(): class __a ( tf.Module ): def __init__( self : str ,lowerCamelCase : List[Any] ): '''simple docstring''' super().__init__() __SCREAMING_SNAKE_CASE = tokenizer __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(lowerCamelCase ) __SCREAMING_SNAKE_CASE = TFGPTaLMHeadModel.from_config(lowerCamelCase ) @tf.function(input_signature=(tf.TensorSpec((None,) ,tf.string ,name="""text""" ),) ) def UpperCAmelCase__ ( self : int ,lowerCamelCase : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.tokenizer(lowerCamelCase ) __SCREAMING_SNAKE_CASE = tokenized["""input_ids"""].to_tensor() __SCREAMING_SNAKE_CASE = tf.cast(input_ids_dense > 0 ,tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __SCREAMING_SNAKE_CASE = self.model(input_ids=lowerCamelCase ,attention_mask=lowerCamelCase )["""logits"""] return outputs @require_tf @require_keras_nlp class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' super().setUp() __SCREAMING_SNAKE_CASE = [GPTaTokenizer.from_pretrained(lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __SCREAMING_SNAKE_CASE = [TFGPTaTokenizer.from_pretrained(lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __SCREAMING_SNAKE_CASE = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] __SCREAMING_SNAKE_CASE = list(zip(self.test_sentences ,self.test_sentences[::-1] ) ) def UpperCAmelCase__ ( self : int ): '''simple docstring''' for tokenizer, tf_tokenizer in zip(self.tokenizers ,self.tf_tokenizers ): for test_inputs in self.test_sentences: __SCREAMING_SNAKE_CASE = tokenizer([test_inputs] ,return_tensors="""tf""" ) __SCREAMING_SNAKE_CASE = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __SCREAMING_SNAKE_CASE = python_outputs[key].numpy() __SCREAMING_SNAKE_CASE = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(lowerCamelCase ,tf.intaa ) == tf_outputs_values ) ) @slow def UpperCAmelCase__ ( self : Dict ): '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __SCREAMING_SNAKE_CASE = tf.function(lowerCamelCase ) for test_inputs in self.test_sentences: __SCREAMING_SNAKE_CASE = tf.constant(lowerCamelCase ) __SCREAMING_SNAKE_CASE = compiled_tokenizer(lowerCamelCase ) __SCREAMING_SNAKE_CASE = tf_tokenizer(lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def UpperCAmelCase__ ( self : Tuple ): '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __SCREAMING_SNAKE_CASE = ModelToSave(tokenizer=lowerCamelCase ) __SCREAMING_SNAKE_CASE = tf.convert_to_tensor([self.test_sentences[0]] ) __SCREAMING_SNAKE_CASE = model.serving(lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __SCREAMING_SNAKE_CASE = Path(lowerCamelCase ) / """saved.model""" tf.saved_model.save(lowerCamelCase ,lowerCamelCase ,signatures={"""serving_default""": model.serving} ) __SCREAMING_SNAKE_CASE = tf.saved_model.load(lowerCamelCase ) __SCREAMING_SNAKE_CASE = loaded_model.signatures["""serving_default"""](lowerCamelCase )["""output_0"""] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def UpperCAmelCase__ ( self : Any ): '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: __SCREAMING_SNAKE_CASE = tf.convert_to_tensor([self.test_sentences[0]] ) __SCREAMING_SNAKE_CASE = tf_tokenizer(lowerCamelCase ) # Build model with some sample inputs __SCREAMING_SNAKE_CASE = tf_tokenizer.get_config() __SCREAMING_SNAKE_CASE = TFGPTaTokenizer.from_config(lowerCamelCase ) __SCREAMING_SNAKE_CASE = model_from_config(lowerCamelCase ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def UpperCAmelCase__ ( self : Union[str, Any] ): '''simple docstring''' for tf_tokenizer in self.tf_tokenizers: # for the test to run __SCREAMING_SNAKE_CASE = 12_3123 for max_length in [3, 5, 1024]: __SCREAMING_SNAKE_CASE = tf.convert_to_tensor([self.test_sentences[0]] ) __SCREAMING_SNAKE_CASE = tf_tokenizer(lowerCamelCase ,max_length=lowerCamelCase ) __SCREAMING_SNAKE_CASE = out["""input_ids"""].numpy().shape[1] assert out_length == max_length
109
from typing import List, Optional, Tuple, Union import PIL import torch from torchvision import transforms from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput from diffusers.schedulers import DDIMScheduler from diffusers.utils import randn_tensor __A = transforms.Compose( [ transforms.Resize((256, 256)), transforms.ToTensor(), transforms.Normalize([0.5], [0.5]), ] ) def lowerCAmelCase_ ( __a ) -> str: """simple docstring""" if isinstance(__a , torch.Tensor ): return image elif isinstance(__a , PIL.Image.Image ): lowerCamelCase__: Any =[image] lowerCamelCase__: Optional[Any] =[trans(img.convert("RGB" ) ) for img in image] lowerCamelCase__: Dict =torch.stack(__a ) return image class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple) ->int: '''simple docstring''' super().__init__() # make sure scheduler can always be converted to DDIM lowerCamelCase__: Tuple =DDIMScheduler.from_config(scheduler.config) self.register_modules(unet=UpperCAmelCase_ , scheduler=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Union[str, Any]) ->Dict: '''simple docstring''' if strength < 0 or strength > 1: raise ValueError(F"""The value of strength should in [0.0, 1.0] but is {strength}""") def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple) ->Tuple: '''simple docstring''' lowerCamelCase__: int =min(int(num_inference_steps * strength) , UpperCAmelCase_) lowerCamelCase__: str =max(num_inference_steps - init_timestep , 0) lowerCamelCase__: int =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[int]=None) ->Optional[int]: '''simple docstring''' if not isinstance(UpperCAmelCase_ , (torch.Tensor, PIL.Image.Image, list)): raise ValueError( F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(UpperCAmelCase_)}""") lowerCamelCase__: Optional[int] =image.to(device=UpperCAmelCase_ , dtype=UpperCAmelCase_) if isinstance(UpperCAmelCase_ , UpperCAmelCase_) and len(UpperCAmelCase_) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(UpperCAmelCase_)}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""") lowerCamelCase__: Dict =init_latents.shape lowerCamelCase__: int =randn_tensor(UpperCAmelCase_ , generator=UpperCAmelCase_ , device=UpperCAmelCase_ , dtype=UpperCAmelCase_) # get latents print("add noise to latents at timestep" , UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.scheduler.add_noise(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: int =init_latents return latents @torch.no_grad() def __call__(self : Tuple , UpperCAmelCase_ : Union[torch.FloatTensor, PIL.Image.Image] = None , UpperCAmelCase_ : float = 0.8 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase_ : float = 0.0 , UpperCAmelCase_ : int = 50 , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[str] = "pil" , UpperCAmelCase_ : bool = True , ) ->Union[ImagePipelineOutput, Tuple]: '''simple docstring''' self.check_inputs(UpperCAmelCase_) # 2. Preprocess image lowerCamelCase__: Dict =preprocess(UpperCAmelCase_) # 3. set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device) lowerCamelCase__ , lowerCamelCase__: str =self.get_timesteps(UpperCAmelCase_ , UpperCAmelCase_ , self.device) lowerCamelCase__: Optional[int] =timesteps[:1].repeat(UpperCAmelCase_) # 4. Prepare latent variables lowerCamelCase__: int =self.prepare_latents(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , self.unet.dtype , self.device , UpperCAmelCase_) lowerCamelCase__: Tuple =latents # 5. Denoising loop for t in self.progress_bar(UpperCAmelCase_): # 1. predict noise model_output lowerCamelCase__: Dict =self.unet(UpperCAmelCase_ , UpperCAmelCase_).sample # 2. predict previous mean of image x_t-1 and add variance depending on eta # eta corresponds to η in paper and should be between [0, 1] # do x_t -> x_t-1 lowerCamelCase__: Optional[int] =self.scheduler.step( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , eta=UpperCAmelCase_ , use_clipped_model_output=UpperCAmelCase_ , generator=UpperCAmelCase_ , ).prev_sample lowerCamelCase__: str =(image / 2 + 0.5).clamp(0 , 1) lowerCamelCase__: Optional[Any] =image.cpu().permute(0 , 2 , 3 , 1).numpy() if output_type == "pil": lowerCamelCase__: Dict =self.numpy_to_pil(UpperCAmelCase_) if not return_dict: return (image, latent_timestep.item()) return ImagePipelineOutput(images=UpperCAmelCase_)
59
0
"""simple docstring""" import argparse from copy import deepcopy import numpy as np from datasets import ClassLabel, DatasetDict, load_dataset from evaluate import load from transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainerCallback, TrainingArguments, set_seed, ) def lowerCamelCase ( ): UpperCAmelCase__ : List[Any] = argparse.ArgumentParser() parser.add_argument('--model_ckpt' ,type=_snake_case ,default='microsoft/unixcoder-base-nine' ) parser.add_argument('--num_epochs' ,type=_snake_case ,default=5 ) parser.add_argument('--batch_size' ,type=_snake_case ,default=6 ) parser.add_argument('--gradient_accumulation_steps' ,type=_snake_case ,default=1 ) parser.add_argument('--freeze' ,type=_snake_case ,default=_snake_case ) parser.add_argument('--learning_rate' ,type=_snake_case ,default=5e-4 ) parser.add_argument('--seed' ,type=_snake_case ,default=0 ) parser.add_argument('--lr_scheduler_type' ,type=_snake_case ,default='cosine' ) parser.add_argument('--num_warmup_steps' ,type=_snake_case ,default=10 ) parser.add_argument('--weight_decay' ,type=_snake_case ,default=0.01 ) parser.add_argument('--output_dir' ,type=_snake_case ,default='./results' ) return parser.parse_args() UpperCamelCase__ = load('accuracy') def lowerCamelCase ( _snake_case ): UpperCAmelCase__ , UpperCAmelCase__ : int = eval_pred UpperCAmelCase__ : Optional[int] = np.argmax(_snake_case ,axis=1 ) return metric.compute(predictions=_snake_case ,references=_snake_case ) class a ( lowercase ): def __init__( self , UpperCamelCase_ ): super().__init__() UpperCAmelCase__ : List[str] = trainer def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , **UpperCamelCase_ ): if control.should_evaluate: UpperCAmelCase__ : int = deepcopy(UpperCamelCase_ ) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix='train' ) return control_copy def lowerCamelCase ( ): UpperCAmelCase__ : int = get_args() set_seed(args.seed ) UpperCAmelCase__ : Optional[int] = load_dataset('codeparrot/codecomplex' ,split='train' ) UpperCAmelCase__ : Tuple = dataset.train_test_split(test_size=0.2 ) UpperCAmelCase__ : List[Any] = train_test['test'].train_test_split(test_size=0.5 ) UpperCAmelCase__ : Tuple = DatasetDict( { 'train': train_test['train'], 'test': test_validation['train'], 'valid': test_validation['test'], } ) print('Loading tokenizer and model' ) UpperCAmelCase__ : str = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCAmelCase__ : Optional[Any] = tokenizer.eos_token UpperCAmelCase__ : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt ,num_labels=7 ) UpperCAmelCase__ : Dict = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): UpperCAmelCase__ : Optional[int] = False UpperCAmelCase__ : Optional[Any] = ClassLabel(num_classes=7 ,names=list(set(train_test_validation['train']['complexity'] ) ) ) def tokenize(_snake_case ): UpperCAmelCase__ : Dict = tokenizer(example['src'] ,truncation=_snake_case ,max_length=1024 ) UpperCAmelCase__ : Any = labels.straint(example['complexity'] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } UpperCAmelCase__ : List[Any] = train_test_validation.map( _snake_case ,batched=_snake_case ,remove_columns=train_test_validation['train'].column_names ,) UpperCAmelCase__ : Tuple = DataCollatorWithPadding(tokenizer=_snake_case ) UpperCAmelCase__ : Union[str, Any] = TrainingArguments( output_dir=args.output_dir ,learning_rate=args.learning_rate ,lr_scheduler_type=args.lr_scheduler_type ,evaluation_strategy='epoch' ,save_strategy='epoch' ,logging_strategy='epoch' ,per_device_train_batch_size=args.batch_size ,per_device_eval_batch_size=args.batch_size ,num_train_epochs=args.num_epochs ,gradient_accumulation_steps=args.gradient_accumulation_steps ,weight_decay=0.01 ,metric_for_best_model='accuracy' ,run_name='complexity-java' ,report_to='wandb' ,) UpperCAmelCase__ : Dict = Trainer( model=_snake_case ,args=_snake_case ,train_dataset=tokenized_datasets['train'] ,eval_dataset=tokenized_datasets['valid'] ,tokenizer=_snake_case ,data_collator=_snake_case ,compute_metrics=_snake_case ,) print('Training...' ) trainer.add_callback(CustomCallback(_snake_case ) ) trainer.train() if __name__ == "__main__": main()
110
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCAmelCase_ ( __a , __a , __a , __a ) -> List[str]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(__a , "rb" ) as fp: lowerCamelCase__: Optional[Any] =pickle.load(__a , encoding="latin1" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) lowerCamelCase__: Union[str, Any] =pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["pretrained_vocab_file"] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) lowerCamelCase__: Any =corpus.vocab.__dict__ torch.save(__a , __a ) lowerCamelCase__: Dict =corpus.__dict__ corpus_dict_no_vocab.pop("vocab" , __a ) lowerCamelCase__: List[str] =pytorch_dump_folder_path + "/" + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(__a , __a ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model lowerCamelCase__: Optional[Any] =os.path.abspath(__a ) lowerCamelCase__: Dict =os.path.abspath(__a ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": lowerCamelCase__: int =TransfoXLConfig() else: lowerCamelCase__: Any =TransfoXLConfig.from_json_file(__a ) print(F"""Building PyTorch model from configuration: {config}""" ) lowerCamelCase__: List[Any] =TransfoXLLMHeadModel(__a ) lowerCamelCase__: List[str] =load_tf_weights_in_transfo_xl(__a , __a , __a ) # Save pytorch-model lowerCamelCase__: List[str] =os.path.join(__a , __a ) lowerCamelCase__: Tuple =os.path.join(__a , __a ) print(F"""Save PyTorch model to {os.path.abspath(__a )}""" ) torch.save(model.state_dict() , __a ) print(F"""Save configuration file to {os.path.abspath(__a )}""" ) with open(__a , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
0
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures A_ = logging.get_logger(__name__) @dataclass class snake_case : '''simple docstring''' UpperCAmelCase : Any = field(metadata={"""help""": """The name of the task to train on: """ + """, """.join(glue_processors.keys() )} ) UpperCAmelCase : Union[str, Any] = field( metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""} ) UpperCAmelCase : List[Any] = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) UpperCAmelCase : Optional[Any] = field( default=__SCREAMING_SNAKE_CASE , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def _lowercase ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ = self.task_name.lower() class snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase : str = """train""" UpperCAmelCase : List[Any] = """dev""" UpperCAmelCase : Tuple = """test""" class snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' UpperCAmelCase : str = 42 UpperCAmelCase : Tuple = 42 UpperCAmelCase : Tuple = 42 def __init__( self : Union[str, Any] , lowerCAmelCase_ : GlueDataTrainingArguments , lowerCAmelCase_ : PreTrainedTokenizerBase , lowerCAmelCase_ : Optional[int] = None , lowerCAmelCase_ : Union[str, Split] = Split.train , lowerCAmelCase_ : Optional[str] = None , ) -> List[str]: """simple docstring""" warnings.warn( '''This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' , UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE_ = args SCREAMING_SNAKE_CASE_ = glue_processors[args.task_name]() SCREAMING_SNAKE_CASE_ = glue_output_modes[args.task_name] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): try: SCREAMING_SNAKE_CASE_ = Split[mode] except KeyError: raise KeyError('''mode is not a valid split name''' ) # Load data features from cache or dataset file SCREAMING_SNAKE_CASE_ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' , ) SCREAMING_SNAKE_CASE_ = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE_ = label_list[2], label_list[1] SCREAMING_SNAKE_CASE_ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE_ = cached_features_file + ".lock" with FileLock(UpperCAmelCase_ ): if os.path.exists(UpperCAmelCase_ ) and not args.overwrite_cache: SCREAMING_SNAKE_CASE_ = time.time() SCREAMING_SNAKE_CASE_ = torch.load(UpperCAmelCase_ ) logger.info( F'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start ) else: logger.info(F'''Creating features from dataset file at {args.data_dir}''' ) if mode == Split.dev: SCREAMING_SNAKE_CASE_ = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: SCREAMING_SNAKE_CASE_ = self.processor.get_test_examples(args.data_dir ) else: SCREAMING_SNAKE_CASE_ = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: SCREAMING_SNAKE_CASE_ = examples[:limit_length] SCREAMING_SNAKE_CASE_ = glue_convert_examples_to_features( UpperCAmelCase_ , UpperCAmelCase_ , max_length=args.max_seq_length , label_list=UpperCAmelCase_ , output_mode=self.output_mode , ) SCREAMING_SNAKE_CASE_ = time.time() torch.save(self.features , UpperCAmelCase_ ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self : Dict ) -> Optional[Any]: """simple docstring""" return len(self.features ) def __getitem__( self : List[str] , lowerCAmelCase_ : str ) -> InputFeatures: """simple docstring""" return self.features[i] def _lowercase ( self : Optional[Any] ) -> List[str]: """simple docstring""" return self.label_list
393
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax __A = logging.get_logger(__name__) @add_end_docstrings(__SCREAMING_SNAKE_CASE ) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__(self : Optional[int] , **UpperCAmelCase_ : List[Any]) ->List[str]: '''simple docstring''' super().__init__(**UpperCAmelCase_) requires_backends(self , "vision") self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING) def __call__(self : List[str] , UpperCAmelCase_ : Union[str, List[str], "Image", List["Image"]] , **UpperCAmelCase_ : List[Any]) ->Tuple: '''simple docstring''' return super().__call__(UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , **UpperCAmelCase_ : Optional[int]) ->Any: '''simple docstring''' lowerCamelCase__: Optional[int] ={} if "candidate_labels" in kwargs: lowerCamelCase__: Tuple =kwargs["candidate_labels"] if "hypothesis_template" in kwargs: lowerCamelCase__: Tuple =kwargs["hypothesis_template"] return preprocess_params, {}, {} def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="This is a photo of {}.") ->str: '''simple docstring''' lowerCamelCase__: int =load_image(UpperCAmelCase_) lowerCamelCase__: Any =self.image_processor(images=[image] , return_tensors=self.framework) lowerCamelCase__: Any =candidate_labels lowerCamelCase__: List[str] =[hypothesis_template.format(UpperCAmelCase_) for x in candidate_labels] lowerCamelCase__: int =self.tokenizer(UpperCAmelCase_ , return_tensors=self.framework , padding=UpperCAmelCase_) lowerCamelCase__: str =[text_inputs] return inputs def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : Any) ->Tuple: '''simple docstring''' lowerCamelCase__: int =model_inputs.pop("candidate_labels") lowerCamelCase__: List[str] =model_inputs.pop("text_inputs") if isinstance(text_inputs[0] , UpperCAmelCase_): lowerCamelCase__: List[Any] =text_inputs[0] else: # Batching case. lowerCamelCase__: List[Any] =text_inputs[0][0] lowerCamelCase__: List[str] =self.model(**UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: str ={ "candidate_labels": candidate_labels, "logits": outputs.logits_per_image, } return model_outputs def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Union[str, Any]) ->int: '''simple docstring''' lowerCamelCase__: List[Any] =model_outputs.pop("candidate_labels") lowerCamelCase__: Optional[int] =model_outputs["logits"][0] if self.framework == "pt": lowerCamelCase__: Optional[Any] =logits.softmax(dim=-1).squeeze(-1) lowerCamelCase__: Optional[Any] =probs.tolist() if not isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Optional[int] =[scores] elif self.framework == "tf": lowerCamelCase__: List[str] =stable_softmax(UpperCAmelCase_ , axis=-1) lowerCamelCase__: Optional[int] =probs.numpy().tolist() else: raise ValueError(F"""Unsupported framework: {self.framework}""") lowerCamelCase__: Optional[int] =[ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase_ , UpperCAmelCase_) , key=lambda UpperCAmelCase_: -x[0]) ] return result
59
0
'''simple docstring''' import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def lowercase_ ( __A : Optional[Any] , __A : Optional[int] , __A : str ) -> List[Any]: """simple docstring""" lowercase : Any =TaConfig.from_json_file(__a ) print(F'Building PyTorch model from configuration: {config}' ) lowercase : Union[str, Any] =TaForConditionalGeneration(__a ) # Load weights from tf checkpoint load_tf_weights_in_ta(__a , __a , __a ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(__a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
94
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = 42 lowercase_ = jnp.floataa lowercase_ = True def SCREAMING_SNAKE_CASE_ (self : Any) ->List[str]: '''simple docstring''' super().setup() lowerCamelCase__: int =nn.Dense(5 , dtype=self.dtype) def __call__(self : Dict , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Any) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =super().__call__(*UpperCAmelCase_ , **UpperCAmelCase_) lowerCamelCase__: int =self.cls(outputs[2]) return outputs[:2] + (cls_out,) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = FlaxBigBirdForNaturalQuestionsModule def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" def cross_entropy(__a , __a , __a=None ): lowerCamelCase__: Tuple =logits.shape[-1] lowerCamelCase__: Tuple =(labels[..., None] == jnp.arange(__a )[None]).astype("f4" ) lowerCamelCase__: str =jax.nn.log_softmax(__a , axis=-1 ) lowerCamelCase__: Optional[Any] =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowerCamelCase__: Optional[Any] =reduction(__a ) return loss lowerCamelCase__: str =partial(__a , reduction=jnp.mean ) lowerCamelCase__: str =cross_entropy(__a , __a ) lowerCamelCase__: Optional[int] =cross_entropy(__a , __a ) lowerCamelCase__: Optional[Any] =cross_entropy(__a , __a ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = "google/bigbird-roberta-base" lowercase_ = 3000 lowercase_ = 1_0500 lowercase_ = 128 lowercase_ = 3 lowercase_ = 1 lowercase_ = 5 # tx_args lowercase_ = 3E-5 lowercase_ = 0.0 lowercase_ = 2_0000 lowercase_ = 0.0095 lowercase_ = "bigbird-roberta-natural-questions" lowercase_ = "training-expt" lowercase_ = "data/nq-training.jsonl" lowercase_ = "data/nq-validation.jsonl" def SCREAMING_SNAKE_CASE_ (self : Tuple) ->List[str]: '''simple docstring''' os.makedirs(self.base_dir , exist_ok=UpperCAmelCase_) lowerCamelCase__: Optional[Any] =os.path.join(self.base_dir , self.save_dir) lowerCamelCase__: List[str] =self.batch_size_per_device * jax.device_count() @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 4096 # no dynamic padding on TPUs def __call__(self : List[Any] , UpperCAmelCase_ : Optional[Any]) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Optional[Any] =self.collate_fn(UpperCAmelCase_) lowerCamelCase__: List[Any] =jax.tree_util.tree_map(UpperCAmelCase_ , UpperCAmelCase_) return batch def SCREAMING_SNAKE_CASE_ (self : int , UpperCAmelCase_ : List[str]) ->List[Any]: '''simple docstring''' lowerCamelCase__ , lowerCamelCase__: List[Any] =self.fetch_inputs(features["input_ids"]) lowerCamelCase__: Union[str, Any] ={ "input_ids": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "attention_mask": jnp.array(UpperCAmelCase_ , dtype=jnp.intaa), "start_labels": jnp.array(features["start_token"] , dtype=jnp.intaa), "end_labels": jnp.array(features["end_token"] , dtype=jnp.intaa), "pooled_labels": jnp.array(features["category"] , dtype=jnp.intaa), } return batch def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : list) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =[self._fetch_inputs(UpperCAmelCase_) for ids in input_ids] return zip(*UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : list) ->Any: '''simple docstring''' lowerCamelCase__: Optional[Any] =[1 for _ in range(len(UpperCAmelCase_))] while len(UpperCAmelCase_) < self.max_length: input_ids.append(self.pad_id) attention_mask.append(0) return input_ids, attention_mask def lowerCAmelCase_ ( __a , __a , __a=None ) -> str: """simple docstring""" if seed is not None: lowerCamelCase__: Any =dataset.shuffle(seed=__a ) for i in range(len(__a ) // batch_size ): lowerCamelCase__: Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(__a ) @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , __a , **__a ) -> List[str]: """simple docstring""" def loss_fn(__a ): lowerCamelCase__: Optional[int] =model_inputs.pop("start_labels" ) lowerCamelCase__: int =model_inputs.pop("end_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[int] =state.apply_fn(**__a , params=__a , dropout_rng=__a , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[Any] =outputs return state.loss_fn( __a , __a , __a , __a , __a , __a , ) lowerCamelCase__ , lowerCamelCase__: int =jax.random.split(__a ) lowerCamelCase__: Optional[Any] =jax.value_and_grad(__a ) lowerCamelCase__ , lowerCamelCase__: List[str] =grad_fn(state.params ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) lowerCamelCase__: List[str] =jax.lax.pmean(__a , "batch" ) lowerCamelCase__: List[str] =state.apply_gradients(grads=__a ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="batch" ) def lowerCAmelCase_ ( __a , **__a ) -> List[Any]: """simple docstring""" lowerCamelCase__: int =model_inputs.pop("start_labels" ) lowerCamelCase__: List[str] =model_inputs.pop("end_labels" ) lowerCamelCase__: int =model_inputs.pop("pooled_labels" ) lowerCamelCase__: Optional[Any] =state.apply_fn(**__a , params=state.params , train=__a ) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: List[str] =outputs lowerCamelCase__: Optional[int] =state.loss_fn(__a , __a , __a , __a , __a , __a ) lowerCamelCase__: Optional[Any] =jax.lax.pmean({"loss": loss} , axis_name="batch" ) return metrics class _SCREAMING_SNAKE_CASE ( train_state.TrainState ): '''simple docstring''' lowercase_ = struct.field(pytree_node=__SCREAMING_SNAKE_CASE ) @dataclass class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = None def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int=None) ->Optional[int]: '''simple docstring''' lowerCamelCase__: Dict =model.params lowerCamelCase__: Tuple =TrainState.create( apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , loss_fn=UpperCAmelCase_ , ) if ckpt_dir is not None: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Any =restore_checkpoint(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Tuple ={ "lr": args.lr, "init_lr": args.init_lr, "warmup_steps": args.warmup_steps, "num_train_steps": num_train_steps, "weight_decay": args.weight_decay, } lowerCamelCase__ , lowerCamelCase__: List[Any] =build_tx(**UpperCAmelCase_) lowerCamelCase__: str =train_state.TrainState( step=UpperCAmelCase_ , apply_fn=model.__call__ , params=UpperCAmelCase_ , tx=UpperCAmelCase_ , opt_state=UpperCAmelCase_ , ) lowerCamelCase__: Tuple =args lowerCamelCase__: Tuple =data_collator lowerCamelCase__: str =lr lowerCamelCase__: Dict =params lowerCamelCase__: List[str] =jax_utils.replicate(UpperCAmelCase_) return state def SCREAMING_SNAKE_CASE_ (self : List[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Tuple) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Tuple =self.args lowerCamelCase__: Any =len(UpperCAmelCase_) // args.batch_size lowerCamelCase__: List[str] =jax.random.PRNGKey(0) lowerCamelCase__: Optional[Any] =jax.random.split(UpperCAmelCase_ , jax.device_count()) for epoch in range(args.max_epochs): lowerCamelCase__: Union[str, Any] =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: str =get_batched_dataset(UpperCAmelCase_ , args.batch_size , seed=UpperCAmelCase_) lowerCamelCase__: Dict =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc=F"""Running EPOCH-{epoch}"""): lowerCamelCase__: List[str] =self.data_collator(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__: Optional[int] =self.train_step_fn(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 if i % args.logging_steps == 0: lowerCamelCase__: Optional[int] =jax_utils.unreplicate(state.step) lowerCamelCase__: List[Any] =running_loss.item() / i lowerCamelCase__: Tuple =self.scheduler_fn(state_step - 1) lowerCamelCase__: Union[str, Any] =self.evaluate(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Dict ={ "step": state_step.item(), "eval_loss": eval_loss.item(), "tr_loss": tr_loss, "lr": lr.item(), } tqdm.write(str(UpperCAmelCase_)) self.logger.log(UpperCAmelCase_ , commit=UpperCAmelCase_) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + F"""-e{epoch}-s{i}""" , state=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str) ->Any: '''simple docstring''' lowerCamelCase__: List[Any] =get_batched_dataset(UpperCAmelCase_ , self.args.batch_size) lowerCamelCase__: List[str] =len(UpperCAmelCase_) // self.args.batch_size lowerCamelCase__: str =jnp.array(0 , dtype=jnp.floataa) lowerCamelCase__: Optional[Any] =0 for batch in tqdm(UpperCAmelCase_ , total=UpperCAmelCase_ , desc="Evaluating ... "): lowerCamelCase__: int =self.data_collator(UpperCAmelCase_) lowerCamelCase__: str =self.val_step_fn(UpperCAmelCase_ , **UpperCAmelCase_) running_loss += jax_utils.unreplicate(metrics["loss"]) i += 1 return running_loss / i def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[int]) ->int: '''simple docstring''' lowerCamelCase__: Any =jax_utils.unreplicate(UpperCAmelCase_) print(F"""SAVING CHECKPOINT IN {save_dir}""" , end=" ... ") self.model_save_fn(UpperCAmelCase_ , params=state.params) with open(os.path.join(UpperCAmelCase_ , "opt_state.msgpack") , "wb") as f: f.write(to_bytes(state.opt_state)) joblib.dump(self.args , os.path.join(UpperCAmelCase_ , "args.joblib")) joblib.dump(self.data_collator , os.path.join(UpperCAmelCase_ , "data_collator.joblib")) with open(os.path.join(UpperCAmelCase_ , "training_state.json") , "w") as f: json.dump({"step": state.step.item()} , UpperCAmelCase_) print("DONE") def lowerCAmelCase_ ( __a , __a ) -> str: """simple docstring""" print(F"""RESTORING CHECKPOINT FROM {save_dir}""" , end=" ... " ) with open(os.path.join(__a , "flax_model.msgpack" ) , "rb" ) as f: lowerCamelCase__: Tuple =from_bytes(state.params , f.read() ) with open(os.path.join(__a , "opt_state.msgpack" ) , "rb" ) as f: lowerCamelCase__: Optional[int] =from_bytes(state.opt_state , f.read() ) lowerCamelCase__: Any =joblib.load(os.path.join(__a , "args.joblib" ) ) lowerCamelCase__: Union[str, Any] =joblib.load(os.path.join(__a , "data_collator.joblib" ) ) with open(os.path.join(__a , "training_state.json" ) , "r" ) as f: lowerCamelCase__: Optional[Any] =json.load(__a ) lowerCamelCase__: Any =training_state["step"] print("DONE" ) return params, opt_state, step, args, data_collator def lowerCAmelCase_ ( __a , __a , __a , __a ) -> Optional[int]: """simple docstring""" lowerCamelCase__: int =num_train_steps - warmup_steps lowerCamelCase__: str =optax.linear_schedule(init_value=__a , end_value=__a , transition_steps=__a ) lowerCamelCase__: Optional[Any] =optax.linear_schedule(init_value=__a , end_value=1e-7 , transition_steps=__a ) lowerCamelCase__: List[Any] =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowerCAmelCase_ ( __a , __a , __a , __a , __a ) -> str: """simple docstring""" def weight_decay_mask(__a ): lowerCamelCase__: List[str] =traverse_util.flatten_dict(__a ) lowerCamelCase__: List[str] ={k: (v[-1] != "bias" and v[-2:] != ("LayerNorm", "scale")) for k, v in params.items()} return traverse_util.unflatten_dict(__a ) lowerCamelCase__: Optional[Any] =scheduler_fn(__a , __a , __a , __a ) lowerCamelCase__: Tuple =optax.adamw(learning_rate=__a , weight_decay=__a , mask=__a ) return tx, lr
59
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available A_ = { '''configuration_gpt_neo''': ['''GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoConfig''', '''GPTNeoOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoForCausalLM''', '''GPTNeoForQuestionAnswering''', '''GPTNeoForSequenceClassification''', '''GPTNeoForTokenClassification''', '''GPTNeoModel''', '''GPTNeoPreTrainedModel''', '''load_tf_weights_in_gpt_neo''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''FlaxGPTNeoForCausalLM''', '''FlaxGPTNeoModel''', '''FlaxGPTNeoPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
609
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = ["image_processor", "tokenizer"] lowercase_ = "ChineseCLIPImageProcessor" lowercase_ = ("BertTokenizer", "BertTokenizerFast") def __init__(self : Any , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Union[str, Any]=None , **UpperCAmelCase_ : str) ->Dict: '''simple docstring''' lowerCamelCase__: str =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_ , ) lowerCamelCase__: Tuple =kwargs.pop("feature_extractor") lowerCamelCase__: Optional[int] =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(UpperCAmelCase_ , UpperCAmelCase_) lowerCamelCase__: Optional[int] =self.image_processor def __call__(self : int , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , **UpperCAmelCase_ : Dict) ->Optional[int]: '''simple docstring''' if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none.") if text is not None: lowerCamelCase__: Dict =self.tokenizer(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if images is not None: lowerCamelCase__: List[str] =self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_) if text is not None and images is not None: lowerCamelCase__: Union[str, Any] =image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**UpperCAmelCase_) , tensor_type=UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : List[Any]) ->Dict: '''simple docstring''' return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_) @property def SCREAMING_SNAKE_CASE_ (self : int) ->List[str]: '''simple docstring''' lowerCamelCase__: str =self.tokenizer.model_input_names lowerCamelCase__: Union[str, Any] =self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def SCREAMING_SNAKE_CASE_ (self : Optional[int]) ->str: '''simple docstring''' warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , UpperCAmelCase_ , ) return self.image_processor_class
59
0
import operator as op def _snake_case ( lowerCAmelCase : Any ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = [] SCREAMING_SNAKE_CASE_ : Tuple = lambda lowerCAmelCase , lowerCAmelCase : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE_ : Tuple = { "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8 ) , "Action".center(1_2 ) , "Stack" , sep=" | " ) print("-" * (3_0 + len(__a )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(__a ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("push(" + x + ")").ljust(1_2 ) , ",".join(__a ) , sep=" | " ) else: SCREAMING_SNAKE_CASE_ : List[Any] = stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + b + ")").ljust(1_2 ) , ",".join(__a ) , sep=" | " ) SCREAMING_SNAKE_CASE_ : Optional[Any] = stack.pop() # pop stack # output in tabular format print("".rjust(8 ) , ("pop(" + a + ")").ljust(1_2 ) , ",".join(__a ) , sep=" | " ) stack.append( str(opr[x](int(__a ) , int(__a ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ("push(" + a + x + b + ")").ljust(1_2 ) , ",".join(__a ) , sep=" | " , ) return int(stack[0] ) if __name__ == "__main__": __lowerCamelCase : Optional[int] = input('''\n\nEnter a Postfix Equation (space separated) = ''').split(''' ''') print('''\n\tResult = ''', solve(Postfix))
216
from math import ceil, sqrt def lowerCAmelCase_ ( __a = 1000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: lowerCamelCase__: Optional[int] =max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: lowerCamelCase__: Tuple =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() = }')
59
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A = logging.get_logger(__name__) A = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class a__ ( __SCREAMING_SNAKE_CASE ): lowercase_ = "big_bird" def __init__( self : List[str] , UpperCamelCase_ : int=50358 , UpperCamelCase_ : List[str]=768 , UpperCamelCase_ : Optional[int]=12 , UpperCamelCase_ : Union[str, Any]=12 , UpperCamelCase_ : Optional[Any]=3072 , UpperCamelCase_ : Union[str, Any]="gelu_new" , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : List[Any]=0.1 , UpperCamelCase_ : Optional[Any]=4096 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : Optional[Any]=0.02 , UpperCamelCase_ : Tuple=1e-12 , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Dict=0 , UpperCamelCase_ : List[str]=1 , UpperCamelCase_ : Dict=2 , UpperCamelCase_ : Optional[Any]=66 , UpperCamelCase_ : Optional[Any]="block_sparse" , UpperCamelCase_ : Any=True , UpperCamelCase_ : List[str]=False , UpperCamelCase_ : Optional[Any]=64 , UpperCamelCase_ : List[Any]=3 , UpperCamelCase_ : int=None , **UpperCamelCase_ : Optional[Any] , ): """simple docstring""" super().__init__( pad_token_id=UpperCAmelCase_ , bos_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , sep_token_id=UpperCAmelCase_ , **UpperCAmelCase_ , ) __UpperCAmelCase : List[Any] = vocab_size __UpperCAmelCase : str = max_position_embeddings __UpperCAmelCase : Union[str, Any] = hidden_size __UpperCAmelCase : Optional[Any] = num_hidden_layers __UpperCAmelCase : Union[str, Any] = num_attention_heads __UpperCAmelCase : Optional[Any] = intermediate_size __UpperCAmelCase : Dict = hidden_act __UpperCAmelCase : List[str] = hidden_dropout_prob __UpperCAmelCase : Optional[int] = attention_probs_dropout_prob __UpperCAmelCase : List[Any] = initializer_range __UpperCAmelCase : Union[str, Any] = type_vocab_size __UpperCAmelCase : Any = layer_norm_eps __UpperCAmelCase : Tuple = use_cache __UpperCAmelCase : Optional[int] = rescale_embeddings __UpperCAmelCase : int = attention_type __UpperCAmelCase : List[str] = use_bias __UpperCAmelCase : int = block_size __UpperCAmelCase : Tuple = num_random_blocks __UpperCAmelCase : Union[str, Any] = classifier_dropout class a__ ( __SCREAMING_SNAKE_CASE ): @property def a_ ( self : Union[str, Any]): """simple docstring""" if self.task == "multiple-choice": __UpperCAmelCase : Optional[int] = {0: "batch", 1: "choice", 2: "sequence"} else: __UpperCAmelCase : str = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ])
77
def lowerCAmelCase_ ( __a = 50000000 ) -> int: """simple docstring""" lowerCamelCase__: Any =set() lowerCamelCase__: int =int((limit - 24) ** (1 / 2) ) lowerCamelCase__: Tuple =set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , __a ) ) ) for primea in primes: lowerCamelCase__: Optional[int] =primea * primea for primea in primes: lowerCamelCase__: List[str] =primea * primea * primea if square + cube >= limit - 16: break for primea in primes: lowerCamelCase__: int =primea * primea * primea * primea lowerCamelCase__: Optional[Any] =square + cube + tetr if total >= limit: break ret.add(__a ) return len(__a ) if __name__ == "__main__": print(f'{solution() = }')
59
0
"""simple docstring""" from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowercase__ = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE ): '''simple docstring''' @register_to_config def __init__( self , lowercase , lowercase = None , lowercase = None ): super().__init__() _lowerCamelCase : Any = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" _lowerCamelCase : int = torch.zeros(UpperCAmelCase_ , UpperCAmelCase_ ) else: _lowerCamelCase : Optional[int] = None _lowerCamelCase : Tuple = torch.nn.Parameter(UpperCAmelCase_ ) class lowerCAmelCase__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = 42 def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase , ): super().__init__() self.register_modules( vqvae=UpperCAmelCase_ , transformer=UpperCAmelCase_ , text_encoder=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ , scheduler=UpperCAmelCase_ , learned_classifier_free_sampling_embeddings=UpperCAmelCase_ , ) def A_ ( self , lowercase , lowercase , lowercase ): _lowerCamelCase : Optional[Any] = len(UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else 1 # get prompt text embeddings _lowerCamelCase : Optional[Any] = self.tokenizer( UpperCAmelCase_ , padding='max_length' , max_length=self.tokenizer.model_max_length , return_tensors='pt' , ) _lowerCamelCase : List[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: _lowerCamelCase : Union[str, Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( 'The following part of your input was truncated because CLIP can only handle sequences up to' F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) _lowerCamelCase : Tuple = text_input_ids[:, : self.tokenizer.model_max_length] _lowerCamelCase : Optional[int] = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 _lowerCamelCase : List[str] = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase_ ) # duplicate text embeddings for each generation per prompt _lowerCamelCase : Tuple = prompt_embeds.repeat_interleave(UpperCAmelCase_ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: _lowerCamelCase : Tuple = self.learned_classifier_free_sampling_embeddings.embeddings _lowerCamelCase : str = negative_prompt_embeds.unsqueeze(0 ).repeat(UpperCAmelCase_ , 1 , 1 ) else: _lowerCamelCase : Any = [""] * batch_size _lowerCamelCase : List[str] = text_input_ids.shape[-1] _lowerCamelCase : List[Any] = self.tokenizer( UpperCAmelCase_ , padding='max_length' , max_length=UpperCAmelCase_ , truncation=UpperCAmelCase_ , return_tensors='pt' , ) _lowerCamelCase : int = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings _lowerCamelCase : List[str] = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=UpperCAmelCase_ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method _lowerCamelCase : Any = negative_prompt_embeds.shape[1] _lowerCamelCase : Optional[Any] = negative_prompt_embeds.repeat(1 , UpperCAmelCase_ , 1 ) _lowerCamelCase : int = negative_prompt_embeds.view(batch_size * num_images_per_prompt , UpperCAmelCase_ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _lowerCamelCase : Tuple = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self , lowercase , lowercase = 100 , lowercase = 5.0 , lowercase = 1.0 , lowercase = 1 , lowercase = None , lowercase = None , lowercase = "pil" , lowercase = True , lowercase = None , lowercase = 1 , ): if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _lowerCamelCase : int = 1 elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): _lowerCamelCase : Union[str, Any] = len(UpperCAmelCase_ ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_ )}''' ) _lowerCamelCase : List[str] = batch_size * num_images_per_prompt _lowerCamelCase : Optional[int] = guidance_scale > 1.0 _lowerCamelCase : Tuple = self._encode_prompt(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(UpperCAmelCase_ )}.''' ) # get the initial completely masked latents unless the user supplied it _lowerCamelCase : Any = (batch_size, self.transformer.num_latent_pixels) if latents is None: _lowerCamelCase : List[Any] = self.transformer.num_vector_embeds - 1 _lowerCamelCase : Tuple = torch.full(UpperCAmelCase_ , UpperCAmelCase_ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( 'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,' F''' {self.transformer.num_vector_embeds - 1} (inclusive).''' ) _lowerCamelCase : int = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(UpperCAmelCase_ , device=self.device ) _lowerCamelCase : str = self.scheduler.timesteps.to(self.device ) _lowerCamelCase : Union[str, Any] = latents for i, t in enumerate(self.progress_bar(UpperCAmelCase_ ) ): # expand the sample if we are doing classifier free guidance _lowerCamelCase : Optional[Any] = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` _lowerCamelCase : Optional[int] = self.transformer(UpperCAmelCase_ , encoder_hidden_states=UpperCAmelCase_ , timestep=UpperCAmelCase_ ).sample if do_classifier_free_guidance: _lowerCamelCase : Any = model_output.chunk(2 ) _lowerCamelCase : Optional[Any] = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(UpperCAmelCase_ , dim=1 , keepdim=UpperCAmelCase_ ) _lowerCamelCase : Optional[int] = self.truncate(UpperCAmelCase_ , UpperCAmelCase_ ) # remove `log(0)`'s (`-inf`s) _lowerCamelCase : Optional[Any] = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 _lowerCamelCase : str = self.scheduler.step(UpperCAmelCase_ , timestep=UpperCAmelCase_ , sample=UpperCAmelCase_ , generator=UpperCAmelCase_ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) _lowerCamelCase : int = self.vqvae.config.vq_embed_dim _lowerCamelCase : Union[str, Any] = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) _lowerCamelCase : int = self.vqvae.quantize.get_codebook_entry(UpperCAmelCase_ , shape=UpperCAmelCase_ ) _lowerCamelCase : str = self.vqvae.decode(UpperCAmelCase_ , force_not_quantize=UpperCAmelCase_ ).sample _lowerCamelCase : Optional[int] = (image / 2 + 0.5).clamp(0 , 1 ) _lowerCamelCase : int = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _lowerCamelCase : List[Any] = self.numpy_to_pil(UpperCAmelCase_ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCAmelCase_ ) def A_ ( self , lowercase , lowercase ): _lowerCamelCase : Tuple = torch.sort(UpperCAmelCase_ , 1 , descending=UpperCAmelCase_ ) _lowerCamelCase : List[str] = torch.exp(UpperCAmelCase_ ) _lowerCamelCase : Union[str, Any] = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out _lowerCamelCase : Optional[int] = torch.full_like(keep_mask[:, 0:1, :] , UpperCAmelCase_ ) _lowerCamelCase : int = torch.cat((all_true, keep_mask) , dim=1 ) _lowerCamelCase : str = keep_mask[:, :-1, :] _lowerCamelCase : Dict = keep_mask.gather(1 , indices.argsort(1 ) ) _lowerCamelCase : List[Any] = log_p_x_0.clone() _lowerCamelCase : int = -torch.inf # -inf = log(0) return rv
630
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( __a , __a , __a = 10**-10 ) -> float: """simple docstring""" lowerCamelCase__: List[str] =a while True: lowerCamelCase__: Optional[Any] =Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}') # Find root of polynomial print(f'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}') # Find Square Root of 5 print(f'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}') # Exponential Roots print(f'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')
59
0
import math import sys def lowerCamelCase ( a_ ) -> int: if number != int(__a ): raise ValueError('the value of input must be a natural number' ) if number < 0: raise ValueError('the value of input must not be a negative number' ) if number == 0: return 1 lowerCAmelCase_ = [-1] * (number + 1) lowerCAmelCase_ = 0 for i in range(1 , number + 1 ): lowerCAmelCase_ = sys.maxsize lowerCAmelCase_ = int(math.sqrt(__a ) ) for j in range(1 , root + 1 ): lowerCAmelCase_ = 1 + answers[i - (j**2)] lowerCAmelCase_ = min(__a , __a ) lowerCAmelCase_ = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
318
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( __a ) -> float: """simple docstring""" return np.dot(__a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__(self : List[str] , *, UpperCAmelCase_ : float = np.inf , UpperCAmelCase_ : str = "linear" , UpperCAmelCase_ : float = 0.0 , ) ->None: '''simple docstring''' lowerCamelCase__: Dict =regularization lowerCamelCase__: Any =gamma if kernel == "linear": lowerCamelCase__: Dict =self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma") if not isinstance(self.gamma , (float, int)): raise ValueError("gamma must be float or int") if not self.gamma > 0: raise ValueError("gamma must be > 0") lowerCamelCase__: Tuple =self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowerCamelCase__: Optional[Any] =F"""Unknown kernel: {kernel}""" raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.dot(UpperCAmelCase_ , UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : List[str] , UpperCAmelCase_ : ndarray , UpperCAmelCase_ : ndarray) ->float: '''simple docstring''' return np.exp(-(self.gamma * norm_squared(vectora - vectora))) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : list[ndarray] , UpperCAmelCase_ : ndarray) ->None: '''simple docstring''' lowerCamelCase__: Optional[Any] =observations lowerCamelCase__: Optional[int] =classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowerCamelCase__) , ): List[str] =np.shape(UpperCAmelCase_) def to_minimize(UpperCAmelCase_ : ndarray) -> float: lowerCamelCase__: int =0 ((lowerCamelCase__) , ): Optional[Any] =np.shape(UpperCAmelCase_) for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j]) ) return 1 / 2 * s - sum(UpperCAmelCase_) lowerCamelCase__: List[Any] =LinearConstraint(UpperCAmelCase_ , 0 , 0) lowerCamelCase__: str =Bounds(0 , self.regularization) lowerCamelCase__: Union[str, Any] =minimize( UpperCAmelCase_ , np.ones(UpperCAmelCase_) , bounds=UpperCAmelCase_ , constraints=[ly_contraint]).x lowerCamelCase__: str =l_star # calculating mean offset of separation plane to points lowerCamelCase__: Tuple =0 for i in range(UpperCAmelCase_): for j in range(UpperCAmelCase_): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j]) lowerCamelCase__: int =s / n def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : ndarray) ->int: '''simple docstring''' lowerCamelCase__: Optional[Any] =sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , UpperCAmelCase_) for n in range(len(self.classes))) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
0
"""simple docstring""" import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class lowerCamelCase : def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=37 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ): UpperCamelCase : Optional[int] = parent UpperCamelCase : int = batch_size UpperCamelCase : List[Any] = seq_length UpperCamelCase : Optional[int] = is_training UpperCamelCase : List[str] = use_input_mask UpperCamelCase : int = use_token_type_ids UpperCamelCase : List[Any] = use_labels UpperCamelCase : Tuple = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : str = embedding_size UpperCamelCase : List[Any] = num_hidden_layers UpperCamelCase : Tuple = num_attention_heads UpperCamelCase : List[Any] = intermediate_size UpperCamelCase : Optional[int] = hidden_act UpperCamelCase : Optional[int] = hidden_dropout_prob UpperCamelCase : Dict = attention_probs_dropout_prob UpperCamelCase : List[str] = max_position_embeddings UpperCamelCase : List[str] = type_vocab_size UpperCamelCase : Optional[Any] = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Optional[Any] = num_labels UpperCamelCase : Optional[Any] = num_choices UpperCamelCase : Union[str, Any] = scope def a_ ( self ): UpperCamelCase : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : List[str] = None if self.use_token_type_ids: UpperCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase : List[str] = None UpperCamelCase : Any = None UpperCamelCase : str = None if self.use_labels: UpperCamelCase : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return MegatronBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Tuple = MegatronBertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Tuple = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) UpperCamelCase : List[str] = model(UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ ) UpperCamelCase : str = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = MegatronBertForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : str = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : int = MegatronBertForCausalLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : str = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = MegatronBertForNextSentencePrediction(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Optional[int] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[Any] = MegatronBertForPreTraining(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Optional[int] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , next_sentence_label=UpperCAmelCase_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = MegatronBertForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Tuple = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : List[str] = MegatronBertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Optional[Any] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = self.num_labels UpperCamelCase : Tuple = MegatronBertForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Optional[int] = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Dict = self.num_choices UpperCamelCase : int = MegatronBertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() UpperCamelCase : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : List[str] = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , token_type_ids=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Union[str, Any] = self.prepare_config_and_inputs() ( UpperCamelCase ) : str = config_and_inputs UpperCamelCase : Optional[int] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): lowercase : Union[str, Any] = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) lowercase : Union[str, Any] = ( { 'feature-extraction': MegatronBertModel, 'fill-mask': MegatronBertForMaskedLM, 'question-answering': MegatronBertForQuestionAnswering, 'text-classification': MegatronBertForSequenceClassification, 'text-generation': MegatronBertForCausalLM, 'token-classification': MegatronBertForTokenClassification, 'zero-shot': MegatronBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Union[str, Any] = True # test_resize_embeddings = False lowercase : Optional[int] = False def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): UpperCamelCase : Optional[int] = super()._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ , return_labels=UpperCAmelCase_ ) if return_labels: if model_class in get_values(UpperCAmelCase_ ): UpperCamelCase : List[Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase_ ) UpperCamelCase : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase_ ) return inputs_dict def a_ ( self ): UpperCamelCase : Dict = MegatronBertModelTester(self ) UpperCamelCase : int = ConfigTester(self , config_class=UpperCAmelCase_ , hidden_size=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*UpperCAmelCase_ ) def a_ ( self ): UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*UpperCAmelCase_ ) def A_ ( snake_case_ : Union[str, Any] ): '''simple docstring''' return torch.tensor( __a ,dtype=torch.long ,device=__a ,) __A : int = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class lowerCamelCase ( unittest.TestCase ): @slow @unittest.skip("""Model is not available.""" ) def a_ ( self ): UpperCamelCase : Optional[Any] = "nvidia/megatron-bert-uncased-345m" if "MYDIR" in os.environ: UpperCamelCase : Optional[int] = os.path.join(os.environ["""MYDIR"""] , UpperCAmelCase_ ) UpperCamelCase : Dict = MegatronBertModel.from_pretrained(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.half() UpperCamelCase : str = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): UpperCamelCase : Dict = model(UpperCAmelCase_ )[0] UpperCamelCase : Dict = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , UpperCAmelCase_ ) UpperCamelCase : Any = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): UpperCamelCase : Optional[Any] = output[0, ii, jj] UpperCamelCase : Optional[Any] = expected[3 * ii + jj] UpperCamelCase : Tuple = "ii={} jj={} a={} b={}".format(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) self.assertTrue(math.isclose(UpperCAmelCase_ , UpperCAmelCase_ , rel_tol=UpperCAmelCase_ , abs_tol=UpperCAmelCase_ ) , msg=UpperCAmelCase_ )
499
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy __A = logging.getLogger(__name__) def lowerCAmelCase_ ( __a , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = False , ) -> str: """simple docstring""" lowerCamelCase__: int =bnb_quantization_config.load_in_abit lowerCamelCase__: Any =bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) lowerCamelCase__: List[Any] =[] # custom device map if isinstance(__a , __a ) and len(device_map.keys() ) > 1: lowerCamelCase__: Optional[int] =[key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: lowerCamelCase__: Any =get_keys_to_not_convert(__a ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__a ) lowerCamelCase__: List[str] =bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__: int =bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__a ) # compatibility with peft lowerCamelCase__: List[str] =load_in_abit lowerCamelCase__: int =load_in_abit lowerCamelCase__: Tuple =get_parameter_device(__a ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) lowerCamelCase__: Tuple =replace_with_bnb_layers(__a , __a , modules_to_not_convert=__a ) # convert param to the right dtype lowerCamelCase__: Dict =bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: lowerCamelCase__: str =name.replace(".weight" , "" ).replace(".bias" , "" ) lowerCamelCase__: Optional[Any] =getattr(__a , __a , __a ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__a ): param.to(__a ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): lowerCamelCase__: str =replace_with_bnb_layers( __a , __a , modules_to_not_convert=__a ) lowerCamelCase__: Optional[Any] =get_quantized_model_device_map( __a , __a , __a , max_memory=__a , no_split_module_classes=__a , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): lowerCamelCase__: Any =True lowerCamelCase__: List[str] =any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __a , __a , __a , dtype=bnb_quantization_config.torch_dtype , offload_folder=__a , offload_state_dict=__a , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__a , device_map=__a , offload_dir=__a ) def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , __a=None ) -> str: """simple docstring""" if device_map is None: if torch.cuda.is_available(): lowerCamelCase__: str ={"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__a , __a ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) lowerCamelCase__: Optional[int] ={} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) lowerCamelCase__: Optional[Any] ={} lowerCamelCase__: str =special_dtypes lowerCamelCase__: List[str] =no_split_module_classes lowerCamelCase__: Dict =bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": lowerCamelCase__: Optional[Any] =get_balanced_memory( __a , low_zero=(device_map == "balanced_low_0") , max_memory=__a , **__a , ) lowerCamelCase__: Union[str, Any] =max_memory lowerCamelCase__: Dict =infer_auto_device_map(__a , **__a ) if isinstance(__a , __a ): # check if don't have any quantized module on the cpu lowerCamelCase__: Union[str, Any] =bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules lowerCamelCase__: List[Any] ={ key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __a , __a , __a=None , __a=None ) -> Optional[Any]: """simple docstring""" if modules_to_not_convert is None: lowerCamelCase__: List[Any] =[] lowerCamelCase__ , lowerCamelCase__: Any =_replace_with_bnb_layers( __a , __a , __a , __a ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __a , __a , __a=None , __a=None , ) -> List[Any]: """simple docstring""" lowerCamelCase__: Optional[int] =False for name, module in model.named_children(): if current_key_name is None: lowerCamelCase__: Optional[Any] =[] current_key_name.append(__a ) if isinstance(__a , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` lowerCamelCase__: List[str] =".".join(__a ) lowerCamelCase__: Optional[Any] =True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: lowerCamelCase__: int =False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: lowerCamelCase__: Optional[int] =bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__a , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: lowerCamelCase__: Dict =bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) lowerCamelCase__: Dict =module.weight.data if module.bias is not None: lowerCamelCase__: List[Any] =module.bias.data bnb_module.requires_grad_(__a ) setattr(__a , __a , __a ) lowerCamelCase__: int =True if len(list(module.children() ) ) > 0: lowerCamelCase__ , lowerCamelCase__: List[str] =_replace_with_bnb_layers( __a , __a , __a , __a ) lowerCamelCase__: Union[str, Any] =has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __a ) -> List[Any]: """simple docstring""" with init_empty_weights(): lowerCamelCase__: Any =deepcopy(__a ) # this has 0 cost since it is done inside `init_empty_weights` context manager` lowerCamelCase__: str =find_tied_parameters(__a ) # For compatibility with Accelerate < 0.18 if isinstance(__a , __a ): lowerCamelCase__: int =sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowerCamelCase__: str =sum(__a , [] ) lowerCamelCase__: str =len(__a ) > 0 # Check if it is a base model lowerCamelCase__: Optional[Any] =False if hasattr(__a , "base_model_prefix" ): lowerCamelCase__: Union[str, Any] =not hasattr(__a , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowerCamelCase__: Optional[int] =list(model.named_children() ) lowerCamelCase__: Optional[int] =[list_modules[-1][0]] # add last module together with tied weights lowerCamelCase__: Union[str, Any] =set(__a ) - set(__a ) lowerCamelCase__: List[str] =list(set(__a ) ) + list(__a ) # remove ".weight" from the keys lowerCamelCase__: List[Any] =[".weight", ".bias"] lowerCamelCase__: Tuple =[] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowerCamelCase__: Optional[Any] =name.replace(__a , "" ) filtered_module_names.append(__a ) return filtered_module_names def lowerCAmelCase_ ( __a ) -> Tuple: """simple docstring""" for m in model.modules(): if isinstance(__a , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" return next(parameter.parameters() ).device def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a ) -> Any: """simple docstring""" if fpaa_statistics is None: set_module_tensor_to_device(__a , __a , 0 , dtype=__a , value=__a ) lowerCamelCase__: Dict =param_name lowerCamelCase__: Tuple =model if "." in tensor_name: lowerCamelCase__: Any =tensor_name.split("." ) for split in splits[:-1]: lowerCamelCase__: Any =getattr(__a , __a ) if new_module is None: raise ValueError(F"""{module} has no attribute {split}.""" ) lowerCamelCase__: str =new_module lowerCamelCase__: int =splits[-1] # offload weights lowerCamelCase__: str =False offload_weight(module._parameters[tensor_name] , __a , __a , index=__a ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __a , index=__a , ) else: offload_weight(__a , __a , __a , index=__a ) offload_weight(__a , param_name.replace("weight" , "SCB" ) , __a , index=__a ) set_module_tensor_to_device(__a , __a , "meta" , dtype=__a , value=torch.empty(*param.size() ) )
59
0
"""simple docstring""" import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str = 3 ): if isinstance(__a , __a ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(__a ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) lowerCAmelCase = QuantumRegister(__a , 'qr' ) lowerCAmelCase = ClassicalRegister(__a , 'cr' ) lowerCAmelCase = QuantumCircuit(__a , __a ) lowerCAmelCase = number_of_qubits for i in range(__a ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(__a ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , __a , __a ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(__a , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(__a , __a ) # simulate with 10000 shots lowerCAmelCase = Aer.get_backend('qasm_simulator' ) lowerCAmelCase = execute(__a , __a , shots=1_0000 ) return job.result().get_counts(__a ) if __name__ == "__main__": print( f'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
4
from __future__ import annotations from math import pi def lowerCAmelCase_ ( __a , __a , __a ) -> dict[str, float]: """simple docstring""" if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if inductance < 0: raise ValueError("Inductance cannot be negative" ) if frequency < 0: raise ValueError("Frequency cannot be negative" ) if reactance < 0: raise ValueError("Inductive reactance cannot be negative" ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
59
0
def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = [1] lowerCamelCase_ = 0, 0, 0 lowerCamelCase_ = ugly_nums[ia] * 2 lowerCamelCase_ = ugly_nums[ia] * 3 lowerCamelCase_ = ugly_nums[ia] * 5 for _ in range(1 , __a ): lowerCamelCase_ = min(__a , __a , __a ) ugly_nums.append(__a ) if next_num == next_a: ia += 1 lowerCamelCase_ = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 lowerCamelCase_ = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 lowerCamelCase_ = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"""{ugly_numbers(2_0_0) = }""")
463
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCAmelCase_ ( __a , __a ) -> List[Any]: """simple docstring""" assert isinstance(__a , __a ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader(__a , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: int =tmp_path / "cache" lowerCamelCase__: Tuple ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Union[str, Any] =features.copy() if features else default_expected_features lowerCamelCase__: Optional[int] =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: int =ParquetDatasetReader(__a , features=__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: Any =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: Optional[Any] =ParquetDatasetReader(__a , cache_dir=__a , split=__a ).read() _check_parquet_dataset(__a , __a ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list] ) def lowerCAmelCase_ ( __a , __a , __a ) -> int: """simple docstring""" if issubclass(__a , __a ): lowerCamelCase__: List[Any] =parquet_path elif issubclass(__a , __a ): lowerCamelCase__: str =[parquet_path] lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_dataset(__a , __a ) def lowerCAmelCase_ ( __a , __a , __a=("train",) ) -> Dict: """simple docstring""" assert isinstance(__a , __a ) for split in splits: lowerCamelCase__: Tuple =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Any: """simple docstring""" lowerCamelCase__: List[Any] =tmp_path / "cache" lowerCamelCase__: Optional[Any] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): lowerCamelCase__: Tuple =ParquetDatasetReader( {"train": parquet_path} , cache_dir=__a , keep_in_memory=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCAmelCase_ ( __a , __a , __a ) -> Optional[Any]: """simple docstring""" lowerCamelCase__: Tuple =tmp_path / "cache" lowerCamelCase__: Optional[int] ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: List[Any] =features.copy() if features else default_expected_features lowerCamelCase__: int =( Features({feature: Value(__a ) for feature, dtype in features.items()} ) if features is not None else None ) lowerCamelCase__: Optional[Any] =ParquetDatasetReader({"train": parquet_path} , features=__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a ) @pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] ) def lowerCAmelCase_ ( __a , __a , __a ) -> Union[str, Any]: """simple docstring""" if split: lowerCamelCase__: Any ={split: parquet_path} else: lowerCamelCase__: int ="train" lowerCamelCase__: Any ={"train": parquet_path, "test": parquet_path} lowerCamelCase__: str =tmp_path / "cache" lowerCamelCase__: Any ={"col_1": "string", "col_2": "int64", "col_3": "float64"} lowerCamelCase__: int =ParquetDatasetReader(__a , cache_dir=__a ).read() _check_parquet_datasetdict(__a , __a , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" lowerCamelCase__: List[str] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: List[str] =pq.ParquetFile(tmp_path / "foo.parquet" ) lowerCamelCase__: List[str] =pf.read() assert dataset.data.table == output_table def lowerCAmelCase_ ( __a , __a ) -> List[str]: """simple docstring""" lowerCamelCase__: List[str] =str(shared_datadir / "test_image_rgb.jpg" ) lowerCamelCase__: Union[str, Any] ={"image": [image_path]} lowerCamelCase__: Optional[Any] =Features({"image": Image()} ) lowerCamelCase__: Optional[int] =Dataset.from_dict(__a , features=__a ) lowerCamelCase__: Optional[int] =ParquetDatasetWriter(__a , tmp_path / "foo.parquet" ) assert writer.write() > 0 lowerCamelCase__: Dict =Dataset.from_parquet(str(tmp_path / "foo.parquet" ) ) assert dataset.features == reloaded_dataset.features lowerCamelCase__: Optional[Any] =ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__a ).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32" )} ), None), (Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCAmelCase_ ( __a , __a ) -> Optional[Any]: """simple docstring""" assert get_writer_batch_size(__a ) == expected
59
0