code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py UpperCAmelCase_ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase_ = direct_transformers_import(PATH_TO_TRANSFORMERS) UpperCAmelCase_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` UpperCAmelCase_ = re.compile(r'\[(.+?)\]\((https://huggingface\.co/.+?)\)') UpperCAmelCase_ = { '''DecisionTransformerConfig''', '''EncoderDecoderConfig''', '''MusicgenConfig''', '''RagConfig''', '''SpeechEncoderDecoderConfig''', '''TimmBackboneConfig''', '''VisionEncoderDecoderConfig''', '''VisionTextDualEncoderConfig''', '''LlamaConfig''', } def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ = None # source code of `config_class` UpperCAmelCase__ = inspect.getsource(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = _re_checkpoint.findall(SCREAMING_SNAKE_CASE__ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith("""/""" ): UpperCAmelCase__ = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link UpperCAmelCase__ = F'''https://huggingface.co/{ckpt_name}''' if ckpt_link == ckpt_link_from_name: UpperCAmelCase__ = ckpt_name break return checkpoint def _UpperCamelCase ( ): '''simple docstring''' UpperCAmelCase__ = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue UpperCAmelCase__ = get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCAmelCase__ = '\n'.join(sorted(SCREAMING_SNAKE_CASE__ ) ) raise ValueError(F'''The following configurations don\'t contain any valid checkpoint:\n{message}''' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
346
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): # Initialise PyTorch model UpperCAmelCase__ = BigBirdConfig.from_json_file(lowerCamelCase ) print(f'''Building PyTorch model from configuration: {config}''' ) if is_trivia_qa: UpperCAmelCase__ = BigBirdForQuestionAnswering(lowerCamelCase ) else: UpperCAmelCase__ = BigBirdForPreTraining(lowerCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(lowerCamelCase , lowerCamelCase , is_trivia_qa=lowerCamelCase ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowerCamelCase ) if __name__ == "__main__": lowerCAmelCase__ : int = 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( '--big_bird_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_trivia_qa', action='store_true', help='Whether to convert a model with a trivia_qa head.' ) lowerCAmelCase__ : List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
98
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def __snake_case ( _lowerCAmelCase : int ) -> List[str]: # vision encoder if "img_encoder.pos_embed" in name: A_ : List[str] = name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: A_ : str = name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: A_ : Optional[int] = name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: A_ : Any = name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: A_ : List[str] = name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: A_ : Dict = name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: A_ : int = name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: A_ : List[Any] = name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: A_ : List[Any] = name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: A_ : List[str] = name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: A_ : int = name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: A_ : Optional[Any] = name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: A_ : Optional[int] = name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: A_ : List[str] = name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: A_ : Optional[Any] = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: A_ : Any = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: A_ : Dict = name.replace("c_fc" , "fc1" ) if "c_proj" in name: A_ : Dict = name.replace("c_proj" , "fc2" ) if "text_encoder" in name: A_ : Union[str, Any] = name.replace("text_encoder" , "text_model" ) if "ln_final" in name: A_ : Tuple = name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: A_ : Dict = name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: A_ : Optional[Any] = name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: A_ : List[str] = name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: A_ : List[Any] = name.replace("text_projector.linear_out" , "text_projection.3" ) return name def __snake_case ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] ) -> Tuple: for key in orig_state_dict.copy().keys(): A_ : int = orig_state_dict.pop(_lowerCAmelCase ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A_ : Tuple = key.split("." ) A_ : Union[str, Any] = int(key_split[2] ), int(key_split[4] ) A_ : List[Any] = config.vision_config.hidden_size if "weight" in key: A_ : Union[str, Any] = val[:dim, :] A_ : Any = val[dim : dim * 2, :] A_ : List[str] = val[-dim:, :] else: A_ : Optional[Any] = val[:dim] A_ : Dict = val[dim : dim * 2] A_ : Union[str, Any] = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A_ : int = key.split("." ) A_ : Optional[int] = int(key_split[3] ) A_ : int = config.text_config.hidden_size if "weight" in key: A_ : int = val[:dim, :] A_ : Tuple = val[ dim : dim * 2, : ] A_ : Optional[int] = val[-dim:, :] else: A_ : Union[str, Any] = val[:dim] A_ : Optional[int] = val[dim : dim * 2] A_ : Any = val[-dim:] else: A_ : Optional[int] = rename_key(_lowerCAmelCase ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): A_ : Optional[Any] = val.squeeze_() else: A_ : Optional[int] = val return orig_state_dict def __snake_case ( ) -> Dict: A_ : Optional[Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' A_ : Union[str, Any] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def __snake_case ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Tuple="groupvit-gcc-yfcc" , _lowerCAmelCase : str=False ) -> Optional[int]: A_ : Dict = GroupViTConfig() A_ : Any = GroupViTModel(_lowerCAmelCase ).eval() A_ : str = torch.load(_lowerCAmelCase , map_location="cpu" )['model'] A_ : str = convert_state_dict(_lowerCAmelCase , _lowerCAmelCase ) A_ : int = model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(_lowerCAmelCase ) == 0) # verify result A_ : Any = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) A_ : Union[str, Any] = prepare_img() A_ : str = processor(text=["a photo of a cat", "a photo of a dog"] , images=_lowerCAmelCase , padding=_lowerCAmelCase , return_tensors="pt" ) with torch.no_grad(): A_ : List[Any] = model(**_lowerCAmelCase ) if model_name == "groupvit-gcc-yfcc": A_ : str = torch.tensor([[13.35_23, 6.36_29]] ) elif model_name == "groupvit-gcc-redcaps": A_ : Dict = torch.tensor([[16.18_73, 8.62_30]] ) else: raise ValueError(f"Model name {model_name} not supported." ) assert torch.allclose(outputs.logits_per_image , _lowerCAmelCase , atol=1e-3 ) processor.save_pretrained(_lowerCAmelCase ) model.save_pretrained(_lowerCAmelCase ) print("Successfully saved processor and model to" , _lowerCAmelCase ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(_lowerCAmelCase , organization="nielsr" ) model.push_to_hub(_lowerCAmelCase , organization="nielsr" ) if __name__ == "__main__": _lowerCAmelCase : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to dump the processor and PyTorch model.''' ) parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to GroupViT checkpoint''') parser.add_argument( '''--model_name''', default='''groupvit-gccy-fcc''', type=str, help='''Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.''', ) _lowerCAmelCase : Tuple = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
300
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
0
'''simple docstring''' class a_ : '''simple docstring''' def __init__( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = val _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None def snake_case_( self , A ) -> str: if self.val: if val < self.val: if self.left is None: _SCREAMING_SNAKE_CASE = Node(_A ) else: self.left.insert(_A ) elif val > self.val: if self.right is None: _SCREAMING_SNAKE_CASE = Node(_A ) else: self.right.insert(_A ) else: _SCREAMING_SNAKE_CASE = val def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : int ) ->Dict: # Recursive traversal if root: inorder(root.left , __lowerCamelCase ) res.append(root.val ) inorder(root.right , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Any ) ->Dict: # Build BST if len(__lowerCamelCase ) == 0: return arr _SCREAMING_SNAKE_CASE = Node(arr[0] ) for i in range(1 , len(__lowerCamelCase ) ): root.insert(arr[i] ) # Traverse BST in order. _SCREAMING_SNAKE_CASE = [] inorder(__lowerCamelCase , __lowerCamelCase ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
58
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
0
from collections import deque class _UpperCamelCase : '''simple docstring''' def __init__( self : Any , a : List[str] , a : Union[str, Any] , a : Optional[int] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = process_name # process name SCREAMING_SNAKE_CASE : Union[str, Any] = arrival_time # arrival time of the process # completion time of finished process or last interrupted time SCREAMING_SNAKE_CASE : str = arrival_time SCREAMING_SNAKE_CASE : Tuple = burst_time # remaining burst time SCREAMING_SNAKE_CASE : int = 0 # total time of the process wait in ready queue SCREAMING_SNAKE_CASE : Tuple = 0 # time from arrival time to completion time class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Union[str, Any] , a : Optional[Any] , a : Union[str, Any] , a : Dict , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Any = number_of_queues # time slice of queues that round robin algorithm applied SCREAMING_SNAKE_CASE : Optional[int] = time_slices # unfinished process is in this ready_queue SCREAMING_SNAKE_CASE : Dict = queue # current time SCREAMING_SNAKE_CASE : Tuple = current_time # finished process is in this sequence queue SCREAMING_SNAKE_CASE : deque[Process] = deque() def __UpperCamelCase ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def __UpperCamelCase ( self : int , a : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [] for i in range(len(_A ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def __UpperCamelCase ( self : Union[str, Any] , a : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = [] for i in range(len(_A ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def __UpperCamelCase ( self : Tuple , a : List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [] for i in range(len(_A ) ): completion_times.append(queue[i].stop_time ) return completion_times def __UpperCamelCase ( self : Dict , a : Any ) -> int: """simple docstring""" return [q.burst_time for q in queue] def __UpperCamelCase ( self : Any , a : Dict ) -> Union[str, Any]: """simple docstring""" process.waiting_time += self.current_time - process.stop_time return process.waiting_time def __UpperCamelCase ( self : Dict , a : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : deque[Process] = deque() # sequence deque of finished process while len(_A ) != 0: SCREAMING_SNAKE_CASE : Optional[Any] = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(_A ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 SCREAMING_SNAKE_CASE : List[str] = 0 # set the process's turnaround time because it is finished SCREAMING_SNAKE_CASE : List[Any] = self.current_time - cp.arrival_time # set the completion time SCREAMING_SNAKE_CASE : Dict = self.current_time # add the process to queue that has finished queue finished.append(_A ) self.finish_queue.extend(_A ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def __UpperCamelCase ( self : Optional[int] , a : Union[str, Any] , a : int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : deque[Process] = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(_A ) ): SCREAMING_SNAKE_CASE : Any = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(_A ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time SCREAMING_SNAKE_CASE : str = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(_A ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished SCREAMING_SNAKE_CASE : Any = 0 # set the finish time SCREAMING_SNAKE_CASE : str = self.current_time # update the process' turnaround time because it is finished SCREAMING_SNAKE_CASE : Optional[int] = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(_A ) self.finish_queue.extend(_A ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" for i in range(self.number_of_queues - 1 ): SCREAMING_SNAKE_CASE : Optional[Any] = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest a_ = Process('P1', 0, 53) a_ = Process('P2', 0, 17) a_ = Process('P3', 0, 68) a_ = Process('P4', 0, 24) a_ = 3 a_ = [17, 25] a_ = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'queue': deque([Pa, Pa, Pa, Pa])}) a_ = Process('P1', 0, 53) a_ = Process('P2', 0, 17) a_ = Process('P3', 0, 68) a_ = Process('P4', 0, 24) a_ = 3 a_ = [17, 25] a_ = deque([Pa, Pa, Pa, Pa]) a_ = MLFQ(number_of_queues, time_slices, queue, 0) a_ = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F'''waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print completion times of processes(P1, P2, P3, P4) print( F'''completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print total turnaround times of processes(P1, P2, P3, P4) print( F'''turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}''' ) # print sequence of finished processes print( F'''sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}''' )
76
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( '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' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
0
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCAmelCase_ ( __A, __A, __A, __A, ) -> list[float]: '''simple docstring''' UpperCAmelCase__ = coefficient_matrix.shape UpperCAmelCase__ = constant_matrix.shape if rowsa != colsa: UpperCAmelCase__ = f"""Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}""" raise ValueError(__A ) if colsa != 1: UpperCAmelCase__ = f"""Constant matrix must be nx1 but received {rowsa}x{colsa}""" raise ValueError(__A ) if rowsa != rowsa: UpperCAmelCase__ = ( 'Coefficient and constant matrices dimensions must be nxn and nx1 but ' f"""received {rowsa}x{colsa} and {rowsa}x{colsa}""" ) raise ValueError(__A ) if len(__A ) != rowsa: UpperCAmelCase__ = ( 'Number of initial values must be equal to number of rows in coefficient ' f"""matrix but received {len(__A )} and {rowsa}""" ) raise ValueError(__A ) if iterations <= 0: raise ValueError("Iterations must be at least 1" ) UpperCAmelCase__ = np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) UpperCAmelCase__ = table.shape strictly_diagonally_dominant(__A ) # Iterates the whole matrix for given number of times for _ in range(__A ): UpperCAmelCase__ = [] for row in range(__A ): UpperCAmelCase__ = 0 for col in range(__A ): if col == row: UpperCAmelCase__ = table[row][col] elif col == cols - 1: UpperCAmelCase__ = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] UpperCAmelCase__ = (temp + val) / denom new_val.append(__A ) UpperCAmelCase__ = new_val return [float(__A ) for i in new_val] def lowerCAmelCase_ ( __A ) -> bool: '''simple docstring''' UpperCAmelCase__ = table.shape UpperCAmelCase__ = True for i in range(0, __A ): UpperCAmelCase__ = 0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError("Coefficient matrix is not strictly diagonally dominant" ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
65
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
0
"""simple docstring""" import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py lowercase__ = '''.''' if __name__ == "__main__": lowercase__ = os.path.join(REPO_PATH, 'utils/documentation_tests.txt') lowercase__ = [] lowercase__ = [] with open(doctest_file_path) as fp: for line in fp: lowercase__ = line.strip() lowercase__ = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: lowercase__ = '''\n'''.join(non_existent_paths) raise ValueError(f"`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}") if all_paths != sorted(all_paths): raise ValueError('Files in `utils/documentation_tests.txt` are not in alphabetical order.')
290
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 OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : 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 __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = 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(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.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 , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) 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 , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
0
def A ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: lowerCamelCase : Tuple = [0] * len(_SCREAMING_SNAKE_CASE ) lowerCamelCase : Tuple = [] lowerCamelCase : Dict = [1] * len(_SCREAMING_SNAKE_CASE ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(_SCREAMING_SNAKE_CASE ) ): if indegree[i] == 0: queue.append(_SCREAMING_SNAKE_CASE ) while queue: lowerCamelCase : int = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowerCamelCase : Tuple = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(_SCREAMING_SNAKE_CASE ) print(max(_SCREAMING_SNAKE_CASE ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE__ : str = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
48
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
0
import math def __UpperCAmelCase ( a_ , a_ = 0 , a_ = 0): snake_case_ = end or len(a_) for i in range(a_ , a_): snake_case_ = i snake_case_ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: snake_case_ = array[temp_index - 1] temp_index -= 1 snake_case_ = temp_index_value return array def __UpperCAmelCase ( a_ , a_ , a_): # Max Heap snake_case_ = index snake_case_ = 2 * index + 1 # Left Node snake_case_ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: snake_case_ = left_index if right_index < heap_size and array[largest] < array[right_index]: snake_case_ = right_index if largest != index: snake_case_ = array[largest], array[index] heapify(a_ , a_ , a_) def __UpperCAmelCase ( a_): snake_case_ = len(a_) for i in range(n // 2 , -1 , -1): heapify(a_ , a_ , a_) for i in range(n - 1 , 0 , -1): snake_case_ = array[0], array[i] heapify(a_ , 0 , a_) return array def __UpperCAmelCase ( a_ , a_ , a_ , a_): if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def __UpperCAmelCase ( a_ , a_ , a_ , a_): snake_case_ = low snake_case_ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i snake_case_ = array[j], array[i] i += 1 def __UpperCAmelCase ( a_): if len(a_) == 0: return array snake_case_ = 2 * math.ceil(math.loga(len(a_))) snake_case_ = 16 return intro_sort(a_ , 0 , len(a_) , a_ , a_) def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_): while end - start > size_threshold: if max_depth == 0: return heap_sort(a_) max_depth -= 1 snake_case_ = median_of_a(a_ , a_ , start + ((end - start) // 2) + 1 , end - 1) snake_case_ = partition(a_ , a_ , a_ , a_) intro_sort(a_ , a_ , a_ , a_ , a_) snake_case_ = p return insertion_sort(a_ , a_ , a_) if __name__ == "__main__": import doctest doctest.testmod() lowercase = input("Enter numbers separated by a comma : ").strip() lowercase = [float(item) for item in user_input.split(",")] print(sort(unsorted))
178
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
'''simple docstring''' def _UpperCAmelCase ( _lowerCamelCase : List[Any] , _lowerCamelCase : Any = 0 ) -> list: _lowerCAmelCase : int = length or len(_lowerCamelCase ) _lowerCAmelCase : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: _lowerCAmelCase : Optional[int] = list_data[i + 1], list_data[i] _lowerCAmelCase : Union[str, Any] = True return list_data if not swapped else bubble_sort(_lowerCamelCase , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
309
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
0
from .data_collator import ( DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeqaSeq, DataCollatorForSOP, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithPadding, DefaultDataCollator, default_data_collator, ) from .metrics import glue_compute_metrics, xnli_compute_metrics from .processors import ( DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor, SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels, squad_convert_examples_to_features, xnli_output_modes, xnli_processors, xnli_tasks_num_labels, )
205
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
'''simple docstring''' import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ = np.inf def set_batch_size(SCREAMING_SNAKE_CASE__ : Dict ) -> None: nonlocal batch_size if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = min(SCREAMING_SNAKE_CASE__ , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = min(SCREAMING_SNAKE_CASE__ , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and feature.dtype == "binary": UpperCAmelCase__ = min(SCREAMING_SNAKE_CASE__ , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return None if batch_size is np.inf else batch_size class lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' def __init__( self : Dict , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Optional[Any] = None , _UpperCAmelCase : Union[str, Any] = None , _UpperCAmelCase : List[str] = None , _UpperCAmelCase : Optional[int] = False , _UpperCAmelCase : List[Any] = False , _UpperCAmelCase : Optional[Any] = None , **_UpperCAmelCase : Optional[int] , ): """simple docstring""" super().__init__( _A , split=_A , features=_A , cache_dir=_A , keep_in_memory=_A , streaming=_A , num_proc=_A , **_A , ) UpperCAmelCase__ = path_or_paths if isinstance(_A , _A ) else {self.split: path_or_paths} UpperCAmelCase__ = _PACKAGED_DATASETS_MODULES['parquet'][1] UpperCAmelCase__ = Parquet( cache_dir=_A , data_files=_A , features=_A , hash=_A , **_A , ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if self.streaming: UpperCAmelCase__ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None self.builder.download_and_prepare( download_config=_A , download_mode=_A , verification_mode=_A , base_path=_A , num_proc=self.num_proc , ) UpperCAmelCase__ = self.builder.as_dataset( split=self.split , verification_mode=_A , in_memory=self.keep_in_memory ) return dataset class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Optional[int] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Dict , _UpperCAmelCase : Tuple = None , **_UpperCAmelCase : Dict , ): """simple docstring""" UpperCAmelCase__ = dataset UpperCAmelCase__ = path_or_buf UpperCAmelCase__ = batch_size or get_writer_batch_size(dataset.features ) UpperCAmelCase__ = parquet_writer_kwargs def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , """wb+""" ) as buffer: UpperCAmelCase__ = self._write(file_obj=_A , batch_size=_A , **self.parquet_writer_kwargs ) else: UpperCAmelCase__ = self._write(file_obj=self.path_or_buf , batch_size=_A , **self.parquet_writer_kwargs ) return written def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : Dict , **_UpperCAmelCase : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = 0 UpperCAmelCase__ = parquet_writer_kwargs.pop("""path_or_buf""" , _A ) UpperCAmelCase__ = self.dataset.features.arrow_schema UpperCAmelCase__ = pq.ParquetWriter(_A , schema=_A , **_A ) for offset in logging.tqdm( range(0 , len(self.dataset ) , _A ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating parquet from Arrow format""" , ): UpperCAmelCase__ = query_table( table=self.dataset._data , key=slice(_A , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(_A ) written += batch.nbytes writer.close() return written
346
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
"""simple docstring""" import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase__ : Optional[int] = { '''facebook/data2vec-base-960h''': '''https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json''', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class snake_case ( snake_case__ ): """simple docstring""" snake_case__ = '''data2vec-audio''' def __init__( self : int ,lowerCamelCase__ : Dict=32 ,lowerCamelCase__ : Dict=768 ,lowerCamelCase__ : Any=12 ,lowerCamelCase__ : List[Any]=12 ,lowerCamelCase__ : int=3_072 ,lowerCamelCase__ : Optional[int]="gelu" ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : Tuple=0.1 ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : Tuple=0.0 ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Tuple=0.0_2 ,lowerCamelCase__ : Union[str, Any]=1e-5 ,lowerCamelCase__ : Union[str, Any]="gelu" ,lowerCamelCase__ : Tuple=(512, 512, 512, 512, 512, 512, 512) ,lowerCamelCase__ : Optional[Any]=(5, 2, 2, 2, 2, 2, 2) ,lowerCamelCase__ : int=(10, 3, 3, 3, 3, 2, 2) ,lowerCamelCase__ : Dict=False ,lowerCamelCase__ : str=16 ,lowerCamelCase__ : Tuple=19 ,lowerCamelCase__ : str=5 ,lowerCamelCase__ : Dict=0.0_5 ,lowerCamelCase__ : Tuple=10 ,lowerCamelCase__ : Optional[Any]=2 ,lowerCamelCase__ : str=0.0 ,lowerCamelCase__ : str=10 ,lowerCamelCase__ : Optional[int]=0 ,lowerCamelCase__ : Tuple="sum" ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Dict=False ,lowerCamelCase__ : Any=256 ,lowerCamelCase__ : Optional[int]=(512, 512, 512, 512, 1_500) ,lowerCamelCase__ : str=(5, 3, 3, 1, 1) ,lowerCamelCase__ : Tuple=(1, 2, 3, 1, 1) ,lowerCamelCase__ : Dict=512 ,lowerCamelCase__ : Dict=0 ,lowerCamelCase__ : Optional[Any]=1 ,lowerCamelCase__ : Union[str, Any]=2 ,lowerCamelCase__ : int=False ,lowerCamelCase__ : int=3 ,lowerCamelCase__ : Dict=2 ,lowerCamelCase__ : Optional[Any]=3 ,lowerCamelCase__ : Tuple=None ,**lowerCamelCase__ : List[str] ,): super().__init__(**_A ,pad_token_id=_A ,bos_token_id=_A ,eos_token_id=_A ) UpperCAmelCase__ = hidden_size UpperCAmelCase__ = feat_extract_activation UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = conv_bias UpperCAmelCase__ = num_conv_pos_embeddings UpperCAmelCase__ = num_conv_pos_embedding_groups UpperCAmelCase__ = conv_pos_kernel_size UpperCAmelCase__ = len(self.conv_dim ) UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = hidden_dropout UpperCAmelCase__ = attention_dropout UpperCAmelCase__ = activation_dropout UpperCAmelCase__ = feat_proj_dropout UpperCAmelCase__ = final_dropout UpperCAmelCase__ = layerdrop UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = initializer_range UpperCAmelCase__ = vocab_size UpperCAmelCase__ = use_weighted_layer_sum 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 UpperCAmelCase__ = mask_time_prob UpperCAmelCase__ = mask_time_length UpperCAmelCase__ = mask_time_min_masks UpperCAmelCase__ = mask_feature_prob UpperCAmelCase__ = mask_feature_length UpperCAmelCase__ = mask_feature_min_masks # ctc loss UpperCAmelCase__ = ctc_loss_reduction UpperCAmelCase__ = ctc_zero_infinity # adapter UpperCAmelCase__ = add_adapter UpperCAmelCase__ = adapter_kernel_size UpperCAmelCase__ = adapter_stride UpperCAmelCase__ = num_adapter_layers UpperCAmelCase__ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCAmelCase__ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = list(_A ) UpperCAmelCase__ = xvector_output_dim @property def __lowerCAmelCase ( self : Optional[Any] ): return math.prod(self.conv_stride )
98
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def __snake_case ( _lowerCAmelCase : List[Any] ) -> Tuple: A_ : Dict = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: A_ : Optional[Any] = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: A_ : Optional[int] = 4 A_ : List[Any] = 48 A_ : Optional[Any] = 'pixelshuffle_aux' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: A_ : Any = [6, 6, 6, 6] A_ : List[Any] = 60 A_ : Union[str, Any] = [6, 6, 6, 6] A_ : str = 'pixelshuffledirect' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: A_ : List[str] = 4 A_ : Union[str, Any] = 'nearest+conv' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: A_ : Any = 1 A_ : List[str] = 1 A_ : Optional[Any] = 126 A_ : Dict = 7 A_ : int = 2_55.0 A_ : Dict = '' return config def __snake_case ( _lowerCAmelCase : Any , _lowerCAmelCase : Tuple ) -> Dict: if "patch_embed.proj" in name and "layers" not in name: A_ : Optional[int] = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: A_ : Any = name.replace("patch_embed.norm" , "embeddings.patch_embeddings.layernorm" ) if "layers" in name: A_ : Any = name.replace("layers" , "encoder.stages" ) if "residual_group.blocks" in name: A_ : Optional[int] = name.replace("residual_group.blocks" , "layers" ) if "attn.proj" in name: A_ : Tuple = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: A_ : Optional[int] = name.replace("attn" , "attention.self" ) if "norm1" in name: A_ : List[Any] = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: A_ : Optional[int] = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: A_ : Optional[int] = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: A_ : Optional[int] = name.replace("mlp.fc2" , "output.dense" ) if "q_bias" in name: A_ : Optional[int] = name.replace("q_bias" , "query.bias" ) if "k_bias" in name: A_ : List[Any] = name.replace("k_bias" , "key.bias" ) if "v_bias" in name: A_ : Any = name.replace("v_bias" , "value.bias" ) if "cpb_mlp" in name: A_ : List[str] = name.replace("cpb_mlp" , "continuous_position_bias_mlp" ) if "patch_embed.proj" in name: A_ : Union[str, Any] = name.replace("patch_embed.proj" , "patch_embed.projection" ) if name == "norm.weight": A_ : Optional[int] = 'layernorm.weight' if name == "norm.bias": A_ : Optional[Any] = 'layernorm.bias' if "conv_first" in name: A_ : int = name.replace("conv_first" , "first_convolution" ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: A_ : Union[str, Any] = name.replace("conv_last" , "final_convolution" ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: A_ : Any = name.replace("conv_before_upsample.0" , "conv_before_upsample" ) if "upsample.0" in name: A_ : Optional[int] = name.replace("upsample.0" , "upsample.convolution_0" ) if "upsample.2" in name: A_ : Any = name.replace("upsample.2" , "upsample.convolution_1" ) A_ : List[str] = 'upsample.' + name elif config.upsampler == "pixelshuffledirect": A_ : Optional[int] = name.replace("upsample.0.weight" , "upsample.conv.weight" ) A_ : List[Any] = name.replace("upsample.0.bias" , "upsample.conv.bias" ) else: pass else: A_ : Optional[Any] = 'swin2sr.' + name return name def __snake_case ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : str ) -> int: for key in orig_state_dict.copy().keys(): A_ : List[str] = orig_state_dict.pop(_lowerCAmelCase ) if "qkv" in key: A_ : List[Any] = key.split("." ) A_ : Optional[Any] = int(key_split[1] ) A_ : Union[str, Any] = int(key_split[4] ) A_ : Union[str, Any] = config.embed_dim if "weight" in key: A_ : List[str] = val[:dim, :] A_ : Tuple = val[dim : dim * 2, :] A_ : Optional[Any] = val[-dim:, :] else: A_ : Union[str, Any] = val[:dim] A_ : Optional[int] = val[dim : dim * 2] A_ : str = val[-dim:] pass else: A_ : List[str] = val return orig_state_dict def __snake_case ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Optional[Any] ) -> Any: A_ : Optional[int] = get_config(_lowerCAmelCase ) A_ : str = SwinaSRForImageSuperResolution(_lowerCAmelCase ) model.eval() A_ : Optional[Any] = torch.hub.load_state_dict_from_url(_lowerCAmelCase , map_location="cpu" ) A_ : Any = convert_state_dict(_lowerCAmelCase , _lowerCAmelCase ) A_ : List[Any] = model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: raise ValueError("Missing keys when converting: {}".format(_lowerCAmelCase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"Unexpected key {key} in state_dict" ) # verify values A_ : Union[str, Any] = 'https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true' A_ : Dict = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw ).convert("RGB" ) A_ : Tuple = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values A_ : Any = 126 if 'Jpeg' in checkpoint_url else 256 A_ : List[str] = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_85, 0.4_56, 0.4_06] , std=[0.2_29, 0.2_24, 0.2_25] ), ] ) A_ : Tuple = transforms(_lowerCAmelCase ).unsqueeze(0 ) if config.num_channels == 1: A_ : Union[str, Any] = pixel_values[:, 0, :, :].unsqueeze(1 ) A_ : str = model(_lowerCAmelCase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: A_ : List[Any] = torch.Size([1, 3, 512, 512] ) A_ : Optional[int] = torch.tensor( [[-0.70_87, -0.71_38, -0.67_21], [-0.83_40, -0.80_95, -0.72_98], [-0.91_49, -0.84_14, -0.79_40]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: A_ : List[str] = torch.Size([1, 3, 1024, 1024] ) A_ : Optional[int] = torch.tensor( [[-0.77_75, -0.81_05, -0.89_33], [-0.77_64, -0.83_56, -0.92_25], [-0.79_76, -0.86_86, -0.95_79]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here A_ : Union[str, Any] = torch.Size([1, 3, 1024, 1024] ) A_ : Optional[int] = torch.tensor( [[-0.80_35, -0.75_04, -0.74_91], [-0.85_38, -0.81_24, -0.77_82], [-0.88_04, -0.86_51, -0.84_93]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: A_ : Optional[Any] = torch.Size([1, 3, 512, 512] ) A_ : Dict = torch.tensor( [[-0.76_69, -0.86_62, -0.87_67], [-0.88_10, -0.99_62, -0.98_20], [-0.93_40, -1.03_22, -1.11_49]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: A_ : Optional[int] = torch.Size([1, 3, 1024, 1024] ) A_ : Any = torch.tensor( [[-0.52_38, -0.55_57, -0.63_21], [-0.60_16, -0.59_03, -0.63_91], [-0.62_44, -0.63_34, -0.68_89]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , _lowerCAmelCase , atol=1e-3 ) print("Looks ok!" ) A_ : Optional[Any] = { 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': ( 'swin2SR-classical-sr-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': ( 'swin2SR-classical-sr-x4-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': ( 'swin2SR-compressed-sr-x4-48' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': ( 'swin2SR-lightweight-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': ( 'swin2SR-realworld-sr-x4-64-bsrgan-psnr' ), } A_ : List[Any] = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_lowerCAmelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(_lowerCAmelCase ) if push_to_hub: model.push_to_hub(f"caidas/{model_name}" ) processor.push_to_hub(f"caidas/{model_name}" ) if __name__ == "__main__": _lowerCAmelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') _lowerCAmelCase : Optional[Any] = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
300
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase_ = { '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['''BloomTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '''BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BloomForCausalLM''', '''BloomModel''', '''BloomPreTrainedModel''', '''BloomForSequenceClassification''', '''BloomForTokenClassification''', '''BloomForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
0
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class _UpperCamelCase ( snake_case__ , snake_case__ ): '''simple docstring''' lowerCamelCase__ =1 @register_to_config def __init__( self : Optional[int] , a : Dict = 1000 , a : List[Any] = None ) -> Any: """simple docstring""" self.set_timesteps(_A ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : Optional[Any] = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : List[Any] = 4 # running values SCREAMING_SNAKE_CASE : Union[str, Any] = [] def __UpperCamelCase ( self : Optional[Any] , a : Tuple , a : int = None ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = num_inference_steps SCREAMING_SNAKE_CASE : str = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Optional[Any] = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : Any = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Any = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Union[str, Any] = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : Union[str, Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : Tuple = timesteps.to(_A ) SCREAMING_SNAKE_CASE : Optional[Any] = [] def __UpperCamelCase ( self : List[Any] , a : int , a : Optional[Any] , a : Optional[Any] , a : Any = True , ) -> str: """simple docstring""" if self.num_inference_steps is None: raise ValueError( "Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler" ) SCREAMING_SNAKE_CASE : List[Any] = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Tuple = timestep_index + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_A ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : Optional[Any] = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Optional[int] = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : Any = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Any = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : Tuple = self._get_prev_sample(_A , _A , _A , _A ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_A ) def __UpperCamelCase ( self : Optional[int] , a : Dict , *a : Union[str, Any] , **a : Tuple ) -> Optional[int]: """simple docstring""" return sample def __UpperCamelCase ( self : Union[str, Any] , a : List[str] , a : Union[str, Any] , a : Tuple , a : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : Dict = self.betas[timestep_index] SCREAMING_SNAKE_CASE : List[Any] = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : str = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : List[Any] = (sample - sigma * ets) / max(_A , 1e-8 ) SCREAMING_SNAKE_CASE : str = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : Any ) -> Tuple: """simple docstring""" return self.config.num_train_timesteps
76
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[Any] = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) UpperCAmelCase : int = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(F"""Following is minimal change for {value}: """) UpperCAmelCase : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
0
import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class A : def __init__(self : int , __UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" if isinstance(_A , _A ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden UpperCAmelCase__ = deepcopy(_A ) elif os.path.exists(_A ): with io.open(_A , "r" , encoding="utf-8" ) as f: UpperCAmelCase__ = json.load(_A ) else: try: UpperCAmelCase__ = baseaa.urlsafe_baadecode(_A ).decode("utf-8" ) UpperCAmelCase__ = json.loads(_A ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( f"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) UpperCAmelCase__ = config self.set_stage_and_offload() def lowercase_ (self : Tuple ) -> Dict: """simple docstring""" UpperCAmelCase__ = self.get_value("zero_optimization.stage" , -1 ) # offload UpperCAmelCase__ = False if self.is_zeroa() or self.is_zeroa(): UpperCAmelCase__ = set(["cpu", "nvme"] ) UpperCAmelCase__ = set( [ self.get_value("zero_optimization.offload_optimizer.device" ), self.get_value("zero_optimization.offload_param.device" ), ] ) if len(offload_devices & offload_devices_valid ) > 0: UpperCAmelCase__ = True def lowercase_ (self : Optional[Any] , __UpperCAmelCase : int ) -> int: """simple docstring""" UpperCAmelCase__ = self.config # find the config node of interest if it exists UpperCAmelCase__ = ds_key_long.split("." ) UpperCAmelCase__ = nodes.pop() for node in nodes: UpperCAmelCase__ = config.get(_A ) if config is None: return None, ds_key return config, ds_key def lowercase_ (self : Tuple , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : str=None ) -> List[str]: """simple docstring""" UpperCAmelCase__ = self.find_config_node(_A ) if config is None: return default return config.get(_A , _A ) def lowercase_ (self : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any]=False ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = self.config # find the config node of interest if it exists UpperCAmelCase__ = ds_key_long.split("." ) for node in nodes: UpperCAmelCase__ = config UpperCAmelCase__ = config.get(_A ) if config is None: if must_exist: raise ValueError(f"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(_A ) def lowercase_ (self : Union[str, Any] , __UpperCAmelCase : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.get_value(_A ) return False if value is None else bool(_A ) def lowercase_ (self : str , __UpperCAmelCase : List[str] ) -> str: """simple docstring""" UpperCAmelCase__ = self.get_value(_A ) return False if value is None else not bool(_A ) def lowercase_ (self : str ) -> str: """simple docstring""" return self._stage == 2 def lowercase_ (self : Any ) -> Any: """simple docstring""" return self._stage == 3 def lowercase_ (self : Tuple ) -> Optional[Any]: """simple docstring""" return self._offload class A : def __init__(self : Any , __UpperCAmelCase : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = engine def lowercase_ (self : Dict , __UpperCAmelCase : Tuple , **__UpperCAmelCase : List[Any] ) -> Dict: """simple docstring""" self.engine.backward(_A , **_A ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class A ( snake_case__ ): def __init__(self : List[Any] , __UpperCAmelCase : int ) -> Tuple: """simple docstring""" super().__init__(_A , device_placement=_A , scaler=_A ) UpperCAmelCase__ = hasattr(self.optimizer , "overflow" ) def lowercase_ (self : str , __UpperCAmelCase : Any=None ) -> Optional[int]: """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ (self : str ) -> List[str]: """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ (self : str ) -> Optional[Any]: """simple docstring""" if self.__has_overflow__: return self.optimizer.overflow return False class A ( snake_case__ ): def __init__(self : List[Any] , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Union[str, Any] ) -> Dict: """simple docstring""" super().__init__(_A , _A ) def lowercase_ (self : Optional[int] ) -> int: """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class A : def __init__(self : Dict , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : Dict=0.001 , __UpperCAmelCase : List[Any]=0 , **__UpperCAmelCase : List[str] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = params UpperCAmelCase__ = lr UpperCAmelCase__ = weight_decay UpperCAmelCase__ = kwargs class A : def __init__(self : Optional[Any] , __UpperCAmelCase : str , __UpperCAmelCase : Optional[int]=None , __UpperCAmelCase : Tuple=0 , **__UpperCAmelCase : Any ) -> List[str]: """simple docstring""" UpperCAmelCase__ = optimizer UpperCAmelCase__ = total_num_steps UpperCAmelCase__ = warmup_num_steps UpperCAmelCase__ = kwargs
65
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = 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] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = 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'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = 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] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = 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] , _A , atol=1e-4 ) ) # verify area __A : int = 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'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = 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] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
0
"""simple docstring""" from __future__ import annotations def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->list[tuple[int, int]]: a__: Optional[Any] = position a__: Union[str, Any] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] a__: int = [] for position in positions: a__: Tuple = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(_SCREAMING_SNAKE_CASE ) return permissible_positions def __a ( _SCREAMING_SNAKE_CASE ) ->bool: return not any(elem == 0 for row in board for elem in row ) def __a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->bool: if is_complete(_SCREAMING_SNAKE_CASE ): return True for position in get_valid_pos(_SCREAMING_SNAKE_CASE , len(_SCREAMING_SNAKE_CASE ) ): a__: Any = position if board[y][x] == 0: a__: List[str] = curr + 1 if open_knight_tour_helper(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , curr + 1 ): return True a__: Optional[Any] = 0 return False def __a ( _SCREAMING_SNAKE_CASE ) ->list[list[int]]: a__: Optional[int] = [[0 for i in range(_SCREAMING_SNAKE_CASE )] for j in range(_SCREAMING_SNAKE_CASE )] for i in range(_SCREAMING_SNAKE_CASE ): for j in range(_SCREAMING_SNAKE_CASE ): a__: Optional[Any] = 1 if open_knight_tour_helper(_SCREAMING_SNAKE_CASE , (i, j) , 1 ): return board a__: Any = 0 a__: List[str] = F'Open Kight Tour cannot be performed on a board of size {n}' raise ValueError(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
290
import argparse import json from tqdm import tqdm def _SCREAMING_SNAKE_CASE ( ) -> List[Any]: __A : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '--src_path' , type=a , default='biencoder-nq-dev.json' , help='Path to raw DPR training data' , ) parser.add_argument( '--evaluation_set' , type=a , help='where to store parsed evaluation_set file' , ) parser.add_argument( '--gold_data_path' , type=a , help='where to store parsed gold_data_path file' , ) __A : Optional[int] = parser.parse_args() with open(args.src_path , 'r' ) as src_file, open(args.evaluation_set , 'w' ) as eval_file, open( args.gold_data_path , 'w' ) as gold_file: __A : List[Any] = json.load(a ) for dpr_record in tqdm(a ): __A : Dict = dpr_record['question'] __A : Any = [context['title'] for context in dpr_record['positive_ctxs']] eval_file.write(question + '\n' ) gold_file.write('\t'.join(a ) + '\n' ) if __name__ == "__main__": main()
280
0
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : Optional[int] = TypeVar('T') class UpperCamelCase__ (Generic[T] ): '''simple docstring''' def __init__( self , UpperCamelCase__ = True ) -> Union[str, Any]: lowerCamelCase : dict[T, list[T]] = {} # dictionary of lists lowerCamelCase : str = directed def _lowercase ( self , UpperCamelCase__ , UpperCamelCase__ ) -> Any: if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) self.adj_list[destination_vertex].append(_A ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) lowerCamelCase : Union[str, Any] = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(_A ) lowerCamelCase : Union[str, Any] = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: lowerCamelCase : Optional[Any] = [destination_vertex] lowerCamelCase : str = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(_A ) lowerCamelCase : List[str] = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: lowerCamelCase : str = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: lowerCamelCase : Tuple = [destination_vertex] lowerCamelCase : str = [] return self def __repr__( self ) -> Optional[Any]: return pformat(self.adj_list )
48
from heapq import heappop, heappush import numpy as np def _SCREAMING_SNAKE_CASE ( a , a , a , a , ) -> tuple[float | int, list[tuple[int, int]]]: __A , __A : int = grid.shape __A : Any = [-1, 1, 0, 0] __A : Optional[Any] = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __A , __A : Optional[int] = [(0, source)], set() __A : Any = np.full((rows, cols) , np.inf ) __A : Any = 0 __A : Any = np.empty((rows, cols) , dtype=a ) __A : Optional[Any] = None while queue: ((__A) , (__A)) : List[str] = heappop(a ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __A : int = [] while (x, y) != source: path.append((x, y) ) __A , __A : Optional[int] = predecessors[x, y] path.append(a ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a ) ): __A , __A : Union[str, Any] = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __A : Optional[int] = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a , (dist + 1, (nx, ny)) ) __A : List[Any] = dist + 1 __A : Union[str, Any] = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
280
0
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class UpperCamelCase_ ( snake_case__ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def _UpperCamelCase ( self , a=0 ) -> List[str]: snake_case_ = floats_tensor((1, 3, 1_28, 1_28) , rng=random.Random(_A ) ) snake_case_ = np.random.RandomState(_A ) snake_case_ = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.75, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _UpperCamelCase ( self ) -> Tuple: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def _UpperCamelCase ( self ) -> List[str]: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case_ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_A ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _UpperCamelCase ( self ) -> Optional[Any]: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case_ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) # warmup pass to apply optimizations snake_case_ = pipe(**self.get_dummy_inputs() ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _UpperCamelCase ( self ) -> Union[str, Any]: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case_ = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _UpperCamelCase ( self ) -> Any: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case_ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def _UpperCamelCase ( self ) -> int: snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) snake_case_ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = self.get_dummy_inputs() snake_case_ = pipe(**_A ).images snake_case_ = image[0, -3:, -3:, -1] assert image.shape == (1, 1_28, 1_28, 3) snake_case_ = np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): '''simple docstring''' @property def _UpperCamelCase ( self ) -> Tuple: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _UpperCamelCase ( self ) -> Dict: snake_case_ = ort.SessionOptions() snake_case_ = False return options def _UpperCamelCase ( self ) -> int: snake_case_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) snake_case_ = init_image.resize((7_68, 5_12) ) # using the PNDM scheduler by default snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = 'A fantasy landscape, trending on artstation' snake_case_ = np.random.RandomState(0 ) snake_case_ = pipe( prompt=_A , image=_A , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=_A , output_type='np' , ) snake_case_ = output.images snake_case_ = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) snake_case_ = np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def _UpperCamelCase ( self ) -> str: snake_case_ = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) snake_case_ = init_image.resize((7_68, 5_12) ) snake_case_ = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) snake_case_ = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=_A , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) snake_case_ = 'A fantasy landscape, trending on artstation' snake_case_ = np.random.RandomState(0 ) snake_case_ = pipe( prompt=_A , image=_A , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=_A , output_type='np' , ) snake_case_ = output.images snake_case_ = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 7_68, 3) snake_case_ = np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
178
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) UpperCAmelCase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name UpperCAmelCase : Dict = ''' Examples: ```py >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline >>> from diffusers.utils import load_image >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16 ... ) >>> pipe_prior.to("cuda") >>> prompt = "A red cartoon frog, 4k" >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False) >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained( ... "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16 ... ) >>> pipe.to("cuda") >>> init_image = load_image( ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" ... "/kandinsky/frog.png" ... ) >>> image = pipe( ... image=init_image, ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... strength=0.2, ... ).images >>> image[0].save("red_frog.png") ``` ''' def _SCREAMING_SNAKE_CASE ( a , a , a=8 ) -> Tuple: __A : List[str] = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 __A : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def _SCREAMING_SNAKE_CASE ( a , a=5_12 , a=5_12 ) -> int: __A : Optional[Any] = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 ) __A : Union[str, Any] = np.array(pil_image.convert('RGB' ) ) __A : Optional[int] = arr.astype(np.floataa ) / 127.5 - 1 __A : int = np.transpose(a , [2, 0, 1] ) __A : Tuple = torch.from_numpy(a ).unsqueeze(0 ) return image class _A( snake_case__ ): """simple docstring""" def __init__( self , _A , _A , _A , ): super().__init__() self.register_modules( unet=_A , scheduler=_A , movq=_A , ) __A : Tuple = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCAmelCase_ ( self , _A , _A , _A ): # get the original timestep using init_timestep __A : Optional[int] = min(int(num_inference_steps * strength ) , _A ) __A : Dict = max(num_inference_steps - init_timestep , 0 ) __A : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A=None ): if not isinstance(_A , (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(_A )}""" ) __A : Union[str, Any] = image.to(device=_A , dtype=_A ) __A : Optional[Any] = batch_size * num_images_per_prompt if image.shape[1] == 4: __A : int = image else: if isinstance(_A , _A ) and len(_A ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(_A )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) elif isinstance(_A , _A ): __A : str = [ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_A ) ] __A : str = torch.cat(_A , dim=0 ) else: __A : List[str] = self.movq.encode(_A ).latent_dist.sample(_A ) __A : Tuple = self.movq.config.scaling_factor * init_latents __A : Optional[int] = torch.cat([init_latents] , dim=0 ) __A : Union[str, Any] = init_latents.shape __A : List[str] = randn_tensor(_A , generator=_A , device=_A , dtype=_A ) # get latents __A : Optional[Any] = self.scheduler.add_noise(_A , _A , _A ) __A : Optional[int] = init_latents return latents def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) __A : Optional[int] = torch.device(F"""cuda:{gpu_id}""" ) __A : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_A , _A ) def UpperCAmelCase_ ( self , _A=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) __A : List[Any] = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __A : int = None for cpu_offloaded_model in [self.unet, self.movq]: __A , __A : Optional[int] = cpu_offload_with_hook(_A , _A , prev_module_hook=_A ) # We'll offload the last model manually. __A : List[str] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCAmelCase_ ( self ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_A , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_A ) def __call__( self , _A , _A , _A , _A = 512 , _A = 512 , _A = 100 , _A = 4.0 , _A = 0.3 , _A = 1 , _A = None , _A = "pil" , _A = True , ): __A : List[Any] = self._execution_device __A : Optional[Any] = guidance_scale > 1.0 if isinstance(_A , _A ): __A : Optional[Any] = torch.cat(_A , dim=0 ) __A : Tuple = image_embeds.shape[0] if isinstance(_A , _A ): __A : List[Any] = torch.cat(_A , dim=0 ) if do_classifier_free_guidance: __A : Union[str, Any] = image_embeds.repeat_interleave(_A , dim=0 ) __A : Optional[int] = negative_image_embeds.repeat_interleave(_A , dim=0 ) __A : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_A ) if not isinstance(_A , _A ): __A : List[Any] = [image] if not all(isinstance(_A , (PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( F"""Input is in incorrect format: {[type(_A ) for i in image]}. Currently, we only support PIL image and pytorch tensor""" ) __A : Dict = torch.cat([prepare_image(_A , _A , _A ) for i in image] , dim=0 ) __A : Any = image.to(dtype=image_embeds.dtype , device=_A ) __A : Tuple = self.movq.encode(_A )['latents'] __A : int = latents.repeat_interleave(_A , dim=0 ) self.scheduler.set_timesteps(_A , device=_A ) __A , __A : int = self.get_timesteps(_A , _A , _A ) __A : Union[str, Any] = timesteps[:1].repeat(batch_size * num_images_per_prompt ) __A , __A : Any = downscale_height_and_width(_A , _A , self.movq_scale_factor ) __A : Tuple = self.prepare_latents( _A , _A , _A , _A , image_embeds.dtype , _A , _A ) for i, t in enumerate(self.progress_bar(_A ) ): # expand the latents if we are doing classifier free guidance __A : Optional[int] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __A : Dict = {'image_embeds': image_embeds} __A : List[str] = self.unet( sample=_A , timestep=_A , encoder_hidden_states=_A , added_cond_kwargs=_A , return_dict=_A , )[0] if do_classifier_free_guidance: __A , __A : Dict = noise_pred.split(latents.shape[1] , dim=1 ) __A , __A : Optional[Any] = noise_pred.chunk(2 ) __A , __A : List[str] = variance_pred.chunk(2 ) __A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __A : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __A , __A : Optional[Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 __A : List[str] = self.scheduler.step( _A , _A , _A , generator=_A , )[0] # post-processing __A : List[Any] = self.movq.decode(_A , force_not_quantize=_A )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: __A : List[str] = image * 0.5 + 0.5 __A : List[str] = image.clamp(0 , 1 ) __A : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": __A : Any = self.numpy_to_pil(_A ) if not return_dict: return (image,) return ImagePipelineOutput(images=_A )
280
0
'''simple docstring''' from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def _UpperCAmelCase ( _lowerCamelCase : str ) -> List[Any]: # A local function to see if a dot lands in the circle. def is_in_circle(_lowerCamelCase : Union[str, Any] , _lowerCamelCase : Tuple ) -> bool: _lowerCAmelCase : Any = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle _lowerCAmelCase : Dict = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(_lowerCamelCase ) ) # The ratio of the area for circle to square is pi/4. _lowerCAmelCase : Optional[int] = proportion * 4 print(f'The estimated value of pi is {pi_estimate}' ) print(f'The numpy value of pi is {pi}' ) print(f'The total error is {abs(pi - pi_estimate )}' ) def _UpperCAmelCase ( _lowerCamelCase : Any , _lowerCamelCase : Union[str, Any] , _lowerCamelCase : int = 0.0 , _lowerCamelCase : int = 1.0 , ) -> float: return mean( function_to_integrate(uniform(_lowerCamelCase , _lowerCamelCase ) ) for _ in range(_lowerCamelCase ) ) * (max_value - min_value) def _UpperCAmelCase ( _lowerCamelCase : Optional[Any] , _lowerCamelCase : Tuple = 0.0 , _lowerCamelCase : Optional[int] = 1.0 ) -> None: def identity_function(_lowerCamelCase : Any ) -> float: return x _lowerCAmelCase : int = area_under_curve_estimator( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : List[str] = (max_value * max_value - min_value * min_value) / 2 print("""******************""" ) print(f'Estimating area under y=x where x varies from {min_value} to {max_value}' ) print(f'Estimated value is {estimated_value}' ) print(f'Expected value is {expected_value}' ) print(f'Total error is {abs(estimated_value - expected_value )}' ) print("""******************""" ) def _UpperCAmelCase ( _lowerCamelCase : List[str] ) -> None: def function_to_integrate(_lowerCamelCase : Optional[Any] ) -> float: return sqrt(4.0 - x * x ) _lowerCAmelCase : List[Any] = area_under_curve_estimator( _lowerCamelCase , _lowerCamelCase , 0.0 , 2.0 ) print("""******************""" ) print("""Estimating pi using area_under_curve_estimator""" ) print(f'Estimated value is {estimated_value}' ) print(f'Expected value is {pi}' ) print(f'Total error is {abs(estimated_value - pi )}' ) print("""******************""" ) if __name__ == "__main__": import doctest doctest.testmod()
309
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
0
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int lowercase_ = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __lowerCAmelCase ( datasets.BuilderConfig ): _a = None def a ( A__ : Dict , A__ : List[Any] , ) -> Union[str, Any]: """simple docstring""" import pyspark def generate_fn(): _lowercase =df.select('*' , pyspark.sql.functions.spark_partition_id().alias('part_id' ) ) for partition_id in partition_order: _lowercase =df_with_partition_id.select('*' ).where(F'''part_id = {partition_id}''' ).drop('part_id' ) _lowercase =partition_df.collect() _lowercase =0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class __lowerCAmelCase ( _BaseExamplesIterable ): def __init__( self , lowerCAmelCase , lowerCAmelCase=None , ) -> List[str]: '''simple docstring''' _lowercase =df _lowercase =partition_order or range(self.df.rdd.getNumPartitions() ) _lowercase =_generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Optional[int]: '''simple docstring''' yield from self.generate_examples_fn() def A__ ( self , lowerCAmelCase ) -> Union[str, Any]: '''simple docstring''' _lowercase =list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(_A ) return SparkExamplesIterable(self.df , partition_order=_A ) def A__ ( self , lowerCAmelCase , lowerCAmelCase ) -> Any: '''simple docstring''' _lowercase =self.split_shard_indices_by_worker(_A , _A ) return SparkExamplesIterable(self.df , partition_order=_A ) @property def A__ ( self ) -> List[Any]: '''simple docstring''' return len(self.partition_order ) class __lowerCAmelCase ( datasets.DatasetBuilder ): _a = SparkConfig def __init__( self , lowerCAmelCase , lowerCAmelCase = None , lowerCAmelCase = None , **lowerCAmelCase , ) -> List[str]: '''simple docstring''' import pyspark _lowercase =pyspark.sql.SparkSession.builder.getOrCreate() _lowercase =df _lowercase =working_dir super().__init__( cache_dir=_A , config_name=str(self.df.semanticHash() ) , **_A , ) def A__ ( self ) -> str: '''simple docstring''' def create_cache_and_write_probe(lowerCAmelCase ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=_A ) _lowercase =os.path.join(self._cache_dir , 'fs_test' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_A , 'a' ) return [probe_file] if self._spark.conf.get('spark.master' , '' ).startswith('local' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: _lowercase =( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(_A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( 'When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir' ) def A__ ( self ) -> List[Any]: '''simple docstring''' return datasets.DatasetInfo(features=self.config.features ) def A__ ( self , lowerCAmelCase ) -> Tuple: '''simple docstring''' return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def A__ ( self , lowerCAmelCase ) -> Tuple: '''simple docstring''' import pyspark def get_arrow_batch_size(lowerCAmelCase ): for batch in it: yield pa.RecordBatch.from_pydict({'batch_bytes': [batch.nbytes]} ) _lowercase =self.df.count() _lowercase =df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. _lowercase =( self.df.limit(_A ) .repartition(1 ) .mapInArrow(_A , 'batch_bytes: long' ) .agg(pyspark.sql.functions.sum('batch_bytes' ).alias('sample_bytes' ) ) .collect()[0] .sample_bytes / sample_num_rows ) _lowercase =approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. _lowercase =min(_A , int(approx_total_size / max_shard_size ) ) _lowercase =self.df.repartition(_A ) def A__ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ) -> List[str]: '''simple docstring''' import pyspark _lowercase =ParquetWriter if file_format == 'parquet' else ArrowWriter _lowercase =os.path.join(self._working_dir , os.path.basename(_A ) ) if self._working_dir else fpath _lowercase =file_format == 'parquet' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. _lowercase =self.config.features _lowercase =self._writer_batch_size _lowercase =self._fs.storage_options def write_arrow(lowerCAmelCase ): # Within the same SparkContext, no two task attempts will share the same attempt ID. _lowercase =pyspark.TaskContext().taskAttemptId() _lowercase =next(_A , _A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['task_id', 'num_examples', 'num_bytes'] , ) _lowercase =0 _lowercase =writer_class( features=_A , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) _lowercase =pa.Table.from_batches([first_batch] ) writer.write_table(_A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: _lowercase =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) shard_id += 1 _lowercase =writer_class( features=writer._features , path=working_fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) _lowercase =pa.Table.from_batches([batch] ) writer.write_table(_A ) if writer._num_bytes > 0: _lowercase =writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['task_id', 'num_examples', 'num_bytes'] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_A ) ): _lowercase =os.path.join(os.path.dirname(_A ) , os.path.basename(_A ) ) shutil.move(_A , _A ) _lowercase =( self.df.mapInArrow(_A , 'task_id: long, num_examples: long, num_bytes: long' ) .groupBy('task_id' ) .agg( pyspark.sql.functions.sum('num_examples' ).alias('total_num_examples' ) , pyspark.sql.functions.sum('num_bytes' ).alias('total_num_bytes' ) , pyspark.sql.functions.count('num_bytes' ).alias('num_shards' ) , pyspark.sql.functions.collect_list('num_examples' ).alias('shard_lengths' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def A__ ( self , lowerCAmelCase , lowerCAmelCase = "arrow" , lowerCAmelCase = None , lowerCAmelCase = None , **lowerCAmelCase , ) -> str: '''simple docstring''' self._validate_cache_dir() _lowercase =convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(_A ) _lowercase =not is_remote_filesystem(self._fs ) _lowercase =os.path.join if is_local else posixpath.join _lowercase ='-TTTTT-SSSSS-of-NNNNN' _lowercase =F'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' _lowercase =path_join(self._output_dir , _A ) _lowercase =0 _lowercase =0 _lowercase =0 _lowercase =[] _lowercase =[] for task_id, content in self._prepare_split_single(_A , _A , _A ): ( _lowercase ) =content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(_A ) _lowercase =total_num_examples _lowercase =total_num_bytes # should rename everything at the end logger.debug(F'''Renaming {total_shards} shards.''' ) if total_shards > 1: _lowercase =all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. _lowercase =self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): rename( _A , fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace('TTTTT-SSSSS' , F'''{global_shard_id:05d}''' ).replace('NNNNN' , F'''{total_shards:05d}''' ) , ) _lowercase =[] _lowercase =0 for i in range(len(_A ) ): _lowercase =task_id_and_num_shards[i] for shard_id in range(_A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(_A , len(_A ) ).map(lambda lowerCAmelCase : _rename_shard(*_A ) ).collect() else: # don't use any pattern _lowercase =0 _lowercase =task_id_and_num_shards[0][0] self._rename( fpath.replace('SSSSS' , F'''{shard_id:05d}''' ).replace('TTTTT' , F'''{task_id:05d}''' ) , fpath.replace(_A , '' ) , ) def A__ ( self , lowerCAmelCase , ) -> Tuple: '''simple docstring''' return SparkExamplesIterable(self.df )
205
import colorsys from PIL import Image # type: ignore def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: __A : List[str] = x __A : str = y for step in range(a ): # noqa: B007 __A : Union[str, Any] = a * a - b * b + x __A : Optional[int] = 2 * a * b + y __A : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def _SCREAMING_SNAKE_CASE ( a ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(a , 1 , 1 ) ) def _SCREAMING_SNAKE_CASE ( a = 8_00 , a = 6_00 , a = -0.6 , a = 0 , a = 3.2 , a = 50 , a = True , ) -> Image.Image: __A : str = Image.new('RGB' , (image_width, image_height) ) __A : Dict = img.load() # loop through the image-coordinates for image_x in range(a ): for image_y in range(a ): # determine the figure-coordinates based on the image-coordinates __A : Dict = figure_width / image_width * image_height __A : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width __A : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height __A : Union[str, Any] = get_distance(a , a , a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: __A : Optional[Any] = get_color_coded_rgb(a ) else: __A : Dict = get_black_and_white_rgb(a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
280
0
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ = {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ['''TimmBackbone'''] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
346
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a , a , a ) -> float: if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE ( a , a , a , ) -> float: if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( a , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from ...utils import BaseOutput, OptionalDependencyNotAvailable, is_torch_available, is_transformers_available from .timesteps import ( fastaa_timesteps, smartaa_timesteps, smartaa_timesteps, smartaaa_timesteps, smartaaa_timesteps, superaa_timesteps, superaa_timesteps, superaaa_timesteps, ) @dataclass class snake_case ( snake_case__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_if import IFPipeline from .pipeline_if_imgaimg import IFImgaImgPipeline from .pipeline_if_imgaimg_superresolution import IFImgaImgSuperResolutionPipeline from .pipeline_if_inpainting import IFInpaintingPipeline from .pipeline_if_inpainting_superresolution import IFInpaintingSuperResolutionPipeline from .pipeline_if_superresolution import IFSuperResolutionPipeline from .safety_checker import IFSafetyChecker from .watermark import IFWatermarker
98
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) UpperCAmelCase : Any = { '''configuration_falcon''': ['''FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FalconConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Any = [ '''FALCON_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FalconForCausalLM''', '''FalconModel''', '''FalconPreTrainedModel''', '''FalconForSequenceClassification''', '''FalconForTokenClassification''', '''FalconForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
import colorsys from PIL import Image # type: ignore def __snake_case ( _lowerCAmelCase : List[str] , _lowerCAmelCase : Tuple , _lowerCAmelCase : Dict ) -> float: A_ : List[str] = x A_ : str = y for step in range(_lowerCAmelCase ): # noqa: B007 A_ : Union[str, Any] = a * a - b * b + x A_ : Optional[int] = 2 * a * b + y A_ : List[str] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def __snake_case ( _lowerCAmelCase : str ) -> tuple: if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def __snake_case ( _lowerCAmelCase : List[str] ) -> tuple: if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(_lowerCAmelCase , 1 , 1 ) ) def __snake_case ( _lowerCAmelCase : Optional[int] = 800 , _lowerCAmelCase : Union[str, Any] = 600 , _lowerCAmelCase : Optional[int] = -0.6 , _lowerCAmelCase : Optional[int] = 0 , _lowerCAmelCase : Union[str, Any] = 3.2 , _lowerCAmelCase : List[Any] = 50 , _lowerCAmelCase : int = True , ) -> Image.Image: A_ : str = Image.new("RGB" , (image_width, image_height) ) A_ : Dict = img.load() # loop through the image-coordinates for image_x in range(_lowerCAmelCase ): for image_y in range(_lowerCAmelCase ): # determine the figure-coordinates based on the image-coordinates A_ : Dict = figure_width / image_width * image_height A_ : Union[str, Any] = figure_center_x + (image_x / image_width - 0.5) * figure_width A_ : Optional[Any] = figure_center_y + (image_y / image_height - 0.5) * figure_height A_ : Union[str, Any] = get_distance(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: A_ : Optional[Any] = get_color_coded_rgb(_lowerCAmelCase ) else: A_ : Dict = get_black_and_white_rgb(_lowerCAmelCase ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure _lowerCAmelCase : str = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
300
def _SCREAMING_SNAKE_CASE ( a ) -> bool: return str(a ) == str(a )[::-1] def _SCREAMING_SNAKE_CASE ( a ) -> int: return int(a ) + int(str(a )[::-1] ) def _SCREAMING_SNAKE_CASE ( a = 1_00_00 ) -> int: __A : int = [] for num in range(1 , a ): __A : List[str] = 0 __A : List[Any] = num while iterations < 50: __A : str = sum_reverse(a ) iterations += 1 if is_palindrome(a ): break else: lychrel_nums.append(a ) return len(a ) if __name__ == "__main__": print(F"""{solution() = }""")
280
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { '''bigcode/gpt_bigcode-santacoder''': '''https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json''', } class a_ ( snake_case__ ): '''simple docstring''' UpperCamelCase = '''gpt_bigcode''' UpperCamelCase = ['''past_key_values'''] UpperCamelCase = { '''hidden_size''': '''n_embd''', '''max_position_embeddings''': '''n_positions''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , A=5_0257 , A=1024 , A=768 , A=12 , A=12 , A=None , A="gelu_pytorch_tanh" , A=0.1 , A=0.1 , A=0.1 , A=1e-5 , A=0.02 , A=True , A=True , A=5_0256 , A=5_0256 , A=True , A=True , A=True , **A , ) -> Tuple: _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = n_positions _SCREAMING_SNAKE_CASE = n_embd _SCREAMING_SNAKE_CASE = n_layer _SCREAMING_SNAKE_CASE = n_head _SCREAMING_SNAKE_CASE = n_inner _SCREAMING_SNAKE_CASE = activation_function _SCREAMING_SNAKE_CASE = resid_pdrop _SCREAMING_SNAKE_CASE = embd_pdrop _SCREAMING_SNAKE_CASE = attn_pdrop _SCREAMING_SNAKE_CASE = layer_norm_epsilon _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = scale_attn_weights _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = attention_softmax_in_fpaa _SCREAMING_SNAKE_CASE = scale_attention_softmax_in_fpaa _SCREAMING_SNAKE_CASE = multi_query _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id super().__init__(bos_token_id=_A , eos_token_id=_A , **_A )
58
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class _A: """simple docstring""" def __init__( self , _A = None ): if components is None: __A : int = [] __A : Tuple = list(_A ) def __len__( self ): return len(self.__components ) def __str__( self ): return "(" + ",".join(map(_A , self.__components ) ) + ")" def __add__( self , _A ): __A : Optional[int] = len(self ) if size == len(_A ): __A : Any = [self.__components[i] + other.component(_A ) for i in range(_A )] return Vector(_A ) else: raise Exception('must have the same size' ) def __sub__( self , _A ): __A : Tuple = len(self ) if size == len(_A ): __A : Union[str, Any] = [self.__components[i] - other.component(_A ) for i in range(_A )] return Vector(_A ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , (float, int) ): __A : str = [c * other for c in self.__components] return Vector(_A ) elif isinstance(_A , _A ) and len(self ) == len(_A ): __A : Union[str, Any] = len(self ) __A : Dict = [self.__components[i] * other.component(_A ) for i in range(_A )] return sum(_A ) else: # error case raise Exception('invalid operand!' ) def UpperCAmelCase_ ( self ): return Vector(self.__components ) def UpperCAmelCase_ ( self , _A ): if isinstance(_A , _A ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def UpperCAmelCase_ ( self , _A , _A ): assert -len(self.__components ) <= pos < len(self.__components ) __A : Optional[int] = value def UpperCAmelCase_ ( self ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __A : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(_A ) ) def UpperCAmelCase_ ( self , _A , _A = False ): __A : Optional[Any] = self * other __A : Optional[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def _SCREAMING_SNAKE_CASE ( a ) -> Vector: assert isinstance(a , a ) return Vector([0] * dimension ) def _SCREAMING_SNAKE_CASE ( a , a ) -> Vector: assert isinstance(a , a ) and (isinstance(a , a )) __A : Optional[Any] = [0] * dimension __A : Tuple = 1 return Vector(a ) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: assert ( isinstance(a , a ) and isinstance(a , a ) and (isinstance(a , (int, float) )) ) return x * scalar + y def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Vector: random.seed(a ) __A : str = [random.randint(a , a ) for _ in range(a )] return Vector(a ) class _A: """simple docstring""" def __init__( self , _A , _A , _A ): __A : Optional[Any] = matrix __A : Dict = w __A : Optional[int] = h def __str__( self ): __A : Tuple = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Optional[Any] = [] for i in range(self.__height ): __A : Optional[Any] = [ self.__matrix[i][j] + other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self , _A ): if self.__width == other.width() and self.__height == other.height(): __A : Tuple = [] for i in range(self.__height ): __A : str = [ self.__matrix[i][j] - other.component(_A , _A ) for j in range(self.__width ) ] matrix.append(_A ) return Matrix(_A , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self , _A ): ... @overload def __mul__( self , _A ): ... def __mul__( self , _A ): if isinstance(_A , _A ): # matrix-vector if len(_A ) == self.__width: __A : List[Any] = zero_vector(self.__height ) for i in range(self.__height ): __A : List[str] = [ self.__matrix[i][j] * other.component(_A ) for j in range(self.__width ) ] ans.change_component(_A , sum(_A ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(_A , (int, float) ): # matrix-scalar __A : List[str] = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(_A , self.__width , self.__height ) return None def UpperCAmelCase_ ( self ): return self.__height def UpperCAmelCase_ ( self ): return self.__width def UpperCAmelCase_ ( self , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A , _A ): if 0 <= x < self.__height and 0 <= y < self.__width: __A : int = value else: raise Exception('change_component: indices out of bounds' ) def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __A : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(_A ) ): __A : Optional[int] = minor[i][:y] + minor[i][y + 1 :] return Matrix(_A , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self , _A , _A ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(_A , _A ) else: raise Exception('Indices out of bounds' ) def UpperCAmelCase_ ( self ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __A : List[str] = [ self.__matrix[0][y] * self.cofactor(0 , _A ) for y in range(self.__width ) ] return sum(_A ) def _SCREAMING_SNAKE_CASE ( a ) -> Matrix: __A : list[list[float]] = [[0] * n for _ in range(a )] return Matrix(a , a , a ) def _SCREAMING_SNAKE_CASE ( a , a , a , a ) -> Matrix: random.seed(a ) __A : list[list[float]] = [ [random.randint(a , a ) for _ in range(a )] for _ in range(a ) ] return Matrix(a , a , a )
280
0
# Lint as: python3 import itertools import os import re a_ = re.compile(r'([A-Z]+)([A-Z][a-z])') a_ = re.compile(r'([a-z\d])([A-Z])') a_ = re.compile(r'(?<!_)_(?!_)') a_ = re.compile(r'(_{2,})') a_ = r'''^\w+(\.\w+)*$''' a_ = r'''<>:/\|?*''' def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Dict = _uppercase_uppercase_re.sub(r"\1_\2" , _a) SCREAMING_SNAKE_CASE : Dict = _lowercase_uppercase_re.sub(r"\1_\2" , _a) return name.lower() def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : str = _single_underscore_re.split(_a) SCREAMING_SNAKE_CASE : Tuple = [_multiple_underscores_re.split(_a) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(_a) if n != "") def lowerCamelCase__ ( _a): if os.path.basename(_a) != name: raise ValueError(f"Should be a dataset name, not a path: {name}") return camelcase_to_snakecase(_a) def lowerCamelCase__ ( _a , _a): if os.path.basename(_a) != name: raise ValueError(f"Should be a dataset name, not a path: {name}") if not re.match(_split_re , _a): raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'.") return f"{filename_prefix_for_name(_a)}-{split}" def lowerCamelCase__ ( _a , _a , _a , _a=None): SCREAMING_SNAKE_CASE : int = filename_prefix_for_split(_a , _a) if filetype_suffix: prefix += f".{filetype_suffix}" SCREAMING_SNAKE_CASE : str = os.path.join(_a , _a) return f"{filepath}*" def lowerCamelCase__ ( _a , _a , _a , _a=None , _a=None): SCREAMING_SNAKE_CASE : Tuple = filename_prefix_for_split(_a , _a) SCREAMING_SNAKE_CASE : Any = os.path.join(_a , _a) if shard_lengths: SCREAMING_SNAKE_CASE : Optional[Any] = len(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(_a)] if filetype_suffix: SCREAMING_SNAKE_CASE : Optional[int] = [filename + f".{filetype_suffix}" for filename in filenames] return filenames else: SCREAMING_SNAKE_CASE : Optional[int] = prefix if filetype_suffix: filename += f".{filetype_suffix}" return [filename]
76
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase : List[str] = '''▁''' UpperCAmelCase : Optional[Any] = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Optional[int] = BertGenerationTokenizer UpperCamelCase : str = False UpperCamelCase : Tuple = True def UpperCAmelCase_ ( self ): super().setUp() __A : Tuple = BertGenerationTokenizer(_A , keep_accents=_A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : str = '<s>' __A : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_A ) , _A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_A ) , _A ) def UpperCAmelCase_ ( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<pad>' ) self.assertEqual(len(_A ) , 1002 ) def UpperCAmelCase_ ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): __A : str = BertGenerationTokenizer(_A , keep_accents=_A ) __A : Dict = tokenizer.tokenize('This is a test' ) self.assertListEqual(_A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_A ) , [285, 46, 10, 170, 382] , ) __A : int = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) __A : Dict = tokenizer.convert_tokens_to_ids(_A ) self.assertListEqual( _A , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : Optional[int] = tokenizer.convert_ids_to_tokens(_A ) self.assertListEqual( _A , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def UpperCAmelCase_ ( self ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def UpperCAmelCase_ ( self ): __A : List[Any] = 'Hello World!' __A : Optional[Any] = [18536, 2260, 101] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @slow def UpperCAmelCase_ ( self ): __A : Dict = ( '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' ) __A : int = [ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(_A , self.big_tokenizer.encode(_A ) ) @require_torch @slow def UpperCAmelCase_ ( self ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : List[Any] = ' '.join(_A ) __A : Union[str, Any] = self.big_tokenizer.encode_plus(_A , return_tensors='pt' , return_token_type_ids=_A ) __A : Optional[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=_A ) __A : int = BertGenerationConfig() __A : List[str] = BertGenerationEncoder(_A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_A ) model(**_A ) @slow def UpperCAmelCase_ ( self ): # fmt: off __A : str = {'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_A , model_name='google/bert_for_seq_generation_L-24_bbc_encoder' , revision='c817d1fd1be2ffa69431227a1fe320544943d4db' , )
280
0
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 OwlViTImageProcessor, OwlViTProcessor @require_vision class A ( unittest.TestCase ): def lowercase_ (self : int ) -> Dict: """simple docstring""" UpperCAmelCase__ = tempfile.mkdtemp() # fmt: off UpperCAmelCase__ = ['', '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 UpperCAmelCase__ = dict(zip(_A , range(len(_A ) ) ) ) UpperCAmelCase__ = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] UpperCAmelCase__ = {'unk_token': '<unk>'} UpperCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase__ = 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(_A ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(_A ) ) UpperCAmelCase__ = { 'do_resize': True, 'size': 2_0, 'do_center_crop': True, 'crop_size': 1_8, 'do_normalize': True, 'image_mean': [0.48145466, 0.4578275, 0.40821073], 'image_std': [0.26862954, 0.26130258, 0.27577711], } UpperCAmelCase__ = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(_A , _A ) def lowercase_ (self : str , **__UpperCAmelCase : Optional[Any] ) -> Any: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token="!" , **_A ) def lowercase_ (self : Dict , **__UpperCAmelCase : str ) -> Optional[int]: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token="!" , **_A ) def lowercase_ (self : int , **__UpperCAmelCase : str ) -> Any: """simple docstring""" return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def lowercase_ (self : Union[str, Any] ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def lowercase_ (self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] UpperCAmelCase__ = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowercase_ (self : Tuple ) -> int: """simple docstring""" UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = self.get_rust_tokenizer() UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = OwlViTProcessor.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 , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) 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 , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def lowercase_ (self : Union[str, Any] ) -> Dict: """simple docstring""" UpperCAmelCase__ = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase__ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) UpperCAmelCase__ = self.get_image_processor(do_normalize=_A ) UpperCAmelCase__ = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def lowercase_ (self : List[str] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = image_processor(_A , return_tensors="np" ) UpperCAmelCase__ = processor(images=_A , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowercase_ (self : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) UpperCAmelCase__ = 'lower newer' UpperCAmelCase__ = processor(text=_A , return_tensors="np" ) UpperCAmelCase__ = tokenizer(_A , return_tensors="np" ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def lowercase_ (self : int ) -> str: """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) UpperCAmelCase__ = 'lower newer' UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def lowercase_ (self : int ) -> int: """simple docstring""" UpperCAmelCase__ = 'google/owlvit-base-patch32' UpperCAmelCase__ = OwlViTProcessor.from_pretrained(_A ) UpperCAmelCase__ = ['cat', 'nasa badge'] UpperCAmelCase__ = processor(text=_A ) UpperCAmelCase__ = 1_6 self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] ) self.assertEqual(inputs["input_ids"].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def lowercase_ (self : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = 'google/owlvit-base-patch32' UpperCAmelCase__ = OwlViTProcessor.from_pretrained(_A ) UpperCAmelCase__ = [['cat', 'nasa badge'], ['person']] UpperCAmelCase__ = processor(text=_A ) UpperCAmelCase__ = 1_6 UpperCAmelCase__ = len(_A ) UpperCAmelCase__ = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] ) self.assertEqual(inputs["input_ids"].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def lowercase_ (self : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase__ = 'google/owlvit-base-patch32' UpperCAmelCase__ = OwlViTProcessor.from_pretrained(_A ) UpperCAmelCase__ = ['cat', 'nasa badge'] UpperCAmelCase__ = processor(text=_A ) UpperCAmelCase__ = 1_6 UpperCAmelCase__ = inputs['input_ids'] UpperCAmelCase__ = [ [4_9_4_0_6, 2_3_6_8, 4_9_4_0_7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [4_9_4_0_6, 6_8_4_1, 1_1_3_0_1, 4_9_4_0_7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ["input_ids", "attention_mask"] ) self.assertEqual(inputs["input_ids"].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def lowercase_ (self : Union[str, Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = self.prepare_image_inputs() UpperCAmelCase__ = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ["query_pixel_values", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def lowercase_ (self : str ) -> str: """simple docstring""" UpperCAmelCase__ = self.get_image_processor() UpperCAmelCase__ = self.get_tokenizer() UpperCAmelCase__ = OwlViTProcessor(tokenizer=_A , image_processor=_A ) UpperCAmelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCAmelCase__ = processor.batch_decode(_A ) UpperCAmelCase__ = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
65
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _A: """simple docstring""" @staticmethod def UpperCAmelCase_ ( *_A , **_A ): pass def _SCREAMING_SNAKE_CASE ( a ) -> str: __A : str = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def _SCREAMING_SNAKE_CASE ( a ) -> Dict: __A : Dict = np.array(a ) __A : List[Any] = npimg.shape return {"hash": hashimage(a ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _A( unittest.TestCase ): """simple docstring""" UpperCamelCase : str = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase : int = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def UpperCAmelCase_ ( self , _A , _A , _A ): __A : Dict = MaskGenerationPipeline(model=_A , image_processor=_A ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def UpperCAmelCase_ ( self , _A , _A ): pass @require_tf @unittest.skip('Image segmentation not implemented in TF' ) def UpperCAmelCase_ ( self ): pass @slow @require_torch def UpperCAmelCase_ ( self ): __A : Union[str, Any] = pipeline('mask-generation' , model='facebook/sam-vit-huge' ) __A : List[str] = image_segmenter('http://images.cocodataset.org/val2017/000000039769.jpg' , points_per_batch=256 ) # Shortening by hashing __A : List[Any] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, {'mask': {'hash': 'e2d0b7a0b7', 'shape': (480, 640)}, 'scores': 0.9_9_6_7}, {'mask': {'hash': '453c7844bd', 'shape': (480, 640)}, 'scores': 0.9_9_3}, {'mask': {'hash': '3d44f2926d', 'shape': (480, 640)}, 'scores': 0.9_9_0_9}, {'mask': {'hash': '64033ddc3f', 'shape': (480, 640)}, 'scores': 0.9_8_7_9}, {'mask': {'hash': '801064ff79', 'shape': (480, 640)}, 'scores': 0.9_8_3_4}, {'mask': {'hash': '6172f276ef', 'shape': (480, 640)}, 'scores': 0.9_7_1_6}, {'mask': {'hash': 'b49e60e084', 'shape': (480, 640)}, 'scores': 0.9_6_1_2}, {'mask': {'hash': 'a811e775fd', 'shape': (480, 640)}, 'scores': 0.9_5_9_9}, {'mask': {'hash': 'a6a8ebcf4b', 'shape': (480, 640)}, 'scores': 0.9_5_5_2}, {'mask': {'hash': '9d8257e080', 'shape': (480, 640)}, 'scores': 0.9_5_3_2}, {'mask': {'hash': '32de6454a8', 'shape': (480, 640)}, 'scores': 0.9_5_1_6}, {'mask': {'hash': 'af3d4af2c8', 'shape': (480, 640)}, 'scores': 0.9_4_9_9}, {'mask': {'hash': '3c6db475fb', 'shape': (480, 640)}, 'scores': 0.9_4_8_3}, {'mask': {'hash': 'c290813fb9', 'shape': (480, 640)}, 'scores': 0.9_4_6_4}, {'mask': {'hash': 'b6f0b8f606', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': '92ce16bfdf', 'shape': (480, 640)}, 'scores': 0.9_4_3}, {'mask': {'hash': 'c749b25868', 'shape': (480, 640)}, 'scores': 0.9_4_0_8}, {'mask': {'hash': 'efb6cab859', 'shape': (480, 640)}, 'scores': 0.9_3_3_5}, {'mask': {'hash': '1ff2eafb30', 'shape': (480, 640)}, 'scores': 0.9_3_2_6}, {'mask': {'hash': '788b798e24', 'shape': (480, 640)}, 'scores': 0.9_2_6_2}, {'mask': {'hash': 'abea804f0e', 'shape': (480, 640)}, 'scores': 0.8_9_9_9}, {'mask': {'hash': '7b9e8ddb73', 'shape': (480, 640)}, 'scores': 0.8_9_8_6}, {'mask': {'hash': 'cd24047c8a', 'shape': (480, 640)}, 'scores': 0.8_9_8_4}, {'mask': {'hash': '6943e6bcbd', 'shape': (480, 640)}, 'scores': 0.8_8_7_3}, {'mask': {'hash': 'b5f47c9191', 'shape': (480, 640)}, 'scores': 0.8_8_7_1} ] , ) # fmt: on @require_torch @slow def UpperCAmelCase_ ( self ): __A : Optional[Any] = 'facebook/sam-vit-huge' __A : List[str] = pipeline('mask-generation' , model=_A ) __A : Tuple = image_segmenter( 'http://images.cocodataset.org/val2017/000000039769.jpg' , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __A : List[str] = [] for i, o in enumerate(outputs['masks'] ): new_outupt += [{"mask": mask_to_test_readable(_A ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_A , decimals=4 ) , [ {'mask': {'hash': '115ad19f5f', 'shape': (480, 640)}, 'scores': 1.0_4_4_4}, {'mask': {'hash': '6affa964c6', 'shape': (480, 640)}, 'scores': 1.0_2_1_0}, {'mask': {'hash': 'dfe28a0388', 'shape': (480, 640)}, 'scores': 1.0_1_6_7}, {'mask': {'hash': 'c0a5f4a318', 'shape': (480, 640)}, 'scores': 1.0_1_3_2}, {'mask': {'hash': 'fe8065c197', 'shape': (480, 640)}, 'scores': 1.0_0_5_3}, ] , )
280
0
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig lowercase__ = logging.get_logger(__name__) class __snake_case : def __init__( self , lowercase , lowercase) -> Tuple: '''simple docstring''' a__: Optional[int] = question_encoder a__: Dict = generator a__: Optional[Any] = self.question_encoder def lowerCamelCase_ ( self , lowercase) -> Union[str, Any]: '''simple docstring''' if os.path.isfile(_A): raise ValueError(f'Provided path ({save_directory}) should be a directory, not a file') os.makedirs(_A , exist_ok=_A) a__: str = os.path.join(_A , 'question_encoder_tokenizer') a__: List[str] = os.path.join(_A , 'generator_tokenizer') self.question_encoder.save_pretrained(_A) self.generator.save_pretrained(_A) @classmethod def lowerCamelCase_ ( cls , lowercase , **lowercase) -> List[Any]: '''simple docstring''' from ..auto.tokenization_auto import AutoTokenizer a__: Optional[int] = kwargs.pop('config' , _A) if config is None: a__: int = RagConfig.from_pretrained(_A) a__: str = AutoTokenizer.from_pretrained( _A , config=config.question_encoder , subfolder='question_encoder_tokenizer') a__: Optional[Any] = AutoTokenizer.from_pretrained( _A , config=config.generator , subfolder='generator_tokenizer') return cls(question_encoder=_A , generator=_A) def __call__( self , *lowercase , **lowercase) -> Tuple: '''simple docstring''' return self.current_tokenizer(*_A , **_A) def lowerCamelCase_ ( self , *lowercase , **lowercase) -> Any: '''simple docstring''' return self.generator.batch_decode(*_A , **_A) def lowerCamelCase_ ( self , *lowercase , **lowercase) -> Union[str, Any]: '''simple docstring''' return self.generator.decode(*_A , **_A) def lowerCamelCase_ ( self) -> Optional[Any]: '''simple docstring''' a__: Tuple = self.question_encoder def lowerCamelCase_ ( self) -> str: '''simple docstring''' a__: str = self.generator def lowerCamelCase_ ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = "longest" , lowercase = None , lowercase = True , **lowercase , ) -> List[str]: '''simple docstring''' warnings.warn( '`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ' 'regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ' 'context manager to prepare your targets. See the documentation of your specific tokenizer for more ' 'details' , _A , ) if max_length is None: a__: str = self.current_tokenizer.model_max_length a__: List[str] = self( _A , add_special_tokens=_A , return_tensors=_A , max_length=_A , padding=_A , truncation=_A , **_A , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: a__: Optional[int] = self.current_tokenizer.model_max_length a__: Any = self( text_target=_A , add_special_tokens=_A , return_tensors=_A , padding=_A , max_length=_A , truncation=_A , **_A , ) a__: Union[str, Any] = labels['input_ids'] return model_inputs
290
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 OwlViTImageProcessor, OwlViTProcessor @require_vision class _A( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[Any] = tempfile.mkdtemp() # fmt: off __A : 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 __A : Union[str, Any] = dict(zip(_A , range(len(_A ) ) ) ) __A : Optional[int] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] __A : int = {'unk_token': '<unk>'} __A : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __A : int = 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(_A ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_A ) ) __A : List[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3], 'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1], } __A : Optional[int] = os.path.join(self.tmpdirname , _A ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_A , _A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A ) def UpperCAmelCase_ ( self , **_A ): return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A ) def UpperCAmelCase_ ( self ): shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self ): __A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self ): __A : List[Any] = self.get_tokenizer() __A : str = self.get_rust_tokenizer() __A : List[str] = self.get_image_processor() __A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_slow.save_pretrained(self.tmpdirname ) __A : int = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A ) __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) processor_fast.save_pretrained(self.tmpdirname ) __A : Optional[Any] = OwlViTProcessor.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 , _A ) self.assertIsInstance(processor_fast.tokenizer , _A ) 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 , _A ) self.assertIsInstance(processor_fast.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : List[str] = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __A : Optional[int] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) __A : Optional[int] = self.get_image_processor(do_normalize=_A ) __A : Any = OwlViTProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Optional[Any] = self.get_tokenizer() __A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Union[str, Any] = self.prepare_image_inputs() __A : int = image_processor(_A , return_tensors='np' ) __A : str = processor(images=_A , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase_ ( self ): __A : str = self.get_image_processor() __A : str = self.get_tokenizer() __A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : str = 'lower newer' __A : str = processor(text=_A , return_tensors='np' ) __A : List[str] = tokenizer(_A , return_tensors='np' ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() ) def UpperCAmelCase_ ( self ): __A : int = self.get_image_processor() __A : Optional[int] = self.get_tokenizer() __A : List[str] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Any = 'lower newer' __A : Optional[Any] = self.prepare_image_inputs() __A : List[Any] = processor(text=_A , images=_A ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Any = 'google/owlvit-base-patch32' __A : int = OwlViTProcessor.from_pretrained(_A ) __A : Dict = ['cat', 'nasa badge'] __A : Optional[Any] = processor(text=_A ) __A : Optional[int] = 16 self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Tuple = 'google/owlvit-base-patch32' __A : Any = OwlViTProcessor.from_pretrained(_A ) __A : Dict = [['cat', 'nasa badge'], ['person']] __A : Dict = processor(text=_A ) __A : Optional[int] = 16 __A : Any = len(_A ) __A : Union[str, Any] = max([len(_A ) for texts in input_texts] ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : List[Any] = 'google/owlvit-base-patch32' __A : str = OwlViTProcessor.from_pretrained(_A ) __A : Union[str, Any] = ['cat', 'nasa badge'] __A : Tuple = processor(text=_A ) __A : str = 16 __A : int = inputs['input_ids'] __A : List[Any] = [ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] ) self.assertEqual(inputs['input_ids'].shape , (2, seq_length) ) self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] ) self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : List[str] = self.get_tokenizer() __A : Optional[Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = self.prepare_image_inputs() __A : Optional[int] = processor(images=_A , query_images=_A ) self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.get_image_processor() __A : Union[str, Any] = self.get_tokenizer() __A : str = OwlViTProcessor(tokenizer=_A , image_processor=_A ) __A : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __A : Any = processor.batch_decode(_A ) __A : Tuple = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A )
280
0
def A ( _SCREAMING_SNAKE_CASE ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("The given input must be positive" ) # get the generated string sequence lowerCamelCase : int = gray_code_sequence_string(_SCREAMING_SNAKE_CASE ) # # convert them to integers for i in range(len(_SCREAMING_SNAKE_CASE ) ): lowerCamelCase : Any = int(sequence[i] ,2 ) return sequence def A ( _SCREAMING_SNAKE_CASE ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] lowerCamelCase : Tuple = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits lowerCamelCase : str = gray_code_sequence_string(bit_count - 1 ) lowerCamelCase : Tuple = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): lowerCamelCase : int = '0' + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): lowerCamelCase : List[Any] = '1' + smaller_sequence[i] sequence.append(_SCREAMING_SNAKE_CASE ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
48
import math def _SCREAMING_SNAKE_CASE ( a ) -> list[int]: __A : List[str] = [] __A : Any = 2 __A : Union[str, Any] = int(math.sqrt(a ) ) # Size of every segment __A : Any = [True] * (end + 1) __A : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(a ) for i in range(start * start , end + 1 , a ): __A : Optional[int] = False start += 1 prime += in_prime __A : Any = end + 1 __A : Any = min(2 * end , a ) while low <= n: __A : List[Any] = [True] * (high - low + 1) for each in in_prime: __A : List[str] = math.floor(low / each ) * each if t < low: t += each for j in range(a , high + 1 , a ): __A : Optional[int] = False for j in range(len(a ) ): if temp[j] is True: prime.append(j + low ) __A : Optional[int] = high + 1 __A : Tuple = min(high + end , a ) return prime print(sieve(10**6))
280
0
import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() lowercase = logging.get_logger(__name__) set_seed(770) lowercase = { '''c_attn''': '''att_proj''', '''c_proj''': '''out_proj''', '''c_fc''': '''in_proj''', '''transformer.''': '''''', '''h.''': '''layers.''', '''ln_1''': '''layernorm_1''', '''ln_2''': '''layernorm_2''', '''ln_f''': '''layernorm_final''', '''wpe''': '''position_embeds_layer''', '''wte''': '''input_embeds_layer''', } lowercase = { '''text_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text.pt''', }, '''coarse_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse.pt''', }, '''fine_small''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine.pt''', }, '''text''': { '''repo_id''': '''suno/bark''', '''file_name''': '''text_2.pt''', }, '''coarse''': { '''repo_id''': '''suno/bark''', '''file_name''': '''coarse_2.pt''', }, '''fine''': { '''repo_id''': '''suno/bark''', '''file_name''': '''fine_2.pt''', }, } lowercase = os.path.dirname(os.path.abspath(__file__)) lowercase = os.path.join(os.path.expanduser("~"), ".cache") lowercase = os.path.join(os.getenv("XDG_CACHE_HOME", default_cache_dir), "suno", "bark_v0") def __UpperCAmelCase ( a_ , a_=False): snake_case_ = model_type if use_small: key += "_small" return os.path.join(a_ , REMOTE_MODEL_PATHS[key]['file_name']) def __UpperCAmelCase ( a_ , a_): os.makedirs(a_ , exist_ok=a_) hf_hub_download(repo_id=a_ , filename=a_ , local_dir=a_) def __UpperCAmelCase ( a_ , a_ , a_=False , a_="text"): if model_type == "text": snake_case_ = BarkSemanticModel snake_case_ = BarkSemanticConfig snake_case_ = BarkSemanticGenerationConfig elif model_type == "coarse": snake_case_ = BarkCoarseModel snake_case_ = BarkCoarseConfig snake_case_ = BarkCoarseGenerationConfig elif model_type == "fine": snake_case_ = BarkFineModel snake_case_ = BarkFineConfig snake_case_ = BarkFineGenerationConfig else: raise NotImplementedError() snake_case_ = f'''{model_type}_small''' if use_small else model_type snake_case_ = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a_): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''') _download(model_info['repo_id'] , model_info['file_name']) snake_case_ = torch.load(a_ , map_location=a_) # this is a hack snake_case_ = checkpoint['model_args'] if "input_vocab_size" not in model_args: snake_case_ = model_args['vocab_size'] snake_case_ = model_args['vocab_size'] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments snake_case_ = model_args.pop('n_head') snake_case_ = model_args.pop('n_embd') snake_case_ = model_args.pop('n_layer') snake_case_ = ConfigClass(**checkpoint['model_args']) snake_case_ = ModelClass(config=a_) snake_case_ = GenerationConfigClass() snake_case_ = model_generation_config snake_case_ = checkpoint['model'] # fixup checkpoint snake_case_ = '_orig_mod.' for k, v in list(state_dict.items()): if k.startswith(a_): # replace part of the key with corresponding layer name in HF implementation snake_case_ = k[len(a_) :] for old_layer_name in new_layer_name_dict: snake_case_ = new_k.replace(a_ , new_layer_name_dict[old_layer_name]) snake_case_ = state_dict.pop(a_) snake_case_ = set(state_dict.keys()) - set(model.state_dict().keys()) snake_case_ = {k for k in extra_keys if not k.endswith('.attn.bias')} snake_case_ = set(model.state_dict().keys()) - set(state_dict.keys()) snake_case_ = {k for k in missing_keys if not k.endswith('.attn.bias')} if len(a_) != 0: raise ValueError(f'''extra keys found: {extra_keys}''') if len(a_) != 0: raise ValueError(f'''missing keys: {missing_keys}''') model.load_state_dict(a_ , strict=a_) snake_case_ = model.num_parameters(exclude_embeddings=a_) snake_case_ = checkpoint['best_val_loss'].item() logger.info(f'''model loaded: {round(n_params/1E6 , 1)}M params, {round(a_ , 3)} loss''') model.eval() model.to(a_) del checkpoint, state_dict return model def __UpperCAmelCase ( a_ , a_=False , a_="text"): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() snake_case_ = 'cpu' # do conversion on cpu snake_case_ = _get_ckpt_path(a_ , use_small=a_) snake_case_ = _load_model(a_ , a_ , model_type=a_ , use_small=a_) # load bark initial model snake_case_ = _bark_load_model(a_ , 'cpu' , model_type=a_ , use_small=a_) if model_type == "text": snake_case_ = bark_model['model'] if model.num_parameters(exclude_embeddings=a_) != bark_model.get_num_params(): raise ValueError('initial and new models don\'t have the same number of parameters') # check if same output as the bark model snake_case_ = 5 snake_case_ = 10 if model_type in ["text", "coarse"]: snake_case_ = torch.randint(2_56 , (batch_size, sequence_length) , dtype=torch.int) snake_case_ = bark_model(a_)[0] snake_case_ = model(a_) # take last logits snake_case_ = output_new_model_total.logits[:, [-1], :] else: snake_case_ = 3 snake_case_ = 8 snake_case_ = torch.randint(2_56 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int) snake_case_ = model(a_ , a_) snake_case_ = bark_model(a_ , a_) snake_case_ = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError('initial and new outputs don\'t have the same shape') if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError('initial and new outputs are not equal') Path(a_).mkdir(exist_ok=a_) model.save_pretrained(a_) def __UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ , ): snake_case_ = os.path.join(a_ , a_) snake_case_ = BarkSemanticConfig.from_pretrained(os.path.join(a_ , 'config.json')) snake_case_ = BarkCoarseConfig.from_pretrained(os.path.join(a_ , 'config.json')) snake_case_ = BarkFineConfig.from_pretrained(os.path.join(a_ , 'config.json')) snake_case_ = EncodecConfig.from_pretrained('facebook/encodec_24khz') snake_case_ = BarkSemanticModel.from_pretrained(a_) snake_case_ = BarkCoarseModel.from_pretrained(a_) snake_case_ = BarkFineModel.from_pretrained(a_) snake_case_ = EncodecModel.from_pretrained('facebook/encodec_24khz') snake_case_ = BarkConfig.from_sub_model_configs( a_ , a_ , a_ , a_) snake_case_ = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config) snake_case_ = BarkModel(a_) snake_case_ = semantic snake_case_ = coarseAcoustic snake_case_ = fineAcoustic snake_case_ = codec snake_case_ = bark_generation_config Path(a_).mkdir(exist_ok=a_) bark.save_pretrained(a_ , repo_id=a_ , push_to_hub=a_) if __name__ == "__main__": lowercase = argparse.ArgumentParser() # Required parameters parser.add_argument("model_type", type=str, help="text, coarse or fine.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--is_small", action="store_true", help="convert the small version instead of the large.") lowercase = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
178
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available UpperCAmelCase : Any = { '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''], '''tokenization_mvp''': ['''MvpTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : int = ['''MvpTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : str = [ '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MvpForCausalLM''', '''MvpForConditionalGeneration''', '''MvpForQuestionAnswering''', '''MvpForSequenceClassification''', '''MvpModel''', '''MvpPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig from .tokenization_mvp import MvpTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mvp_fast import MvpTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mvp import ( MVP_PRETRAINED_MODEL_ARCHIVE_LIST, MvpForCausalLM, MvpForConditionalGeneration, MvpForQuestionAnswering, MvpForSequenceClassification, MvpModel, MvpPreTrainedModel, ) else: import sys UpperCAmelCase : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
'''simple docstring''' from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _UpperCAmelCase ( _lowerCamelCase : Tuple , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[int] = False ) -> list[float]: if radian_mode: return [magnitude * cos(_lowerCamelCase ), magnitude * sin(_lowerCamelCase )] return [magnitude * cos(radians(_lowerCamelCase ) ), magnitude * sin(radians(_lowerCamelCase ) )] def _UpperCAmelCase ( _lowerCamelCase : int , _lowerCamelCase : Dict , _lowerCamelCase : Union[str, Any] = 10**-1 ) -> bool: _lowerCAmelCase : NDArray[floataa] = cross(_lowerCamelCase , _lowerCamelCase ) _lowerCAmelCase : float = sum(_lowerCamelCase ) return abs(_lowerCamelCase ) < eps if __name__ == "__main__": # Test to check if it works UpperCamelCase_ = array( [ polar_force(7_1_8.4, 1_80 - 30), polar_force(8_7_9.5_4, 45), polar_force(1_00, -90), ] ) UpperCamelCase_ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg UpperCamelCase_ = array( [ polar_force(30 * 9.8_1, 15), polar_force(2_15, 1_80 - 45), polar_force(2_64, 90 - 30), ] ) UpperCamelCase_ = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg UpperCamelCase_ = array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]]) UpperCamelCase_ = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
309
def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: __A , __A : Optional[Any] = [], [] while len(a ) > 1: __A , __A : Any = min(a ), max(a ) start.append(a ) end.append(a ) collection.remove(a ) collection.remove(a ) end.reverse() return start + collection + end if __name__ == "__main__": UpperCAmelCase : int = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase : Dict = [int(item) for item in user_input.split(''',''')] print(*merge_sort(unsorted), sep=''',''')
280
0
from __future__ import annotations def a ( A__ : Tuple ) -> int: """simple docstring""" if not nums: return 0 _lowercase =nums[0] _lowercase =0 for num in nums[1:]: _lowercase =( max_excluding + num, max(A__ , A__ ), ) return max(A__ , A__ ) if __name__ == "__main__": import doctest doctest.testmod()
205
def _SCREAMING_SNAKE_CASE ( a , a = 0 ) -> list: __A : int = length or len(a ) __A : str = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: __A , __A : Optional[int] = list_data[i + 1], list_data[i] __A : Union[str, Any] = True return list_data if not swapped else bubble_sort(a , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
'''simple docstring''' import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels UpperCAmelCase_ = object() # For specifying empty leaf dict `{}` UpperCAmelCase_ = object() def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' UpperCAmelCase__ = tuple((re.compile(x + """$""" ) for x in qs) ) for i in range(len(SCREAMING_SNAKE_CASE__ ) - len(SCREAMING_SNAKE_CASE__ ) + 1 ): UpperCAmelCase__ = [x.match(SCREAMING_SNAKE_CASE__ ) for x, y in zip(SCREAMING_SNAKE_CASE__ , ks[i:] )] if matches and all(SCREAMING_SNAKE_CASE__ ): return True return False def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] ): '''simple docstring''' def replace(SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] ): for rule, replacement in rules: if _match(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return replacement return val return replace def _UpperCamelCase ( ): '''simple docstring''' return [ # embeddings (("transformer", "wpe", "embedding"), P("""mp""" , SCREAMING_SNAKE_CASE__ )), (("transformer", "wte", "embedding"), P("""mp""" , SCREAMING_SNAKE_CASE__ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(SCREAMING_SNAKE_CASE__ , """mp""" )), (("attention", "out_proj", "kernel"), P("""mp""" , SCREAMING_SNAKE_CASE__ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(SCREAMING_SNAKE_CASE__ , """mp""" )), (("mlp", "c_fc", "bias"), P("""mp""" )), (("mlp", "c_proj", "kernel"), P("""mp""" , SCREAMING_SNAKE_CASE__ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : Dict ): '''simple docstring''' UpperCAmelCase__ = _get_partition_rules() UpperCAmelCase__ = _replacement_rules(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = {k: _unmatched for k in flatten_dict(SCREAMING_SNAKE_CASE__ )} UpperCAmelCase__ = {k: replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(SCREAMING_SNAKE_CASE__ ) )
346
from __future__ import annotations def _SCREAMING_SNAKE_CASE ( a ) -> int: if not nums: return 0 __A : Optional[int] = nums[0] __A : str = 0 for num in nums[1:]: __A , __A : Tuple = ( max_excluding + num, max(a , a ), ) return max(a , a ) if __name__ == "__main__": import doctest doctest.testmod()
280
0
"""simple docstring""" from typing import TYPE_CHECKING from ....utils import _LazyModule lowerCAmelCase__ : Optional[int] = {'''tokenization_tapex''': ['''TapexTokenizer''']} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys lowerCAmelCase__ : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure)
98
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase : Optional[int] = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Union[str, Any] = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase : Optional[Any] = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys UpperCAmelCase : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
280
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : Dict = logging.get_logger(__name__) _lowerCAmelCase : List[Any] = { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/config.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/config.json''' # See all FNet models at https://huggingface.co/models?filter=fnet } class __magic_name__ ( snake_case__ ): """simple docstring""" __UpperCamelCase = '''fnet''' def __init__( self :Any , snake_case :Optional[int]=32_000 , snake_case :Union[str, Any]=768 , snake_case :List[str]=12 , snake_case :Dict=3_072 , snake_case :List[str]="gelu_new" , snake_case :int=0.1 , snake_case :str=512 , snake_case :List[Any]=4 , snake_case :Dict=0.02 , snake_case :str=1e-12 , snake_case :Optional[Any]=False , snake_case :Optional[int]=512 , snake_case :Union[str, Any]=3 , snake_case :List[Any]=1 , snake_case :Dict=2 , **snake_case :List[str] , ): '''simple docstring''' super().__init__(pad_token_id=_A , bos_token_id=_A , eos_token_id=_A , **_A ) A_ : Dict = vocab_size A_ : Optional[Any] = max_position_embeddings A_ : Dict = hidden_size A_ : Any = num_hidden_layers A_ : Optional[int] = intermediate_size A_ : Optional[int] = hidden_act A_ : List[Any] = hidden_dropout_prob A_ : Optional[Any] = initializer_range A_ : Optional[int] = type_vocab_size A_ : Tuple = layer_norm_eps A_ : Tuple = use_tpu_fourier_optimizations A_ : str = tpu_short_seq_length
300
def _SCREAMING_SNAKE_CASE ( a ) -> str: if number > 0: raise ValueError('input must be a negative integer' ) __A : Optional[int] = len(bin(a )[3:] ) __A : Dict = bin(abs(a ) - (1 << binary_number_length) )[3:] __A : int = ( ( '1' + '0' * (binary_number_length - len(a )) + twos_complement_number ) if number < 0 else '0' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
280
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Any ) ->int: while a != 0: _SCREAMING_SNAKE_CASE = b % a, a return b def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : Dict ) ->int: if gcd(__lowerCamelCase , __lowerCamelCase ) != 1: _SCREAMING_SNAKE_CASE = F'mod inverse of {a!r} and {m!r} does not exist' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = 1, 0, a _SCREAMING_SNAKE_CASE = 0, 1, m while va != 0: _SCREAMING_SNAKE_CASE = ua // va _SCREAMING_SNAKE_CASE = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
58
import warnings from pathlib import Path from typing import List, Tuple, Union import fire from torch import nn from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel from transformers.utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE ( a , a , a ) -> None: __A : int = nn.ModuleList([src_layers[i] for i in layers_to_copy] ) assert len(a ) == len(a ), F"""{len(a )} != {len(a )}""" dest_layers.load_state_dict(layers_to_copy.state_dict() ) UpperCAmelCase : List[Any] = { # maps num layers in teacher -> num_layers in student -> which teacher layers to copy. # 12: bart, 16: pegasus, 6: marian/Helsinki-NLP 12: { 1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher 2: [0, 6], 3: [0, 6, 11], 4: [0, 4, 8, 11], 6: [0, 2, 4, 7, 9, 11], 9: [0, 1, 2, 4, 5, 7, 9, 10, 11], 12: list(range(12)), }, 16: { # maps num layers in student -> which teacher layers to copy 1: [0], 2: [0, 15], 3: [0, 8, 15], 4: [0, 5, 10, 15], 6: [0, 3, 6, 9, 12, 15], 8: [0, 2, 4, 6, 8, 10, 12, 15], 9: [0, 1, 3, 5, 7, 9, 11, 13, 15], 12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15], 16: list(range(16)), }, 6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))}, } UpperCAmelCase : Optional[int] = { # maps num layers in student -> which teacher layers to copy. 6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]}, 12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]}, 16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]}, } def _SCREAMING_SNAKE_CASE ( a , a ) -> Dict: try: __A : int = LAYERS_TO_COPY[n_teacher][n_student] return val except KeyError: if n_student != n_teacher: warnings.warn( F"""no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first""" F""" {n_student}""" ) return list(range(a ) ) def _SCREAMING_SNAKE_CASE ( a , a ) -> List[int]: if n_student > n_teacher: raise ValueError(F"""Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}""" ) elif n_teacher == n_student: return list(range(a ) ) elif n_student == 1: return [n_teacher - 1] else: return LAYERS_TO_SUPERVISE[n_teacher][n_student] def _SCREAMING_SNAKE_CASE ( a , a = "student" , a = None , a = None , a=False , a=None , a=None , **a , ) -> Tuple[PreTrainedModel, List[int], List[int]]: __A : List[str] = 'encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher.' assert (e is not None) or (d is not None), _msg if isinstance(a , a ): AutoTokenizer.from_pretrained(a ).save_pretrained(a ) # purely for convenience __A : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(a ).eval() else: assert isinstance(a , a ), F"""teacher must be a model or string got type {type(a )}""" __A : int = teacher.config.to_diff_dict() try: __A , __A : List[Any] = teacher.config.encoder_layers, teacher.config.decoder_layers if e is None: __A : str = teacher_e if d is None: __A : List[Any] = teacher_d init_kwargs.update({'encoder_layers': e, 'decoder_layers': d} ) except AttributeError: # T5 if hasattr(teacher.config , 'num_encoder_layers' ): __A , __A : List[Any] = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers else: __A , __A : Optional[int] = teacher.config.num_layers, teacher.config.num_decoder_layers if e is None: __A : int = teacher_e if d is None: __A : Optional[Any] = teacher_d if hasattr(teacher.config , 'num_encoder_layers' ): init_kwargs.update({'num_encoder_layers': e, 'num_decoder_layers': d} ) else: init_kwargs.update({'num_layers': e, 'num_decoder_layers': d} ) # Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs init_kwargs.update(a ) # Copy weights __A : Dict = teacher.config_class(**a ) __A : int = AutoModelForSeqaSeqLM.from_config(a ) # Start by copying the full teacher state dict this will copy the first N teacher layers to the student. __A : Any = student.load_state_dict(teacher.state_dict() , strict=a ) assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys. if copy_first_teacher_layers: # Our copying is done. We just log and save __A , __A : Optional[int] = list(range(a ) ), list(range(a ) ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to""" F""" {save_path}""" ) student.save_pretrained(a ) return student, e_layers_to_copy, d_layers_to_copy # Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer. if e_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) if d_layers_to_copy is None: __A : List[int] = pick_layers_to_copy(a , a ) try: if hasattr( a , 'prophetnet' ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers copy_layers(teacher.prophetnet.encoder.layers , student.prophetnet.encoder.layers , a ) copy_layers(teacher.prophetnet.decoder.layers , student.prophetnet.decoder.layers , a ) else: copy_layers(teacher.model.encoder.layers , student.model.encoder.layers , a ) copy_layers(teacher.model.decoder.layers , student.model.decoder.layers , a ) except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block copy_layers(teacher.encoder.block , student.encoder.block , a ) copy_layers(teacher.decoder.block , student.decoder.block , a ) logger.info( F"""Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}""" ) __A : Optional[int] = { 'teacher_type': teacher.config.model_type, 'copied_encoder_layers': e_layers_to_copy, 'copied_decoder_layers': d_layers_to_copy, } student.save_pretrained(a ) # Save information about copying for easier reproducibility return student, e_layers_to_copy, d_layers_to_copy if __name__ == "__main__": fire.Fire(create_student_by_copying_alternating_layers)
280
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { '''microsoft/swinv2-tiny-patch4-window8-256''': ( '''https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json''' ), } class _UpperCamelCase ( snake_case__ ): '''simple docstring''' lowerCamelCase__ ='''swinv2''' lowerCamelCase__ ={ '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : Optional[int] , a : List[str]=224 , a : Tuple=4 , a : Tuple=3 , a : Union[str, Any]=96 , a : Any=[2, 2, 6, 2] , a : Union[str, Any]=[3, 6, 12, 24] , a : str=7 , a : List[str]=4.0 , a : List[Any]=True , a : Optional[Any]=0.0 , a : Any=0.0 , a : Optional[int]=0.1 , a : Tuple="gelu" , a : Optional[Any]=False , a : int=0.02 , a : Dict=1e-5 , a : List[Any]=32 , **a : Optional[Any] , ) -> List[Any]: """simple docstring""" super().__init__(**_A ) SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : Dict = patch_size SCREAMING_SNAKE_CASE : List[Any] = num_channels SCREAMING_SNAKE_CASE : List[str] = embed_dim SCREAMING_SNAKE_CASE : Tuple = depths SCREAMING_SNAKE_CASE : List[Any] = len(_A ) SCREAMING_SNAKE_CASE : Union[str, Any] = num_heads SCREAMING_SNAKE_CASE : Union[str, Any] = window_size SCREAMING_SNAKE_CASE : Optional[int] = mlp_ratio SCREAMING_SNAKE_CASE : str = qkv_bias SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE : Union[str, Any] = layer_norm_eps SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Tuple = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE : Optional[int] = int(embed_dim * 2 ** (len(_A ) - 1) ) SCREAMING_SNAKE_CASE : List[Any] = (0, 0, 0, 0)
76
def _SCREAMING_SNAKE_CASE ( a , a ) -> list[int]: __A : Optional[int] = int(a ) # Initialize Result __A : Optional[int] = [] # Traverse through all denomination for denomination in reversed(a ): # Find denominations while int(a ) >= int(a ): total_value -= int(a ) answer.append(a ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase : List[str] = [] UpperCAmelCase : Optional[int] = '''0''' if ( input('''Do you want to enter your denominations ? (yY/n): ''').strip().lower() == "y" ): UpperCAmelCase : List[Any] = int(input('''Enter the number of denominations you want to add: ''').strip()) for i in range(0, n): denominations.append(int(input(F"""Denomination {i}: """).strip())) UpperCAmelCase : int = input('''Enter the change you want to make in Indian Currency: ''').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase : Optional[int] = [1, 2, 5, 10, 20, 50, 1_00, 5_00, 20_00] UpperCAmelCase : Tuple = input('''Enter the change you want to make: ''').strip() if int(value) == 0 or int(value) < 0: print('''The total value cannot be zero or negative.''') else: print(F"""Following is minimal change for {value}: """) UpperCAmelCase : Optional[int] = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=''' ''')
280
0
from __future__ import annotations from math import ceil, floor, sqrt def lowerCAmelCase_ ( __A = 2_000_000 ) -> int: '''simple docstring''' UpperCAmelCase__ = [0] UpperCAmelCase__ = 42 for idx in range(1, ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target UpperCAmelCase__ = 0 # the area corresponding to the grid that gives the product closest to target UpperCAmelCase__ = 0 # an estimate of b, using the quadratic formula UpperCAmelCase__ = 42 # the largest integer less than b_estimate UpperCAmelCase__ = 42 # the largest integer less than b_estimate UpperCAmelCase__ = 42 # the triangle number corresponding to b_floor UpperCAmelCase__ = 42 # the triangle number corresponding to b_ceil UpperCAmelCase__ = 42 for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1 ): UpperCAmelCase__ = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 UpperCAmelCase__ = floor(__A ) UpperCAmelCase__ = ceil(__A ) UpperCAmelCase__ = triangle_numbers[b_floor] UpperCAmelCase__ = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): UpperCAmelCase__ = triangle_b_first_guess * triangle_a UpperCAmelCase__ = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): UpperCAmelCase__ = triangle_b_second_guess * triangle_a UpperCAmelCase__ = idx_a * b_ceil return area if __name__ == "__main__": print(f'''{solution() = }''')
65
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class _A( unittest.TestCase ): """simple docstring""" def __init__( self , _A , _A=7 , _A=3 , _A=30 , _A=400 , _A=True , _A=None , _A=True , _A=[0.5, 0.5, 0.5] , _A=[0.5, 0.5, 0.5] , _A=True , _A=1 / 255 , _A=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __A : List[Any] = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} __A : Union[str, Any] = parent __A : Optional[int] = batch_size __A : int = num_channels __A : int = min_resolution __A : Any = max_resolution __A : List[Any] = do_resize __A : List[Any] = size __A : Union[str, Any] = do_normalize __A : Optional[int] = image_mean __A : Optional[int] = image_std __A : int = do_rescale __A : str = rescale_factor __A : Tuple = do_pad def UpperCAmelCase_ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase_ ( self , _A , _A=False ): if not batched: __A : List[str] = image_inputs[0] if isinstance(_A , Image.Image ): __A , __A : int = image.size else: __A , __A : Any = image.shape[1], image.shape[2] if w < h: __A : List[Any] = int(self.size['shortest_edge'] * h / w ) __A : List[Any] = self.size['shortest_edge'] elif w > h: __A : Union[str, Any] = self.size['shortest_edge'] __A : str = int(self.size['shortest_edge'] * w / h ) else: __A : Dict = self.size['shortest_edge'] __A : str = self.size['shortest_edge'] else: __A : int = [] for image in image_inputs: __A , __A : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __A : List[str] = max(_A , key=lambda _A : item[0] )[0] __A : str = max(_A , key=lambda _A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : List[str] = YolosImageProcessor if is_vision_available() else None def UpperCAmelCase_ ( self ): __A : Dict = YolosImageProcessingTester(self ) @property def UpperCAmelCase_ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self ): __A : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , 'image_mean' ) ) self.assertTrue(hasattr(_A , 'image_std' ) ) self.assertTrue(hasattr(_A , 'do_normalize' ) ) self.assertTrue(hasattr(_A , 'do_resize' ) ) self.assertTrue(hasattr(_A , 'size' ) ) def UpperCAmelCase_ ( self ): __A : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _A ) __A : Dict = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_A ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _A ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): # Initialize image_processing __A : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A ) for image in image_inputs: self.assertIsInstance(_A , Image.Image ) # Test not batched input __A : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A , __A : Optional[Any] = self.image_processor_tester.get_expected_values(_A , batched=_A ) __A : str = image_processing(_A , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __A : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input __A : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : List[Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Tuple = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processing __A : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __A : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test not batched input __A : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values __A , __A : Union[str, Any] = self.image_processor_tester.get_expected_values(_A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __A : Optional[int] = image_processing(_A , return_tensors='pt' ).pixel_values __A , __A : Optional[int] = self.image_processor_tester.get_expected_values(_A , batched=_A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCAmelCase_ ( self ): # Initialize image_processings __A : Tuple = self.image_processing_class(**self.image_processor_dict ) __A : Any = self.image_processing_class(do_resize=_A , do_normalize=_A , do_rescale=_A ) # create random PyTorch tensors __A : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __A : Optional[int] = image_processing_a.pad(_A , return_tensors='pt' ) __A : Optional[int] = image_processing_a(_A , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): # prepare image and target __A : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: __A : Optional[Any] = json.loads(f.read() ) __A : Optional[Any] = {'image_id': 39769, 'annotations': target} # encode them __A : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) __A : List[Any] = image_processing(images=_A , annotations=_A , return_tensors='pt' ) # verify pixel values __A : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = 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] , _A , atol=1e-4 ) ) # verify area __A : List[Any] = 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'] , _A ) ) # verify boxes __A : Any = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = 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] , _A , atol=1e-3 ) ) # verify image_id __A : Optional[int] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : Any = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify orig_size __A : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) ) @slow def UpperCAmelCase_ ( self ): # prepare image, target and masks_path __A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: __A : Tuple = json.loads(f.read() ) __A : Any = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} __A : List[Any] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them __A : Any = YolosImageProcessor(format='coco_panoptic' ) __A : List[Any] = image_processing(images=_A , annotations=_A , masks_path=_A , return_tensors='pt' ) # verify pixel values __A : Any = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _A ) __A : Union[str, Any] = 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] , _A , atol=1e-4 ) ) # verify area __A : int = 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'] , _A ) ) # verify boxes __A : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _A ) __A : Optional[Any] = 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] , _A , atol=1e-3 ) ) # verify image_id __A : Union[str, Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _A ) ) # verify is_crowd __A : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _A ) ) # verify class_labels __A : List[str] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _A ) ) # verify masks __A : Tuple = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _A ) # verify orig_size __A : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _A ) ) # verify size __A : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _A ) )
280
0
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 snake_case : Tuple = get_tests_dir("fixtures") class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): # A mock response for an HTTP head request to emulate server down __magic_name__ : Union[str, Any] = mock.Mock() __magic_name__ : str = 500 __magic_name__ : str = {} __magic_name__ : Dict = HTTPError __magic_name__ : Dict = {} # Download this model to make sure it's in the cache. __magic_name__ : List[Any] = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=_a ) as mock_head: __magic_name__ : int = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # This check we did call the fake head request mock_head.assert_called() def SCREAMING_SNAKE_CASE ( self ): # This test is for deprecated behavior and can be removed in v5 __magic_name__ : str = ViTImageProcessor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json" ) def SCREAMING_SNAKE_CASE ( self ): with self.assertRaises(_a ): # config is in subfolder, the following should not work without specifying the subfolder __magic_name__ : Optional[Any] = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants" ) __magic_name__ : Optional[int] = AutoImageProcessor.from_pretrained( "hf-internal-testing/stable-diffusion-all-variants" , subfolder="feature_extractor" ) self.assertIsNotNone(_a ) @is_staging_test class _snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE ( cls ): __magic_name__ : str = TOKEN HfFolder.save_token(_a ) @classmethod def SCREAMING_SNAKE_CASE ( cls ): try: delete_repo(token=cls._token , repo_id="test-image-processor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-image-processor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-image-processor" ) except HTTPError: pass def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ViTImageProcessor.from_pretrained(_a ) image_processor.push_to_hub("test-image-processor" , use_auth_token=self._token ) __magic_name__ : int = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id="test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _a , repo_id="test-image-processor" , push_to_hub=_a , use_auth_token=self._token ) __magic_name__ : Optional[Any] = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = ViTImageProcessor.from_pretrained(_a ) image_processor.push_to_hub("valid_org/test-image-processor" , use_auth_token=self._token ) __magic_name__ : List[str] = ViTImageProcessor.from_pretrained("valid_org/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( _a , repo_id="valid_org/test-image-processor-org" , push_to_hub=_a , use_auth_token=self._token ) __magic_name__ : Union[str, Any] = ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org" ) for k, v in image_processor.__dict__.items(): self.assertEqual(_a , getattr(_a , _a ) ) def SCREAMING_SNAKE_CASE ( self ): CustomImageProcessor.register_for_auto_class() __magic_name__ : List[str] = CustomImageProcessor.from_pretrained(_a ) image_processor.push_to_hub("test-dynamic-image-processor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"} , ) __magic_name__ : List[str] = AutoImageProcessor.from_pretrained( f'''{USER}/test-dynamic-image-processor''' , trust_remote_code=_a ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , "CustomImageProcessor" )
281
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if isinstance(_snake_case , _snake_case ): __magic_name__ : Union[str, Any] = np.full((len(_snake_case ), sequence_length, 2) , _snake_case ) else: __magic_name__ : List[Any] = np.full((len(_snake_case ), sequence_length) , _snake_case ) for i, tensor in enumerate(_snake_case ): if padding_side == "right": if isinstance(_snake_case , _snake_case ): __magic_name__ : Optional[Any] = tensor[:sequence_length] else: __magic_name__ : Union[str, Any] = tensor[:sequence_length] else: if isinstance(_snake_case , _snake_case ): __magic_name__ : List[Any] = tensor[:sequence_length] else: __magic_name__ : Optional[Any] = tensor[:sequence_length] return out_tensor.tolist() def lowerCAmelCase_ ( _snake_case : Optional[int] ) -> Tuple: '''simple docstring''' __magic_name__ : Union[str, Any] = ord(_snake_case ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True __magic_name__ : Any = unicodedata.category(_snake_case ) if cat.startswith("P" ): return True return False @dataclass class _snake_case ( snake_case ): UpperCamelCase__ = 42 UpperCamelCase__ = True UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = -100 UpperCamelCase__ = "pt" def SCREAMING_SNAKE_CASE ( self , _a ): import torch __magic_name__ : List[str] = "label" if "label" in features[0].keys() else "labels" __magic_name__ : Union[str, Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __magic_name__ : Optional[int] = self.tokenizer.pad( _a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" if labels is None else None , ) if labels is None: return batch __magic_name__ : Dict = torch.tensor(batch["entity_ids"] ).shape[1] __magic_name__ : List[Any] = self.tokenizer.padding_side if padding_side == "right": __magic_name__ : str = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: __magic_name__ : int = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] __magic_name__ : Dict = [feature["ner_tags"] for feature in features] __magic_name__ : List[Any] = padding_tensor(_a , -1 , _a , _a ) __magic_name__ : Any = [feature["original_entity_spans"] for feature in features] __magic_name__ : Any = padding_tensor(_a , (-1, -1) , _a , _a ) __magic_name__ : List[Any] = {k: torch.tensor(_a , dtype=torch.intaa ) for k, v in batch.items()} return batch
281
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging snake_case : Optional[int] = logging.get_logger(__name__) if is_vision_available(): import PIL class _snake_case ( snake_case ): UpperCamelCase__ = ['pixel_values'] def __init__( self , _a = True , _a = None , _a = PILImageResampling.BICUBIC , _a = True , _a = None , _a = True , _a = 1 / 255 , _a = True , _a = None , _a = None , _a = True , **_a , ): super().__init__(**_a ) __magic_name__ : Tuple = size if size is not None else {"shortest_edge": 224} __magic_name__ : int = get_size_dict(_a , default_to_square=_a ) __magic_name__ : Dict = crop_size if crop_size is not None else {"height": 224, "width": 224} __magic_name__ : Tuple = get_size_dict(_a , default_to_square=_a , param_name="crop_size" ) __magic_name__ : Optional[Any] = do_resize __magic_name__ : str = size __magic_name__ : str = resample __magic_name__ : Tuple = do_center_crop __magic_name__ : Tuple = crop_size __magic_name__ : List[str] = do_rescale __magic_name__ : Any = rescale_factor __magic_name__ : Union[str, Any] = do_normalize __magic_name__ : Union[str, Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __magic_name__ : Optional[int] = image_std if image_std is not None else OPENAI_CLIP_STD __magic_name__ : Optional[Any] = do_convert_rgb def SCREAMING_SNAKE_CASE ( self , _a , _a , _a = PILImageResampling.BICUBIC , _a = None , **_a , ): __magic_name__ : List[Any] = get_size_dict(_a , default_to_square=_a ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) __magic_name__ : Dict = get_resize_output_image_size(_a , size=size["shortest_edge"] , default_to_square=_a ) return resize(_a , size=_a , resample=_a , data_format=_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a = None , **_a , ): __magic_name__ : Union[str, Any] = get_size_dict(_a ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(_a , size=(size["height"], size["width"]) , data_format=_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a = None , **_a , ): return rescale(_a , scale=_a , data_format=_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a = None , **_a , ): return normalize(_a , mean=_a , std=_a , data_format=_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = None , _a = ChannelDimension.FIRST , **_a , ): __magic_name__ : Dict = do_resize if do_resize is not None else self.do_resize __magic_name__ : str = size if size is not None else self.size __magic_name__ : Tuple = get_size_dict(_a , param_name="size" , default_to_square=_a ) __magic_name__ : Optional[Any] = resample if resample is not None else self.resample __magic_name__ : Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ : Optional[int] = crop_size if crop_size is not None else self.crop_size __magic_name__ : Dict = get_size_dict(_a , param_name="crop_size" , default_to_square=_a ) __magic_name__ : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ : List[Any] = image_mean if image_mean is not None else self.image_mean __magic_name__ : List[Any] = image_std if image_std is not None else self.image_std __magic_name__ : List[str] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __magic_name__ : List[Any] = make_list_of_images(_a ) if not valid_images(_a ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # PIL RGBA images are converted to RGB if do_convert_rgb: __magic_name__ : Optional[Any] = [convert_to_rgb(_a ) for image in images] # All transformations expect numpy arrays. __magic_name__ : Union[str, Any] = [to_numpy_array(_a ) for image in images] if do_resize: __magic_name__ : List[Any] = [self.resize(image=_a , size=_a , resample=_a ) for image in images] if do_center_crop: __magic_name__ : Tuple = [self.center_crop(image=_a , size=_a ) for image in images] if do_rescale: __magic_name__ : Union[str, Any] = [self.rescale(image=_a , scale=_a ) for image in images] if do_normalize: __magic_name__ : List[str] = [self.normalize(image=_a , mean=_a , std=_a ) for image in images] __magic_name__ : Dict = [to_channel_dimension_format(_a , _a ) for image in images] __magic_name__ : Any = {"pixel_values": images} return BatchFeature(data=_a , tensor_type=_a )
281
import math def lowerCAmelCase_ ( _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' return math.pow(_snake_case , 2 ) - a def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' return 2 * x def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' __magic_name__ : Optional[int] = 2.0 while start <= a: __magic_name__ : str = math.pow(_snake_case , 2 ) return start def lowerCAmelCase_ ( _snake_case : float , _snake_case : int = 9999 , _snake_case : float = 0.00_000_000_000_001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) __magic_name__ : Optional[int] = get_initial_point(_snake_case ) for _ in range(_snake_case ): __magic_name__ : int = value __magic_name__ : str = value - fx(_snake_case , _snake_case ) / fx_derivative(_snake_case ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
281
1
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run snake_case : str = True except (ImportError, AttributeError): snake_case : List[Any] = object def lowerCAmelCase_ ( *_snake_case : Optional[Any] , **_snake_case : Any ) -> Tuple: '''simple docstring''' pass snake_case : List[str] = False snake_case : List[str] = logging.get_logger("transformers-cli/serving") def lowerCAmelCase_ ( _snake_case : Namespace ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Tuple = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(_snake_case , args.host , args.port , args.workers ) class _snake_case ( snake_case ): UpperCamelCase__ = 42 class _snake_case ( snake_case ): UpperCamelCase__ = 42 UpperCamelCase__ = 42 class _snake_case ( snake_case ): UpperCamelCase__ = 42 class _snake_case ( snake_case ): UpperCamelCase__ = 42 class _snake_case ( snake_case ): @staticmethod def SCREAMING_SNAKE_CASE ( _a ): __magic_name__ : Tuple = parser.add_parser( "serve" , help="CLI tool to run inference requests through REST and GraphQL endpoints." ) serve_parser.add_argument( "--task" , type=_a , choices=get_supported_tasks() , help="The task to run the pipeline on" , ) serve_parser.add_argument("--host" , type=_a , default="localhost" , help="Interface the server will listen on." ) serve_parser.add_argument("--port" , type=_a , default=8_888 , help="Port the serving will listen to." ) serve_parser.add_argument("--workers" , type=_a , default=1 , help="Number of http workers" ) serve_parser.add_argument("--model" , type=_a , help="Model's name or path to stored model." ) serve_parser.add_argument("--config" , type=_a , help="Model's config name or path to stored model." ) serve_parser.add_argument("--tokenizer" , type=_a , help="Tokenizer name to use." ) serve_parser.add_argument( "--device" , type=_a , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) serve_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a ): __magic_name__ : Optional[Any] = pipeline __magic_name__ : List[str] = host __magic_name__ : str = port __magic_name__ : Any = workers if not _serve_dependencies_installed: raise RuntimeError( "Using serve command requires FastAPI and uvicorn. " "Please install transformers with [serving]: pip install \"transformers[serving]\"." "Or install FastAPI and uvicorn separately." ) else: logger.info(f'''Serving model over {host}:{port}''' ) __magic_name__ : int = FastAPI( routes=[ APIRoute( "/" , self.model_info , response_model=_a , response_class=_a , methods=["GET"] , ), APIRoute( "/tokenize" , self.tokenize , response_model=_a , response_class=_a , methods=["POST"] , ), APIRoute( "/detokenize" , self.detokenize , response_model=_a , response_class=_a , methods=["POST"] , ), APIRoute( "/forward" , self.forward , response_model=_a , response_class=_a , methods=["POST"] , ), ] , timeout=600 , ) def SCREAMING_SNAKE_CASE ( self ): run(self._app , host=self.host , port=self.port , workers=self.workers ) def SCREAMING_SNAKE_CASE ( self ): return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def SCREAMING_SNAKE_CASE ( self , _a = Body(_a , embed=_a ) , _a = Body(_a , embed=_a ) ): try: __magic_name__ : str = self._pipeline.tokenizer.tokenize(_a ) if return_ids: __magic_name__ : Dict = self._pipeline.tokenizer.convert_tokens_to_ids(_a ) return ServeTokenizeResult(tokens=_a , tokens_ids=_a ) else: return ServeTokenizeResult(tokens=_a ) except Exception as e: raise HTTPException(status_code=500 , detail={"model": "", "error": str(_a )} ) def SCREAMING_SNAKE_CASE ( self , _a = Body(_a , embed=_a ) , _a = Body(_a , embed=_a ) , _a = Body(_a , embed=_a ) , ): try: __magic_name__ : Dict = self._pipeline.tokenizer.decode(_a , _a , _a ) return ServeDeTokenizeResult(model="" , text=_a ) except Exception as e: raise HTTPException(status_code=500 , detail={"model": "", "error": str(_a )} ) async def SCREAMING_SNAKE_CASE ( self , _a=Body(_a , embed=_a ) ): # Check we don't have empty string if len(_a ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __magic_name__ : Any = self._pipeline(_a ) return ServeForwardResult(output=_a ) except Exception as e: raise HTTPException(500 , {"error": str(_a )} )
281
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class _snake_case : UpperCamelCase__ = LEDConfig UpperCamelCase__ = {} UpperCamelCase__ = 'gelu' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , _a=4 , ): __magic_name__ : int = parent __magic_name__ : Optional[int] = batch_size __magic_name__ : Tuple = seq_length __magic_name__ : List[Any] = is_training __magic_name__ : Dict = use_labels __magic_name__ : Optional[Any] = vocab_size __magic_name__ : int = hidden_size __magic_name__ : Optional[int] = num_hidden_layers __magic_name__ : Optional[int] = num_attention_heads __magic_name__ : Tuple = intermediate_size __magic_name__ : Any = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : List[str] = max_position_embeddings __magic_name__ : Any = eos_token_id __magic_name__ : str = pad_token_id __magic_name__ : int = bos_token_id __magic_name__ : Optional[int] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after __magic_name__ : Tuple = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests __magic_name__ : Tuple = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __magic_name__ : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __magic_name__ : int = tf.concat([input_ids, eos_tensor] , axis=1 ) __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) __magic_name__ : List[str] = prepare_led_inputs_dict(_a , _a , _a ) __magic_name__ : Union[str, Any] = tf.concat( [tf.zeros_like(_a )[:, :-1], tf.ones_like(_a )[:, -1:]] , axis=-1 , ) __magic_name__ : List[Any] = global_attention_mask return config, inputs_dict def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Dict = TFLEDModel(config=_a ).get_decoder() __magic_name__ : Optional[int] = inputs_dict["input_ids"] __magic_name__ : Union[str, Any] = input_ids[:1, :] __magic_name__ : str = inputs_dict["attention_mask"][:1, :] __magic_name__ : int = 1 # first forward pass __magic_name__ : Tuple = model(_a , attention_mask=_a , use_cache=_a ) __magic_name__ , __magic_name__ : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __magic_name__ : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __magic_name__ : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __magic_name__ : Optional[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) __magic_name__ : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __magic_name__ : List[str] = model(_a , attention_mask=_a )[0] __magic_name__ : Dict = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __magic_name__ : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __magic_name__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] __magic_name__ : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : List[Any] , _snake_case : Any , _snake_case : str=None , _snake_case : List[str]=None , _snake_case : int=None , _snake_case : Any=None , ) -> int: '''simple docstring''' if attention_mask is None: __magic_name__ : str = tf.cast(tf.math.not_equal(_snake_case , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __magic_name__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __magic_name__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __magic_name__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () UpperCamelCase__ = (TFLEDForConditionalGeneration,) if is_tf_available() else () UpperCamelCase__ = ( { 'conversational': TFLEDForConditionalGeneration, 'feature-extraction': TFLEDModel, 'summarization': TFLEDForConditionalGeneration, 'text2text-generation': TFLEDForConditionalGeneration, 'translation': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = TFLEDModelTester(self ) __magic_name__ : List[Any] = ConfigTester(self , config_class=_a ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ , __magic_name__ : int = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ : List[str] = tf.zeros_like(inputs_dict["attention_mask"] ) __magic_name__ : Optional[Any] = 2 __magic_name__ : Tuple = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) __magic_name__ : Any = True __magic_name__ : str = self.model_tester.seq_length __magic_name__ : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_a ): __magic_name__ : str = outputs.decoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_a ): __magic_name__ : Any = [t.numpy() for t in outputs.encoder_attentions] __magic_name__ : Tuple = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = False __magic_name__ : Tuple = False __magic_name__ : Optional[int] = model_class(_a ) __magic_name__ : str = model(self._prepare_for_class(_a , _a ) ) __magic_name__ : Any = len(_a ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) if self.is_encoder_decoder: __magic_name__ : Tuple = model_class(_a ) __magic_name__ : Optional[Any] = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_decoder_attentions_output(_a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __magic_name__ : Dict = True __magic_name__ : str = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) # Check attention is always last and order is fine __magic_name__ : Union[str, Any] = True __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) ) self.assertEqual(model.config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): # TODO: Head-masking not yet implement pass def lowerCAmelCase_ ( _snake_case : int ) -> Optional[int]: '''simple docstring''' return tf.constant(_snake_case , dtype=tf.intaa ) snake_case : Optional[int] = 1E-4 @slow @require_tf class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here __magic_name__ : Optional[int] = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : str = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Any = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : List[Any] = model(**_a )[0] __magic_name__ : List[str] = (1, 1_024, 768) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : int = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here __magic_name__ : int = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Tuple = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Optional[Any] = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : Union[str, Any] = model(**_a )[0] __magic_name__ : Optional[int] = (1, 1_024, model.config.vocab_size) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : str = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 , rtol=1e-3 )
281
1
def lowerCAmelCase_ ( _snake_case : Any ) -> str: '''simple docstring''' __magic_name__ : Tuple = len(_snake_case ) for i in range(length - 1 ): __magic_name__ : Dict = i for k in range(i + 1 , _snake_case ): if collection[k] < collection[least]: __magic_name__ : Tuple = k if least != i: __magic_name__ , __magic_name__ : List[str] = (collection[i], collection[least]) return collection if __name__ == "__main__": snake_case : Optional[int] = input("Enter numbers separated by a comma:\n").strip() snake_case : Any = [int(item) for item in user_input.split(",")] print(selection_sort(unsorted))
281
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() snake_case : Optional[Any] = logging.get_logger(__name__) def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Union[str, Any]=False ) -> List[str]: '''simple docstring''' __magic_name__ : Union[str, Any] = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" __magic_name__ : int = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Any , _snake_case : Dict=False ) -> int: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: __magic_name__ : int = "" else: __magic_name__ : Union[str, Any] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __magic_name__ : Optional[Any] = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) __magic_name__ : int = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __magic_name__ : Dict = in_proj_weight[ : config.hidden_size, : ] __magic_name__ : List[str] = in_proj_bias[: config.hidden_size] __magic_name__ : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __magic_name__ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __magic_name__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] __magic_name__ : int = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( _snake_case : List[str] ) -> List[str]: '''simple docstring''' __magic_name__ : List[str] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : int , _snake_case : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __magic_name__ : int = dct.pop(_snake_case ) __magic_name__ : List[Any] = val def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" __magic_name__ : List[str] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Any , _snake_case : int=False ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=_snake_case , ) __magic_name__ : List[str] = ViTHybridConfig(backbone_config=_snake_case , image_size=384 , num_labels=1000 ) __magic_name__ : str = False # load original model from timm __magic_name__ : Union[str, Any] = timm.create_model(_snake_case , pretrained=_snake_case ) timm_model.eval() # load state_dict of original model, remove and rename some keys __magic_name__ : List[Any] = timm_model.state_dict() if base_model: remove_classification_head_(_snake_case ) __magic_name__ : Tuple = create_rename_keys(_snake_case , _snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) read_in_q_k_v(_snake_case , _snake_case , _snake_case ) __magic_name__ : List[str] = "huggingface/label-files" __magic_name__ : int = "imagenet-1k-id2label.json" __magic_name__ : Optional[int] = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type="dataset" ) , "r" ) ) __magic_name__ : int = {int(_snake_case ): v for k, v in idalabel.items()} __magic_name__ : List[str] = idalabel __magic_name__ : List[str] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": __magic_name__ : List[str] = ViTHybridModel(_snake_case ).eval() else: __magic_name__ : str = ViTHybridForImageClassification(_snake_case ).eval() model.load_state_dict(_snake_case ) # create image processor __magic_name__ : List[Any] = create_transform(**resolve_data_config({} , model=_snake_case ) ) __magic_name__ : int = transform.transforms __magic_name__ : List[str] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } __magic_name__ : int = ViTHybridImageProcessor( do_resize=_snake_case , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_snake_case , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_snake_case , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) __magic_name__ : List[Any] = prepare_img() __magic_name__ : Any = transform(_snake_case ).unsqueeze(0 ) __magic_name__ : Tuple = processor(_snake_case , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(_snake_case , _snake_case ) # verify logits with torch.no_grad(): __magic_name__ : Optional[int] = model(_snake_case ) __magic_name__ : List[str] = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: __magic_name__ : List[str] = timm_model.forward_features(_snake_case ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_snake_case , outputs.pooler_output , atol=1E-3 ) else: __magic_name__ : Any = timm_model(_snake_case ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_snake_case , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_snake_case ) if push_to_hub: print(F'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(F'''ybelkada/{vit_name}''' ) processor.push_to_hub(F'''ybelkada/{vit_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) snake_case : List[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
import unittest import numpy as np def lowerCAmelCase_ ( _snake_case : np.ndarray , _snake_case : np.ndarray , _snake_case : np.ndarray , _snake_case : np.ndarray | None = None , ) -> np.ndarray: '''simple docstring''' __magic_name__ : Any = np.shape(_snake_case ) __magic_name__ : List[str] = np.shape(_snake_case ) __magic_name__ : Dict = np.shape(_snake_case ) if shape_a[0] != shape_b[0]: __magic_name__ : List[Any] = ( "Expected the same number of rows for A and B. " F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(_snake_case ) if shape_b[1] != shape_c[1]: __magic_name__ : Any = ( "Expected the same number of columns for B and C. " F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(_snake_case ) __magic_name__ : str = pseudo_inv if a_inv is None: try: __magic_name__ : int = np.linalg.inv(_snake_case ) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __magic_name__ : Dict = np.array([[0, 3], [3, 0], [2, 3]] ) __magic_name__ : List[Any] = np.array([[2, 1], [6, 3]] ) __magic_name__ : Dict = schur_complement(_a , _a , _a ) __magic_name__ : int = np.block([[a, b], [b.T, c]] ) __magic_name__ : Dict = np.linalg.det(_a ) __magic_name__ : str = np.linalg.det(_a ) __magic_name__ : Dict = np.linalg.det(_a ) self.assertAlmostEqual(_a , det_a * det_s ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __magic_name__ : str = np.array([[0, 3], [3, 0], [2, 3]] ) __magic_name__ : Union[str, Any] = np.array([[2, 1], [6, 3]] ) with self.assertRaises(_a ): schur_complement(_a , _a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] ) __magic_name__ : Optional[Any] = np.array([[0, 3], [3, 0], [2, 3]] ) __magic_name__ : List[Any] = np.array([[2, 1, 3], [6, 3, 5]] ) with self.assertRaises(_a ): schur_complement(_a , _a , _a ) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
281
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration snake_case : List[str] = "facebook/wmt19-en-de" snake_case : Dict = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model snake_case : List[str] = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) snake_case : int = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test snake_case : Optional[Any] = tokenizer(["Making tiny model"], return_tensors="pt") snake_case : List[str] = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save snake_case : Dict = "tiny-wmt19-en-de" tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-de
281
1
from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCAmelCase_ ( _snake_case : bool = True , *_snake_case : str , **_snake_case : int ) -> Dict: '''simple docstring''' if not is_tqdm_available(): raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`." ) __magic_name__ : str = False if main_process_only: __magic_name__ : Tuple = PartialState().local_process_index == 0 return _tqdm(*_snake_case , **_snake_case , disable=_snake_case )
281
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Union[str, Any] ) -> Tuple: '''simple docstring''' __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' with open(_snake_case , encoding="utf_8" ) as f: __magic_name__ : List[str] = csv.reader(_snake_case ) __magic_name__ : List[Any] = [] next(_snake_case ) # skip the first line for line in tqdm(_snake_case ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( _snake_case : str , _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : Optional[int] ) -> int: '''simple docstring''' __magic_name__ : Optional[int] = [] for dataset in encoded_datasets: __magic_name__ : Union[str, Any] = len(_snake_case ) __magic_name__ : Dict = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __magic_name__ : List[str] = np.zeros((n_batch, 2) , dtype=np.intaa ) __magic_name__ : Optional[int] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __magic_name__ : int = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(_snake_case ): __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : str = with_conta __magic_name__ : Tuple = with_conta __magic_name__ : Union[str, Any] = len(_snake_case ) - 1 __magic_name__ : int = len(_snake_case ) - 1 __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[int] = mc_label __magic_name__ : str = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(_snake_case ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser() parser.add_argument("--model_name" , type=_snake_case , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=_snake_case , default="" ) parser.add_argument("--eval_dataset" , type=_snake_case , default="" ) parser.add_argument("--seed" , type=_snake_case , default=42 ) parser.add_argument("--num_train_epochs" , type=_snake_case , default=3 ) parser.add_argument("--train_batch_size" , type=_snake_case , default=8 ) parser.add_argument("--eval_batch_size" , type=_snake_case , default=16 ) parser.add_argument("--adam_epsilon" , default=1E-8 , type=_snake_case , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=_snake_case , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=_snake_case , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=_snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=_snake_case , default=6.25E-5 ) parser.add_argument("--warmup_steps" , default=0 , type=_snake_case , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=_snake_case , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=_snake_case , default=0.01 ) parser.add_argument("--lm_coef" , type=_snake_case , default=0.9 ) parser.add_argument("--n_valid" , type=_snake_case , default=374 ) parser.add_argument("--server_ip" , type=_snake_case , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=_snake_case , default="" , help="Can be used for distant debugging." ) __magic_name__ : List[Any] = parser.parse_args() print(_snake_case ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __magic_name__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) __magic_name__ : Optional[int] = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(_snake_case , _snake_case ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __magic_name__ : List[Any] = ["_start_", "_delimiter_", "_classify_"] __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(_snake_case ) __magic_name__ : Optional[Any] = tokenizer.convert_tokens_to_ids(_snake_case ) __magic_name__ : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(_snake_case ) ) model.to(_snake_case ) # Load and encode the datasets def tokenize_and_encode(_snake_case : str ): if isinstance(_snake_case , _snake_case ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case ) ) elif isinstance(_snake_case , _snake_case ): return obj return [tokenize_and_encode(_snake_case ) for o in obj] logger.info("Encoding dataset..." ) __magic_name__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) __magic_name__ : str = load_rocstories_dataset(args.eval_dataset ) __magic_name__ : int = (train_dataset, eval_dataset) __magic_name__ : List[str] = tokenize_and_encode(_snake_case ) # Compute the max input length for the Transformer __magic_name__ : Optional[Any] = model.config.n_positions // 2 - 2 __magic_name__ : Optional[int] = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __magic_name__ : List[str] = min(_snake_case , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __magic_name__ : List[Any] = pre_process_datasets(_snake_case , _snake_case , _snake_case , *_snake_case ) __magic_name__ , __magic_name__ : Optional[int] = tensor_datasets[0], tensor_datasets[1] __magic_name__ : Tuple = TensorDataset(*_snake_case ) __magic_name__ : Union[str, Any] = RandomSampler(_snake_case ) __magic_name__ : Dict = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.train_batch_size ) __magic_name__ : Any = TensorDataset(*_snake_case ) __magic_name__ : Optional[Any] = SequentialSampler(_snake_case ) __magic_name__ : int = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __magic_name__ : Tuple = args.max_steps __magic_name__ : List[str] = args.max_steps // (len(_snake_case ) // args.gradient_accumulation_steps) + 1 else: __magic_name__ : List[str] = len(_snake_case ) // args.gradient_accumulation_steps * args.num_train_epochs __magic_name__ : str = list(model.named_parameters() ) __magic_name__ : Dict = ["bias", "LayerNorm.bias", "LayerNorm.weight"] __magic_name__ : str = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] __magic_name__ : str = AdamW(_snake_case , lr=args.learning_rate , eps=args.adam_epsilon ) __magic_name__ : List[str] = get_linear_schedule_with_warmup( _snake_case , num_warmup_steps=args.warmup_steps , num_training_steps=_snake_case ) if args.do_train: __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): __magic_name__ : List[str] = 0 __magic_name__ : Tuple = 0 __magic_name__ : Dict = tqdm(_snake_case , desc="Training" ) for step, batch in enumerate(_snake_case ): __magic_name__ : Optional[Any] = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = batch __magic_name__ : Optional[Any] = model(_snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __magic_name__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __magic_name__ : int = "Training loss: {:.2e} lr: {:.2e}".format(_snake_case , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __magic_name__ : Dict = model.module if hasattr(_snake_case , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __magic_name__ : List[Any] = os.path.join(args.output_dir , _snake_case ) __magic_name__ : Dict = os.path.join(args.output_dir , _snake_case ) torch.save(model_to_save.state_dict() , _snake_case ) model_to_save.config.to_json_file(_snake_case ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __magic_name__ : Dict = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(_snake_case ) if args.do_eval: model.eval() __magic_name__ , __magic_name__ : Any = 0, 0 __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0 for batch in tqdm(_snake_case , desc="Evaluating" ): __magic_name__ : int = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = batch with torch.no_grad(): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = model( _snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Tuple = mc_logits.detach().cpu().numpy() __magic_name__ : Any = mc_labels.to("cpu" ).numpy() __magic_name__ : str = accuracy(_snake_case , _snake_case ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __magic_name__ : Tuple = eval_loss / nb_eval_steps __magic_name__ : List[Any] = eval_accuracy / nb_eval_examples __magic_name__ : int = tr_loss / nb_tr_steps if args.do_train else None __magic_name__ : Any = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} __magic_name__ : int = os.path.join(args.output_dir , "eval_results.txt" ) with open(_snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , _snake_case , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
281
1
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Union[str, Any] = logging.get_logger(__name__) snake_case : int = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class _snake_case ( snake_case ): UpperCamelCase__ = 'align_text_model' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=0 , _a="absolute" , _a=True , **_a , ): super().__init__(**_a ) __magic_name__ : int = vocab_size __magic_name__ : List[Any] = hidden_size __magic_name__ : Tuple = num_hidden_layers __magic_name__ : Union[str, Any] = num_attention_heads __magic_name__ : Any = hidden_act __magic_name__ : Optional[int] = intermediate_size __magic_name__ : Optional[Any] = hidden_dropout_prob __magic_name__ : Dict = attention_probs_dropout_prob __magic_name__ : int = max_position_embeddings __magic_name__ : Optional[int] = type_vocab_size __magic_name__ : List[str] = initializer_range __magic_name__ : Tuple = layer_norm_eps __magic_name__ : str = position_embedding_type __magic_name__ : Dict = use_cache __magic_name__ : int = pad_token_id @classmethod def SCREAMING_SNAKE_CASE ( cls , _a , **_a ): cls._set_token_in_kwargs(_a ) __magic_name__ , __magic_name__ : List[Any] = cls.get_config_dict(_a , **_a ) # get the text config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": __magic_name__ : Union[str, Any] = 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(_a , **_a ) class _snake_case ( snake_case ): UpperCamelCase__ = 'align_vision_model' def __init__( self , _a = 3 , _a = 600 , _a = 2.0 , _a = 3.1 , _a = 8 , _a = [3, 3, 5, 3, 5, 5, 3] , _a = [32, 16, 24, 40, 80, 112, 192] , _a = [16, 24, 40, 80, 112, 192, 320] , _a = [] , _a = [1, 2, 2, 2, 1, 2, 1] , _a = [1, 2, 2, 3, 3, 4, 1] , _a = [1, 6, 6, 6, 6, 6, 6] , _a = 0.25 , _a = "swish" , _a = 2_560 , _a = "mean" , _a = 0.02 , _a = 0.0_01 , _a = 0.99 , _a = 0.2 , **_a , ): super().__init__(**_a ) __magic_name__ : Optional[int] = num_channels __magic_name__ : Tuple = image_size __magic_name__ : Any = width_coefficient __magic_name__ : Optional[Any] = depth_coefficient __magic_name__ : str = depth_divisor __magic_name__ : Optional[int] = kernel_sizes __magic_name__ : Tuple = in_channels __magic_name__ : str = out_channels __magic_name__ : Dict = depthwise_padding __magic_name__ : List[Any] = strides __magic_name__ : List[str] = num_block_repeats __magic_name__ : Optional[Any] = expand_ratios __magic_name__ : Any = squeeze_expansion_ratio __magic_name__ : Union[str, Any] = hidden_act __magic_name__ : Dict = hidden_dim __magic_name__ : Any = pooling_type __magic_name__ : Tuple = initializer_range __magic_name__ : int = batch_norm_eps __magic_name__ : Union[str, Any] = batch_norm_momentum __magic_name__ : str = drop_connect_rate __magic_name__ : str = sum(_a ) * 4 @classmethod def SCREAMING_SNAKE_CASE ( cls , _a , **_a ): cls._set_token_in_kwargs(_a ) __magic_name__ , __magic_name__ : List[str] = cls.get_config_dict(_a , **_a ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": __magic_name__ : Optional[int] = 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(_a , **_a ) class _snake_case ( snake_case ): UpperCamelCase__ = 'align' UpperCamelCase__ = True def __init__( self , _a=None , _a=None , _a=640 , _a=1.0 , _a=0.02 , **_a , ): super().__init__(**_a ) if text_config is None: __magic_name__ : int = {} logger.info("text_config is None. Initializing the AlignTextConfig with default values." ) if vision_config is None: __magic_name__ : Union[str, Any] = {} logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." ) __magic_name__ : Union[str, Any] = AlignTextConfig(**_a ) __magic_name__ : Any = AlignVisionConfig(**_a ) __magic_name__ : Tuple = projection_dim __magic_name__ : List[str] = temperature_init_value __magic_name__ : Optional[Any] = initializer_range @classmethod def SCREAMING_SNAKE_CASE ( cls , _a , _a , **_a ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = copy.deepcopy(self.__dict__ ) __magic_name__ : Optional[int] = self.text_config.to_dict() __magic_name__ : Tuple = self.vision_config.to_dict() __magic_name__ : List[Any] = self.__class__.model_type return output
281
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
281
1
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCAmelCase_ ( _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Tuple: '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Dict = "mock-s3-bucket" __magic_name__ : Any = F'''s3://{mock_bucket}''' __magic_name__ : str = extract_path_from_uri(_snake_case ) assert dataset_path.startswith("s3://" ) is False __magic_name__ : Tuple = "./local/path" __magic_name__ : Optional[Any] = extract_path_from_uri(_snake_case ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' __magic_name__ : str = is_remote_filesystem(_snake_case ) assert is_remote is True __magic_name__ : Optional[int] = fsspec.filesystem("file" ) __magic_name__ : int = is_remote_filesystem(_snake_case ) assert is_remote is False @pytest.mark.parametrize("compression_fs_class" , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : int , _snake_case : Tuple , _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Any ) -> int: '''simple docstring''' __magic_name__ : Any = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file} __magic_name__ : str = input_paths[compression_fs_class.protocol] if input_path is None: __magic_name__ : Dict = F'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_snake_case ) __magic_name__ : str = fsspec.filesystem(compression_fs_class.protocol , fo=_snake_case ) assert isinstance(_snake_case , _snake_case ) __magic_name__ : int = os.path.basename(_snake_case ) __magic_name__ : Optional[int] = expected_filename[: expected_filename.rindex("." )] assert fs.glob("*" ) == [expected_filename] with fs.open(_snake_case , "r" , encoding="utf-8" ) as f, open(_snake_case , encoding="utf-8" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol" , ["zip", "gzip"] ) def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] ) -> str: '''simple docstring''' __magic_name__ : int = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} __magic_name__ : int = compressed_file_paths[protocol] __magic_name__ : Tuple = "dataset.jsonl" __magic_name__ : List[str] = F'''{protocol}://{member_file_path}::{compressed_file_path}''' __magic_name__ , *__magic_name__ : Optional[Any] = fsspec.get_fs_token_paths(_snake_case ) assert fs.isfile(_snake_case ) assert not fs.isfile("non_existing_" + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : List[str] , _snake_case : Tuple ) -> str: '''simple docstring''' __magic_name__ : int = hf_api.dataset_info(_snake_case , token=_snake_case ) __magic_name__ : Optional[Any] = HfFileSystem(repo_info=_snake_case , token=_snake_case ) assert sorted(hffs.glob("*" ) ) == [".gitattributes", "data"] assert hffs.isdir("data" ) assert hffs.isfile(".gitattributes" ) and hffs.isfile("data/text_data.txt" ) with open(_snake_case ) as f: assert hffs.open("data/text_data.txt" , "r" ).read() == f.read() def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' __magic_name__ : Optional[Any] = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_snake_case , _snake_case , clobber=_snake_case ) with pytest.warns(_snake_case ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_snake_case ) == 1 assert ( str(warning_info[0].message ) == F'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
281
1
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_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING snake_case : int = logging.get_logger(__name__) @add_end_docstrings(snake_case ) class _snake_case ( snake_case ): def __init__( self , *_a , **_a ): super().__init__(*_a , **_a ) requires_backends(self , "vision" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def SCREAMING_SNAKE_CASE ( self , _a=None ): __magic_name__ : Dict = {} if top_k is not None: __magic_name__ : Optional[Any] = top_k return {}, {}, postprocess_params def __call__( self , _a , **_a ): return super().__call__(_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Dict = load_image(_a ) __magic_name__ : List[Any] = self.image_processor(images=_a , return_tensors=self.framework ) return model_inputs def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Any = self.model(**_a ) return model_outputs def SCREAMING_SNAKE_CASE ( self , _a , _a=5 ): if top_k > self.model.config.num_labels: __magic_name__ : Optional[int] = self.model.config.num_labels if self.framework == "pt": __magic_name__ : Any = model_outputs.logits.softmax(-1 )[0] __magic_name__ , __magic_name__ : List[Any] = probs.topk(_a ) elif self.framework == "tf": __magic_name__ : int = stable_softmax(model_outputs.logits , axis=-1 )[0] __magic_name__ : List[str] = tf.math.top_k(_a , k=_a ) __magic_name__ , __magic_name__ : Optional[int] = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(f'''Unsupported framework: {self.framework}''' ) __magic_name__ : Dict = scores.tolist() __magic_name__ : str = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_a , _a )]
281
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : List[Any] = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _snake_case ( snake_case ): UpperCamelCase__ = 'convbert' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=1 , _a=0 , _a=2 , _a=768 , _a=2 , _a=9 , _a=1 , _a=None , **_a , ): super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) __magic_name__ : Tuple = vocab_size __magic_name__ : List[Any] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : List[Any] = num_attention_heads __magic_name__ : str = intermediate_size __magic_name__ : Any = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : Tuple = max_position_embeddings __magic_name__ : str = type_vocab_size __magic_name__ : List[str] = initializer_range __magic_name__ : Tuple = layer_norm_eps __magic_name__ : List[Any] = embedding_size __magic_name__ : List[Any] = head_ratio __magic_name__ : str = conv_kernel_size __magic_name__ : Dict = num_groups __magic_name__ : str = classifier_dropout class _snake_case ( snake_case ): @property def SCREAMING_SNAKE_CASE ( self ): if self.task == "multiple-choice": __magic_name__ : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: __magic_name__ : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
281
1
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = CycleDiffusionPipeline UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { 'negative_prompt', 'height', 'width', 'negative_prompt_embeds', } UpperCamelCase__ = PipelineTesterMixin.required_optional_params - {'latents'} UpperCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'} ) UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE ( self ): torch.manual_seed(0 ) __magic_name__ : Union[str, Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) __magic_name__ : List[str] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , num_train_timesteps=1_000 , clip_sample=_a , set_alpha_to_one=_a , ) torch.manual_seed(0 ) __magic_name__ : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) __magic_name__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) __magic_name__ : Tuple = CLIPTextModel(_a ) __magic_name__ : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __magic_name__ : List[str] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE ( self , _a , _a=0 ): __magic_name__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(_a ) ).to(_a ) __magic_name__ : str = image / 2 + 0.5 if str(_a ).startswith("mps" ): __magic_name__ : Tuple = torch.manual_seed(_a ) else: __magic_name__ : int = torch.Generator(device=_a ).manual_seed(_a ) __magic_name__ : Dict = { "prompt": "An astronaut riding an elephant", "source_prompt": "An astronaut riding a horse", "image": image, "generator": generator, "num_inference_steps": 2, "eta": 0.1, "strength": 0.8, "guidance_scale": 3, "source_guidance_scale": 1, "output_type": "numpy", } return inputs def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = "cpu" # ensure determinism for the device-dependent torch.Generator __magic_name__ : Any = self.get_dummy_components() __magic_name__ : Any = CycleDiffusionPipeline(**_a ) __magic_name__ : List[Any] = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __magic_name__ : str = self.get_dummy_inputs(_a ) __magic_name__ : Union[str, Any] = pipe(**_a ) __magic_name__ : Any = output.images __magic_name__ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __magic_name__ : Union[str, Any] = np.array([0.44_59, 0.49_43, 0.45_44, 0.66_43, 0.54_74, 0.43_27, 0.57_01, 0.59_59, 0.51_79] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = self.get_dummy_components() for name, module in components.items(): if hasattr(_a , "half" ): __magic_name__ : Tuple = module.half() __magic_name__ : int = CycleDiffusionPipeline(**_a ) __magic_name__ : int = pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __magic_name__ : Optional[Any] = self.get_dummy_inputs(_a ) __magic_name__ : int = pipe(**_a ) __magic_name__ : Optional[int] = output.images __magic_name__ : List[Any] = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) __magic_name__ : List[Any] = np.array([0.35_06, 0.45_43, 0.4_46, 0.45_75, 0.51_95, 0.41_55, 0.52_73, 0.5_18, 0.41_16] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def SCREAMING_SNAKE_CASE ( self ): return super().test_save_load_local() @unittest.skip("non-deterministic pipeline" ) def SCREAMING_SNAKE_CASE ( self ): return super().test_inference_batch_single_identical() @skip_mps def SCREAMING_SNAKE_CASE ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def SCREAMING_SNAKE_CASE ( self ): return super().test_save_load_optional_components() @skip_mps def SCREAMING_SNAKE_CASE ( self ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/cycle-diffusion/black_colored_car.png" ) __magic_name__ : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy" ) __magic_name__ : int = init_image.resize((512, 512) ) __magic_name__ : Optional[Any] = "CompVis/stable-diffusion-v1-4" __magic_name__ : Optional[Any] = DDIMScheduler.from_pretrained(_a , subfolder="scheduler" ) __magic_name__ : int = CycleDiffusionPipeline.from_pretrained( _a , scheduler=_a , safety_checker=_a , torch_dtype=torch.floataa , revision="fp16" ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() __magic_name__ : List[Any] = "A black colored car" __magic_name__ : Union[str, Any] = "A blue colored car" __magic_name__ : int = torch.manual_seed(0 ) __magic_name__ : Tuple = pipe( prompt=_a , source_prompt=_a , image=_a , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_a , output_type="np" , ) __magic_name__ : List[str] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/cycle-diffusion/black_colored_car.png" ) __magic_name__ : str = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy" ) __magic_name__ : Any = init_image.resize((512, 512) ) __magic_name__ : List[str] = "CompVis/stable-diffusion-v1-4" __magic_name__ : Dict = DDIMScheduler.from_pretrained(_a , subfolder="scheduler" ) __magic_name__ : str = CycleDiffusionPipeline.from_pretrained(_a , scheduler=_a , safety_checker=_a ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) pipe.enable_attention_slicing() __magic_name__ : str = "A black colored car" __magic_name__ : Dict = "A blue colored car" __magic_name__ : Optional[int] = torch.manual_seed(0 ) __magic_name__ : int = pipe( prompt=_a , source_prompt=_a , image=_a , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_a , output_type="np" , ) __magic_name__ : Tuple = output.images assert np.abs(image - expected_image ).max() < 2e-2
281
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCAmelCase_ ( ) -> str: '''simple docstring''' __magic_name__ : int = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" __magic_name__ : Union[str, Any] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ).convert("RGB" ) return image def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias") ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Optional[Any] ) -> int: '''simple docstring''' __magic_name__ : Tuple = dct.pop(_snake_case ) __magic_name__ : int = val def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __magic_name__ : List[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) __magic_name__ : Optional[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict __magic_name__ : Optional[int] = torch.cat((q_bias, torch.zeros_like(_snake_case , requires_grad=_snake_case ), v_bias) ) __magic_name__ : Union[str, Any] = qkv_bias def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : str ) -> int: '''simple docstring''' __magic_name__ : List[Any] = 364 if "coco" in model_name else 224 __magic_name__ : Union[str, Any] = BlipaVisionConfig(image_size=_snake_case ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: __magic_name__ : List[str] = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=_snake_case ).to_dict() elif "opt-6.7b" in model_name: __magic_name__ : Any = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=_snake_case ).to_dict() elif "t5-xl" in model_name: __magic_name__ : Dict = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __magic_name__ : int = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() __magic_name__ : List[Any] = BlipaConfig(vision_config=_snake_case , text_config=_snake_case ) return config, image_size @torch.no_grad() def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : str=None , _snake_case : Dict=False ) -> List[Any]: '''simple docstring''' __magic_name__ : Optional[int] = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) __magic_name__ : List[Any] = tokenizer("\n" , add_special_tokens=_snake_case ).input_ids[0] __magic_name__ , __magic_name__ : Tuple = get_blipa_config(_snake_case , eos_token_id=_snake_case ) __magic_name__ : Union[str, Any] = BlipaForConditionalGeneration(_snake_case ).eval() __magic_name__ : Any = { "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"), "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"), "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"), "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"), "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"), "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"), "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"), } __magic_name__ , __magic_name__ : Union[str, Any] = model_name_to_original[model_name] # load original model print("Loading original model..." ) __magic_name__ : Union[str, Any] = "cuda" if torch.cuda.is_available() else "cpu" __magic_name__ , __magic_name__ , __magic_name__ : Optional[Any] = load_model_and_preprocess( name=_snake_case , model_type=_snake_case , is_eval=_snake_case , device=_snake_case ) original_model.eval() print("Done!" ) # update state dict keys __magic_name__ : Dict = original_model.state_dict() __magic_name__ : str = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __magic_name__ : Any = state_dict.pop(_snake_case ) if key.startswith("Qformer.bert" ): __magic_name__ : Optional[int] = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: __magic_name__ : Any = key.replace("self" , "attention" ) if "opt_proj" in key: __magic_name__ : Union[str, Any] = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: __magic_name__ : Optional[int] = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): __magic_name__ : List[str] = key.replace("opt" , "language" ) if key.startswith("t5" ): __magic_name__ : Tuple = key.replace("t5" , "language" ) __magic_name__ : Dict = val # read in qv biases read_in_q_v_bias(_snake_case , _snake_case ) __magic_name__ , __magic_name__ : Tuple = hf_model.load_state_dict(_snake_case , strict=_snake_case ) assert len(_snake_case ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __magic_name__ : List[Any] = load_demo_image() __magic_name__ : Tuple = vis_processors["eval"](_snake_case ).unsqueeze(0 ).to(_snake_case ) __magic_name__ : Dict = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(_snake_case ) # create processor __magic_name__ : Optional[Any] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=_snake_case , image_std=_snake_case ) __magic_name__ : Dict = BlipaProcessor(image_processor=_snake_case , tokenizer=_snake_case ) __magic_name__ : Union[str, Any] = processor(images=_snake_case , return_tensors="pt" ).pixel_values.to(_snake_case ) # make sure processor creates exact same pixel values assert torch.allclose(_snake_case , _snake_case ) original_model.to(_snake_case ) hf_model.to(_snake_case ) with torch.no_grad(): if "opt" in model_name: __magic_name__ : List[Any] = original_model({"image": original_pixel_values, "text_input": [""]} ).logits __magic_name__ : Optional[int] = hf_model(_snake_case , _snake_case ).logits else: __magic_name__ : int = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits __magic_name__ : Tuple = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) __magic_name__ : List[str] = hf_model(_snake_case , _snake_case , labels=_snake_case ).logits assert original_logits.shape == logits.shape print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": __magic_name__ : List[str] = torch.tensor( [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]] , device=_snake_case ) assert torch.allclose(logits[0, :3, :3] , _snake_case , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": __magic_name__ : Tuple = torch.tensor( [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]] , device=_snake_case ) else: # cast to same type __magic_name__ : str = logits.dtype assert torch.allclose(original_logits.to(_snake_case ) , _snake_case , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) __magic_name__ : Optional[int] = "" __magic_name__ : Dict = tokenizer(_snake_case , return_tensors="pt" ).input_ids.to(_snake_case ) __magic_name__ : int = original_model.generate({"image": original_pixel_values} ) __magic_name__ : Optional[Any] = hf_model.generate( _snake_case , _snake_case , do_sample=_snake_case , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("Original generation:" , _snake_case ) __magic_name__ : Tuple = input_ids.shape[1] __magic_name__ : int = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=_snake_case ) __magic_name__ : Union[str, Any] = [text.strip() for text in output_text] print("HF generation:" , _snake_case ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_snake_case ) hf_model.save_pretrained(_snake_case ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() snake_case : Union[str, Any] = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) snake_case : int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
from __future__ import annotations class _snake_case : def __init__( self , _a , _a ): __magic_name__ , __magic_name__ : Dict = text, pattern __magic_name__ , __magic_name__ : int = len(_a ), len(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def SCREAMING_SNAKE_CASE ( self , _a ): for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def SCREAMING_SNAKE_CASE ( self ): # searches pattern in text and returns index positions __magic_name__ : Optional[int] = [] for i in range(self.textLen - self.patLen + 1 ): __magic_name__ : Any = self.mismatch_in_text(_a ) if mismatch_index == -1: positions.append(_a ) else: __magic_name__ : Optional[Any] = self.match_in_pattern(self.text[mismatch_index] ) __magic_name__ : List[Any] = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions snake_case : Any = "ABAABA" snake_case : List[str] = "AB" snake_case : Tuple = BoyerMooreSearch(text, pattern) snake_case : str = bms.bad_character_heuristic() if len(positions) == 0: print("No match found") else: print("Pattern found in following positions: ") print(positions)
281
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : Union[str, Any] = { "vocab_file": "vocab.txt", "merges_file": "bpe.codes", } snake_case : Dict = { "vocab_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt", }, "merges_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes", }, } snake_case : Union[str, Any] = { "vinai/phobert-base": 256, "vinai/phobert-large": 256, } def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = set() __magic_name__ : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __magic_name__ : int = char __magic_name__ : List[str] = set(_snake_case ) return pairs class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , **_a , ): super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , **_a , ) __magic_name__ : Dict = vocab_file __magic_name__ : Tuple = merges_file __magic_name__ : List[Any] = {} __magic_name__ : List[Any] = 0 __magic_name__ : Tuple = 1 __magic_name__ : int = 2 __magic_name__ : Union[str, Any] = 3 self.add_from_file(_a ) __magic_name__ : Optional[int] = {v: k for k, v in self.encoder.items()} with open(_a , encoding="utf-8" ) as merges_handle: __magic_name__ : List[str] = merges_handle.read().split("\n" )[:-1] __magic_name__ : Union[str, Any] = [tuple(merge.split()[:-1] ) for merge in merges] __magic_name__ : Union[str, Any] = dict(zip(_a , range(len(_a ) ) ) ) __magic_name__ : Optional[int] = {} def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __magic_name__ : Optional[Any] = [self.cls_token_id] __magic_name__ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[Any] = [self.sep_token_id] __magic_name__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ): return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self , _a ): if token in self.cache: return self.cache[token] __magic_name__ : List[Any] = tuple(_a ) __magic_name__ : List[Any] = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) __magic_name__ : Any = get_pairs(_a ) if not pairs: return token while True: __magic_name__ : str = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __magic_name__ , __magic_name__ : List[str] = bigram __magic_name__ : List[str] = [] __magic_name__ : List[str] = 0 while i < len(_a ): try: __magic_name__ : Any = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __magic_name__ : Tuple = 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 __magic_name__ : Union[str, Any] = tuple(_a ) __magic_name__ : Optional[int] = new_word if len(_a ) == 1: break else: __magic_name__ : List[Any] = get_pairs(_a ) __magic_name__ : Optional[int] = "@@ ".join(_a ) __magic_name__ : Tuple = word[:-4] __magic_name__ : str = word return word def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = [] __magic_name__ : Dict = re.findall(r"\S+\n?" , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(" " ) ) ) return split_tokens def SCREAMING_SNAKE_CASE ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.decoder.get(_a , self.unk_token ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Tuple = " ".join(_a ).replace("@@ " , "" ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : Optional[int] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __magic_name__ : Union[str, Any] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) if os.path.abspath(self.merges_file ) != os.path.abspath(_a ): copyfile(self.merges_file , _a ) return out_vocab_file, out_merge_file def SCREAMING_SNAKE_CASE ( self , _a ): if isinstance(_a , _a ): try: with open(_a , "r" , encoding="utf-8" ) as fd: self.add_from_file(_a ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return __magic_name__ : List[Any] = f.readlines() for lineTmp in lines: __magic_name__ : Optional[Any] = lineTmp.strip() __magic_name__ : Union[str, Any] = line.rfind(" " ) if idx == -1: raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'" ) __magic_name__ : Optional[int] = line[:idx] __magic_name__ : Dict = len(self.encoder )
281
1
import unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE ( *_a , **_a ): pass @is_pipeline_test @require_vision class _snake_case ( unittest.TestCase ): @require_torch def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , ) __magic_name__ : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ : Tuple = image_classifier(_a , candidate_labels=["a", "b", "c"] ) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(_a ) , [ [{"score": 0.3_33, "label": "a"}, {"score": 0.3_33, "label": "b"}, {"score": 0.3_33, "label": "c"}], [{"score": 0.3_33, "label": "a"}, {"score": 0.3_33, "label": "c"}, {"score": 0.3_33, "label": "b"}], ] , ) __magic_name__ : Optional[Any] = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(_a ) , [ [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], ] , ) @require_tf def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification" , framework="tf" ) __magic_name__ : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ : Any = image_classifier(_a , candidate_labels=["a", "b", "c"] ) self.assertEqual( nested_simplify(_a ) , [{"score": 0.3_33, "label": "a"}, {"score": 0.3_33, "label": "b"}, {"score": 0.3_33, "label": "c"}] , ) __magic_name__ : int = image_classifier([image] * 5 , candidate_labels=["A", "B", "C"] , batch_size=2 ) self.assertEqual( nested_simplify(_a ) , [ [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], [ {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, {"score": 0.3_33, "label": ANY(_a )}, ], ] , ) @slow @require_torch def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , ) # This is an image of 2 cats with remotes and no planes __magic_name__ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ : Union[str, Any] = image_classifier(_a , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(_a ) , [ {"score": 0.5_11, "label": "remote"}, {"score": 0.4_85, "label": "cat"}, {"score": 0.0_04, "label": "plane"}, ] , ) __magic_name__ : Optional[Any] = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(_a ) , [ [ {"score": 0.5_11, "label": "remote"}, {"score": 0.4_85, "label": "cat"}, {"score": 0.0_04, "label": "plane"}, ], ] * 5 , ) @slow @require_tf def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = pipeline( task="zero-shot-image-classification" , model="openai/clip-vit-base-patch32" , framework="tf" ) # This is an image of 2 cats with remotes and no planes __magic_name__ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) __magic_name__ : List[str] = image_classifier(_a , candidate_labels=["cat", "plane", "remote"] ) self.assertEqual( nested_simplify(_a ) , [ {"score": 0.5_11, "label": "remote"}, {"score": 0.4_85, "label": "cat"}, {"score": 0.0_04, "label": "plane"}, ] , ) __magic_name__ : Dict = image_classifier([image] * 5 , candidate_labels=["cat", "plane", "remote"] , batch_size=2 ) self.assertEqual( nested_simplify(_a ) , [ [ {"score": 0.5_11, "label": "remote"}, {"score": 0.4_85, "label": "cat"}, {"score": 0.0_04, "label": "plane"}, ], ] * 5 , )
281
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( _snake_case : str = "laptop" ) -> DataFrame: '''simple docstring''' __magic_name__ : Tuple = F'''https://www.amazon.in/laptop/s?k={product}''' __magic_name__ : Dict = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } __magic_name__ : Tuple = BeautifulSoup(requests.get(_snake_case , headers=_snake_case ).text ) # Initialize a Pandas dataframe with the column titles __magic_name__ : int = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" , attrs={"class": "s-result-item", "data-component-type": "s-search-result"} , ) , soup.find_all("div" , attrs={"class": "a-row a-size-base a-color-base"} ) , ): try: __magic_name__ : Dict = item.ha.text __magic_name__ : Optional[int] = "https://www.amazon.in/" + item.ha.a["href"] __magic_name__ : Optional[Any] = item.find("span" , attrs={"class": "a-offscreen"} ).text try: __magic_name__ : Union[str, Any] = item.find("span" , attrs={"class": "a-icon-alt"} ).text except AttributeError: __magic_name__ : Dict = "Not available" try: __magic_name__ : Optional[int] = ( "₹" + item.find( "span" , attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: __magic_name__ : List[str] = "" try: __magic_name__ : int = float( ( ( float(product_mrp.strip("₹" ).replace("," , "" ) ) - float(product_price.strip("₹" ).replace("," , "" ) ) ) / float(product_mrp.strip("₹" ).replace("," , "" ) ) ) * 100 ) except ValueError: __magic_name__ : str = float("nan" ) except AttributeError: pass __magic_name__ : Optional[int] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __magic_name__ : Optional[Any] = " " __magic_name__ : str = " " data_frame.index += 1 return data_frame if __name__ == "__main__": snake_case : Any = "headphones" get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
281
1
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse("0.8.3"): raise Exception("requires gluonnlp == 0.8.3") if version.parse(mx.__version__) != version.parse("1.5.0"): raise Exception("requires mxnet == 1.5.0") logging.set_verbosity_info() snake_case : Any = logging.get_logger(__name__) snake_case : Optional[int] = "The Nymphenburg Palace is a beautiful palace in Munich!" def lowerCAmelCase_ ( _snake_case : str , _snake_case : str ) -> Tuple: '''simple docstring''' __magic_name__ : int = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1E-5, "token_type_vocab_size": 2, } __magic_name__ : Any = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __magic_name__ : Tuple = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=_snake_case , output_all_encodings=_snake_case , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , _snake_case ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __magic_name__ : List[str] = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __magic_name__ : Optional[Any] = os.path.join(get_home_dir() , "models" ) __magic_name__ : Tuple = _load_vocab(_snake_case , _snake_case , _snake_case , cls=_snake_case ) __magic_name__ : Any = nlp.model.BERTModel( _snake_case , len(_snake_case ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=_snake_case , use_token_type_embed=_snake_case , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=_snake_case , use_decoder=_snake_case , ) original_bort.load_parameters(_snake_case , cast_dtype=_snake_case , ignore_extra=_snake_case ) __magic_name__ : str = original_bort._collect_params_with_prefix() # Build our config 🤗 __magic_name__ : List[str] = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(_snake_case ), } __magic_name__ : Any = BertConfig.from_dict(_snake_case ) __magic_name__ : Tuple = BertForMaskedLM(_snake_case ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(_snake_case : Any ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(_snake_case : int , _snake_case : Union[str, Any] ): __magic_name__ : Tuple = hf_param.shape __magic_name__ : str = to_torch(params[gluon_param] ) __magic_name__ : str = gluon_param.shape assert ( shape_hf == shape_gluon ), F'''The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers''' return gluon_param __magic_name__ : List[Any] = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __magic_name__ : Dict = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __magic_name__ : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __magic_name__ : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __magic_name__ : Any = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __magic_name__ : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __magic_name__ : BertSelfAttention = layer.attention.self __magic_name__ : str = check_and_map_params( self_attn.key.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_key.bias''' ) __magic_name__ : str = check_and_map_params( self_attn.key.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_key.weight''' ) __magic_name__ : Optional[Any] = check_and_map_params( self_attn.query.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_query.bias''' ) __magic_name__ : Optional[int] = check_and_map_params( self_attn.query.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_query.weight''' ) __magic_name__ : int = check_and_map_params( self_attn.value.bias.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_value.bias''' ) __magic_name__ : Optional[Any] = check_and_map_params( self_attn.value.weight.data , F'''encoder.transformer_cells.{i}.attention_cell.proj_value.weight''' ) # self attention output __magic_name__ : BertSelfOutput = layer.attention.output __magic_name__ : Any = check_and_map_params( self_output.dense.bias , F'''encoder.transformer_cells.{i}.proj.bias''' ) __magic_name__ : int = check_and_map_params( self_output.dense.weight , F'''encoder.transformer_cells.{i}.proj.weight''' ) __magic_name__ : Union[str, Any] = check_and_map_params( self_output.LayerNorm.bias , F'''encoder.transformer_cells.{i}.layer_norm.beta''' ) __magic_name__ : List[Any] = check_and_map_params( self_output.LayerNorm.weight , F'''encoder.transformer_cells.{i}.layer_norm.gamma''' ) # intermediate __magic_name__ : BertIntermediate = layer.intermediate __magic_name__ : Dict = check_and_map_params( intermediate.dense.bias , F'''encoder.transformer_cells.{i}.ffn.ffn_1.bias''' ) __magic_name__ : Tuple = check_and_map_params( intermediate.dense.weight , F'''encoder.transformer_cells.{i}.ffn.ffn_1.weight''' ) # output __magic_name__ : BertOutput = layer.output __magic_name__ : List[Any] = check_and_map_params( bert_output.dense.bias , F'''encoder.transformer_cells.{i}.ffn.ffn_2.bias''' ) __magic_name__ : Any = check_and_map_params( bert_output.dense.weight , F'''encoder.transformer_cells.{i}.ffn.ffn_2.weight''' ) __magic_name__ : List[Any] = check_and_map_params( bert_output.LayerNorm.bias , F'''encoder.transformer_cells.{i}.ffn.layer_norm.beta''' ) __magic_name__ : List[Any] = check_and_map_params( bert_output.LayerNorm.weight , F'''encoder.transformer_cells.{i}.ffn.layer_norm.gamma''' ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __magic_name__ : int = RobertaTokenizer.from_pretrained("roberta-base" ) __magic_name__ : Tuple = tokenizer.encode_plus(_snake_case )["input_ids"] # Get gluon output __magic_name__ : Any = mx.nd.array([input_ids] ) __magic_name__ : str = original_bort(inputs=_snake_case , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(_snake_case ) __magic_name__ : Dict = BertModel.from_pretrained(_snake_case ) hf_bort_model.eval() __magic_name__ : Optional[Any] = tokenizer.encode_plus(_snake_case , return_tensors="pt" ) __magic_name__ : str = hf_bort_model(**_snake_case )[0] __magic_name__ : Union[str, Any] = output_gluon[0].asnumpy() __magic_name__ : List[str] = output_hf[0].detach().numpy() __magic_name__ : Tuple = np.max(np.abs(hf_layer - gluon_layer ) ).item() __magic_name__ : Optional[int] = np.allclose(_snake_case , _snake_case , atol=1E-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , _snake_case ) if __name__ == "__main__": snake_case : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--bort_checkpoint_path", default=None, type=str, required=True, help="Path the official Bort params file." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) snake_case : int = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
281
from __future__ import annotations class _snake_case : def __init__( self , _a ): __magic_name__ : Optional[Any] = data __magic_name__ : Node | None = None __magic_name__ : Node | None = None def lowerCAmelCase_ ( _snake_case : Node | None ) -> None: # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_ ( _snake_case : Node | None ) -> int: '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_ ( _snake_case : Node ) -> bool: '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_ ( ) -> None: # Main function for testing. '''simple docstring''' __magic_name__ : int = Node(1 ) __magic_name__ : Union[str, Any] = Node(2 ) __magic_name__ : Tuple = Node(3 ) __magic_name__ : Optional[Any] = Node(4 ) __magic_name__ : Union[str, Any] = Node(5 ) __magic_name__ : Any = Node(6 ) __magic_name__ : int = Node(7 ) __magic_name__ : List[str] = Node(8 ) __magic_name__ : Union[str, Any] = Node(9 ) print(is_full_binary_tree(_snake_case ) ) print(depth_of_tree(_snake_case ) ) print("Tree is: " ) display(_snake_case ) if __name__ == "__main__": main()
281
1
import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCAmelCase_ ( _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : Optional[int] ) -> str: '''simple docstring''' if isinstance(_snake_case , torch.Tensor ): return image elif isinstance(_snake_case , PIL.Image.Image ): __magic_name__ : List[Any] = [image] if isinstance(image[0] , PIL.Image.Image ): __magic_name__ : Any = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] __magic_name__ : str = np.concatenate(_snake_case , axis=0 ) __magic_name__ : Tuple = np.array(_snake_case ).astype(np.floataa ) / 255.0 __magic_name__ : Optional[int] = image.transpose(0 , 3 , 1 , 2 ) __magic_name__ : List[str] = 2.0 * image - 1.0 __magic_name__ : Optional[int] = torch.from_numpy(_snake_case ) elif isinstance(image[0] , torch.Tensor ): __magic_name__ : Union[str, Any] = torch.cat(_snake_case , dim=0 ) return image def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Optional[int]=0.9_995 ) -> Union[str, Any]: '''simple docstring''' if not isinstance(_snake_case , np.ndarray ): __magic_name__ : List[str] = True __magic_name__ : Tuple = va.device __magic_name__ : int = va.cpu().numpy() __magic_name__ : Optional[Any] = va.cpu().numpy() __magic_name__ : Optional[Any] = np.sum(va * va / (np.linalg.norm(_snake_case ) * np.linalg.norm(_snake_case )) ) if np.abs(_snake_case ) > DOT_THRESHOLD: __magic_name__ : Optional[Any] = (1 - t) * va + t * va else: __magic_name__ : Tuple = np.arccos(_snake_case ) __magic_name__ : Tuple = np.sin(_snake_case ) __magic_name__ : List[Any] = theta_a * t __magic_name__ : Tuple = np.sin(_snake_case ) __magic_name__ : Dict = np.sin(theta_a - theta_t ) / sin_theta_a __magic_name__ : List[str] = sin_theta_t / sin_theta_a __magic_name__ : Tuple = sa * va + sa * va if inputs_are_torch: __magic_name__ : int = torch.from_numpy(_snake_case ).to(_snake_case ) return va def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : List[Any] ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Optional[Any] = F.normalize(_snake_case , dim=-1 ) __magic_name__ : Dict = F.normalize(_snake_case , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Optional[Any] ) -> Any: '''simple docstring''' for param in model.parameters(): __magic_name__ : int = value class _snake_case ( snake_case ): def __init__( self , _a , _a , _a , _a , _a , _a , _a , _a=None , _a=None , _a=None , ): super().__init__() self.register_modules( vae=_a , text_encoder=_a , clip_model=_a , tokenizer=_a , unet=_a , scheduler=_a , feature_extractor=_a , coca_model=_a , coca_tokenizer=_a , coca_transform=_a , ) __magic_name__ : str = ( feature_extractor.size if isinstance(feature_extractor.size , _a ) else feature_extractor.size["shortest_edge"] ) __magic_name__ : str = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , _a ) set_requires_grad(self.clip_model , _a ) def SCREAMING_SNAKE_CASE ( self , _a = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __magic_name__ : Dict = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(_a ) def SCREAMING_SNAKE_CASE ( self ): self.enable_attention_slicing(_a ) def SCREAMING_SNAKE_CASE ( self ): set_requires_grad(self.vae , _a ) def SCREAMING_SNAKE_CASE ( self ): set_requires_grad(self.vae , _a ) def SCREAMING_SNAKE_CASE ( self ): set_requires_grad(self.unet , _a ) def SCREAMING_SNAKE_CASE ( self ): set_requires_grad(self.unet , _a ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): # get the original timestep using init_timestep __magic_name__ : int = min(int(num_inference_steps * strength ) , _a ) __magic_name__ : Tuple = max(num_inference_steps - init_timestep , 0 ) __magic_name__ : Tuple = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a=None ): if not isinstance(_a , torch.Tensor ): raise ValueError(f'''`image` has to be of type `torch.Tensor` but is {type(_a )}''' ) __magic_name__ : Union[str, Any] = image.to(device=_a , dtype=_a ) if isinstance(_a , _a ): __magic_name__ : List[Any] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_a ) ] __magic_name__ : Tuple = torch.cat(_a , dim=0 ) else: __magic_name__ : Dict = self.vae.encode(_a ).latent_dist.sample(_a ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __magic_name__ : List[str] = 0.1_82_15 * init_latents __magic_name__ : List[Any] = init_latents.repeat_interleave(_a , dim=0 ) __magic_name__ : Tuple = randn_tensor(init_latents.shape , generator=_a , device=_a , dtype=_a ) # get latents __magic_name__ : List[str] = self.scheduler.add_noise(_a , _a , _a ) __magic_name__ : Optional[Any] = init_latents return latents def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : str = self.coca_transform(_a ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): __magic_name__ : Any = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) __magic_name__ : Tuple = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split("<end_of_text>" )[0].replace("<start_of_text>" , "" ).rstrip(" .," ) def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Tuple = self.feature_extractor.preprocess(_a ) __magic_name__ : List[str] = torch.from_numpy(clip_image_input["pixel_values"][0] ).unsqueeze(0 ).to(self.device ).half() __magic_name__ : List[str] = self.clip_model.get_image_features(_a ) __magic_name__ : List[Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __magic_name__ : Tuple = image_embeddings_clip.repeat_interleave(_a , dim=0 ) return image_embeddings_clip @torch.enable_grad() def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a , ): __magic_name__ : Optional[Any] = latents.detach().requires_grad_() __magic_name__ : List[str] = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __magic_name__ : Union[str, Any] = self.unet(_a , _a , encoder_hidden_states=_a ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): __magic_name__ : List[str] = self.scheduler.alphas_cumprod[timestep] __magic_name__ : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __magic_name__ : Tuple = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 __magic_name__ : int = torch.sqrt(_a ) __magic_name__ : Union[str, Any] = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , _a ): __magic_name__ : Union[str, Any] = self.scheduler.sigmas[index] __magic_name__ : Tuple = latents - sigma * noise_pred else: raise ValueError(f'''scheduler type {type(self.scheduler )} not supported''' ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __magic_name__ : Dict = 1 / 0.1_82_15 * sample __magic_name__ : Any = self.vae.decode(_a ).sample __magic_name__ : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) __magic_name__ : List[Any] = transforms.Resize(self.feature_extractor_size )(_a ) __magic_name__ : Any = self.normalize(_a ).to(latents.dtype ) __magic_name__ : Any = self.clip_model.get_image_features(_a ) __magic_name__ : List[Any] = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=_a ) __magic_name__ : Dict = spherical_dist_loss(_a , _a ).mean() * clip_guidance_scale __magic_name__ : Tuple = -torch.autograd.grad(_a , _a )[0] if isinstance(self.scheduler , _a ): __magic_name__ : Union[str, Any] = latents.detach() + grads * (sigma**2) __magic_name__ : Optional[Any] = noise_pred_original else: __magic_name__ : List[Any] = noise_pred_original - torch.sqrt(_a ) * grads return noise_pred, latents @torch.no_grad() def __call__( self , _a , _a , _a = None , _a = None , _a = 512 , _a = 512 , _a = 0.6 , _a = 50 , _a = 7.5 , _a = 1 , _a = 0.0 , _a = 100 , _a = None , _a = "pil" , _a = True , _a = 0.8 , _a = 0.1 , _a = 0.1 , ): if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError(f'''You have passed {batch_size} batch_size, but only {len(_a )} generators.''' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(f'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' ) if isinstance(_a , torch.Generator ) and batch_size > 1: __magic_name__ : Any = [generator] + [None] * (batch_size - 1) __magic_name__ : Optional[int] = [ ("model", self.coca_model is None), ("tokenizer", self.coca_tokenizer is None), ("transform", self.coca_transform is None), ] __magic_name__ : Optional[int] = [x[0] for x in coca_is_none if x[1]] __magic_name__ : Union[str, Any] = ", ".join(_a ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(_a ): raise ValueError( f'''Content prompt is None and CoCa [{coca_is_none_str}] is None.''' f'''Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __magic_name__ : Dict = self.get_image_description(_a ) if style_prompt is None: if len(_a ): raise ValueError( f'''Style prompt is None and CoCa [{coca_is_none_str}] is None.''' f''' Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.''' ) __magic_name__ : Dict = self.get_image_description(_a ) # get prompt text embeddings for content and style __magic_name__ : Tuple = self.tokenizer( _a , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors="pt" , ) __magic_name__ : Optional[Any] = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] __magic_name__ : str = self.tokenizer( _a , padding="max_length" , max_length=self.tokenizer.model_max_length , truncation=_a , return_tensors="pt" , ) __magic_name__ : List[str] = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] __magic_name__ : Optional[Any] = slerp(_a , _a , _a ) # duplicate text embeddings for each generation per prompt __magic_name__ : Union[str, Any] = text_embeddings.repeat_interleave(_a , dim=0 ) # set timesteps __magic_name__ : int = "offset" in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) __magic_name__ : Optional[int] = {} if accepts_offset: __magic_name__ : Optional[int] = 1 self.scheduler.set_timesteps(_a , **_a ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) __magic_name__ , __magic_name__ : Dict = self.get_timesteps(_a , _a , self.device ) __magic_name__ : str = timesteps[:1].repeat(_a ) # Preprocess image __magic_name__ : Tuple = preprocess(_a , _a , _a ) __magic_name__ : int = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __magic_name__ : Dict = preprocess(_a , _a , _a ) __magic_name__ : Dict = self.prepare_latents( _a , _a , _a , text_embeddings.dtype , self.device , _a ) __magic_name__ : Tuple = slerp(_a , _a , _a ) if clip_guidance_scale > 0: __magic_name__ : Union[str, Any] = self.get_clip_image_embeddings(_a , _a ) __magic_name__ : str = self.get_clip_image_embeddings(_a , _a ) __magic_name__ : Dict = slerp( _a , _a , _a ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. __magic_name__ : Tuple = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __magic_name__ : Optional[int] = content_text_input.input_ids.shape[-1] __magic_name__ : str = self.tokenizer([""] , padding="max_length" , max_length=_a , return_tensors="pt" ) __magic_name__ : Optional[int] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt __magic_name__ : Optional[int] = uncond_embeddings.repeat_interleave(_a , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __magic_name__ : int = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. __magic_name__ : List[Any] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) __magic_name__ : Optional[int] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps __magic_name__ : List[str] = torch.randn(_a , generator=_a , device="cpu" , dtype=_a ).to( self.device ) else: __magic_name__ : List[Any] = torch.randn(_a , generator=_a , device=self.device , dtype=_a ) else: if latents.shape != latents_shape: raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) __magic_name__ : Dict = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __magic_name__ : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __magic_name__ : Optional[int] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __magic_name__ : Optional[int] = {} if accepts_eta: __magic_name__ : str = eta # check if the scheduler accepts generator __magic_name__ : str = "generator" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: __magic_name__ : List[Any] = generator with self.progress_bar(total=_a ): for i, t in enumerate(_a ): # expand the latents if we are doing classifier free guidance __magic_name__ : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __magic_name__ : List[str] = self.scheduler.scale_model_input(_a , _a ) # predict the noise residual __magic_name__ : Dict = self.unet(_a , _a , encoder_hidden_states=_a ).sample # perform classifier free guidance if do_classifier_free_guidance: __magic_name__ , __magic_name__ : List[Any] = noise_pred.chunk(2 ) __magic_name__ : Optional[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: __magic_name__ : List[str] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) __magic_name__ , __magic_name__ : Tuple = self.cond_fn( _a , _a , _a , _a , _a , _a , _a , ) # compute the previous noisy sample x_t -> x_t-1 __magic_name__ : str = self.scheduler.step(_a , _a , _a , **_a ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor __magic_name__ : List[Any] = 1 / 0.1_82_15 * latents __magic_name__ : int = self.vae.decode(_a ).sample __magic_name__ : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) __magic_name__ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __magic_name__ : List[Any] = self.numpy_to_pil(_a ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=_a , nsfw_content_detected=_a )
281
def lowerCAmelCase_ ( _snake_case : str , _snake_case : str ) -> bool: '''simple docstring''' __magic_name__ : Union[str, Any] = len(_snake_case ) + 1 __magic_name__ : List[str] = len(_snake_case ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. __magic_name__ : str = [[0 for i in range(_snake_case )] for j in range(_snake_case )] # since string of zero length match pattern of zero length __magic_name__ : Optional[int] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , _snake_case ): __magic_name__ : Optional[int] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , _snake_case ): __magic_name__ : Union[str, Any] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , _snake_case ): for j in range(1 , _snake_case ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": __magic_name__ : Optional[int] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: __magic_name__ : Optional[Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): __magic_name__ : List[Any] = dp[i - 1][j] else: __magic_name__ : Union[str, Any] = 0 else: __magic_name__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") snake_case : Optional[Any] = "aab" snake_case : List[str] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F"{input_string} matches the given pattern {pattern}") else: print(F"{input_string} does not match with the given pattern {pattern}")
281
1
def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) or number < 0: raise ValueError("Input must be a non-negative integer" ) __magic_name__ : Union[str, Any] = 0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
281
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE ( *_a , **_a ): pass def lowerCAmelCase_ ( _snake_case : Image ) -> str: '''simple docstring''' __magic_name__ : Optional[int] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowerCAmelCase_ ( _snake_case : Image ) -> Dict: '''simple docstring''' __magic_name__ : List[Any] = np.array(_snake_case ) __magic_name__ : Optional[int] = npimg.shape return {"hash": hashimage(_snake_case ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _snake_case ( unittest.TestCase ): UpperCamelCase__ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase__ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): __magic_name__ : Dict = MaskGenerationPipeline(model=_a , image_processor=_a ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def SCREAMING_SNAKE_CASE ( self , _a , _a ): pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def SCREAMING_SNAKE_CASE ( self ): pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = pipeline("mask-generation" , model="facebook/sam-vit-huge" ) __magic_name__ : str = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Dict = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0_21}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, {"mask": {"hash": "e2d0b7a0b7", "shape": (480, 640)}, "scores": 0.99_67}, {"mask": {"hash": "453c7844bd", "shape": (480, 640)}, "scores": 0.9_93}, {"mask": {"hash": "3d44f2926d", "shape": (480, 640)}, "scores": 0.99_09}, {"mask": {"hash": "64033ddc3f", "shape": (480, 640)}, "scores": 0.98_79}, {"mask": {"hash": "801064ff79", "shape": (480, 640)}, "scores": 0.98_34}, {"mask": {"hash": "6172f276ef", "shape": (480, 640)}, "scores": 0.97_16}, {"mask": {"hash": "b49e60e084", "shape": (480, 640)}, "scores": 0.96_12}, {"mask": {"hash": "a811e775fd", "shape": (480, 640)}, "scores": 0.95_99}, {"mask": {"hash": "a6a8ebcf4b", "shape": (480, 640)}, "scores": 0.95_52}, {"mask": {"hash": "9d8257e080", "shape": (480, 640)}, "scores": 0.95_32}, {"mask": {"hash": "32de6454a8", "shape": (480, 640)}, "scores": 0.95_16}, {"mask": {"hash": "af3d4af2c8", "shape": (480, 640)}, "scores": 0.94_99}, {"mask": {"hash": "3c6db475fb", "shape": (480, 640)}, "scores": 0.94_83}, {"mask": {"hash": "c290813fb9", "shape": (480, 640)}, "scores": 0.94_64}, {"mask": {"hash": "b6f0b8f606", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "92ce16bfdf", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "c749b25868", "shape": (480, 640)}, "scores": 0.94_08}, {"mask": {"hash": "efb6cab859", "shape": (480, 640)}, "scores": 0.93_35}, {"mask": {"hash": "1ff2eafb30", "shape": (480, 640)}, "scores": 0.93_26}, {"mask": {"hash": "788b798e24", "shape": (480, 640)}, "scores": 0.92_62}, {"mask": {"hash": "abea804f0e", "shape": (480, 640)}, "scores": 0.89_99}, {"mask": {"hash": "7b9e8ddb73", "shape": (480, 640)}, "scores": 0.89_86}, {"mask": {"hash": "cd24047c8a", "shape": (480, 640)}, "scores": 0.89_84}, {"mask": {"hash": "6943e6bcbd", "shape": (480, 640)}, "scores": 0.88_73}, {"mask": {"hash": "b5f47c9191", "shape": (480, 640)}, "scores": 0.88_71} ] , ) # fmt: on @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : str = "facebook/sam-vit-huge" __magic_name__ : str = pipeline("mask-generation" , model=_a ) __magic_name__ : Tuple = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Any = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.02_10}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, ] , )
281
1
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( _snake_case : str = "laptop" ) -> DataFrame: '''simple docstring''' __magic_name__ : Tuple = F'''https://www.amazon.in/laptop/s?k={product}''' __magic_name__ : Dict = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } __magic_name__ : Tuple = BeautifulSoup(requests.get(_snake_case , headers=_snake_case ).text ) # Initialize a Pandas dataframe with the column titles __magic_name__ : int = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" , attrs={"class": "s-result-item", "data-component-type": "s-search-result"} , ) , soup.find_all("div" , attrs={"class": "a-row a-size-base a-color-base"} ) , ): try: __magic_name__ : Dict = item.ha.text __magic_name__ : Optional[int] = "https://www.amazon.in/" + item.ha.a["href"] __magic_name__ : Optional[Any] = item.find("span" , attrs={"class": "a-offscreen"} ).text try: __magic_name__ : Union[str, Any] = item.find("span" , attrs={"class": "a-icon-alt"} ).text except AttributeError: __magic_name__ : Dict = "Not available" try: __magic_name__ : Optional[int] = ( "₹" + item.find( "span" , attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: __magic_name__ : List[str] = "" try: __magic_name__ : int = float( ( ( float(product_mrp.strip("₹" ).replace("," , "" ) ) - float(product_price.strip("₹" ).replace("," , "" ) ) ) / float(product_mrp.strip("₹" ).replace("," , "" ) ) ) * 100 ) except ValueError: __magic_name__ : str = float("nan" ) except AttributeError: pass __magic_name__ : Optional[int] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __magic_name__ : Optional[Any] = " " __magic_name__ : str = " " data_frame.index += 1 return data_frame if __name__ == "__main__": snake_case : Any = "headphones" get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
281
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets snake_case : List[Any] = "\\n@inproceedings{lin-2004-rouge,\n title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",\n author = \"Lin, Chin-Yew\",\n booktitle = \"Text Summarization Branches Out\",\n month = jul,\n year = \"2004\",\n address = \"Barcelona, Spain\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W04-1013\",\n pages = \"74--81\",\n}\n" snake_case : Any = "\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n" snake_case : str = "\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n `\"rougeL\"`: Longest common subsequence based scoring.\n `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric('rouge')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n >>> print(results[\"rouge1\"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results[\"rouge1\"].mid.fmeasure)\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/google-research/google-research/tree/master/rouge"] , reference_urls=[ "https://en.wikipedia.org/wiki/ROUGE_(metric)", "https://github.com/google-research/google-research/tree/master/rouge", ] , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a=None , _a=True , _a=False ): if rouge_types is None: __magic_name__ : str = ["rouge1", "rouge2", "rougeL", "rougeLsum"] __magic_name__ : List[str] = rouge_scorer.RougeScorer(rouge_types=_a , use_stemmer=_a ) if use_aggregator: __magic_name__ : Dict = scoring.BootstrapAggregator() else: __magic_name__ : str = [] for ref, pred in zip(_a , _a ): __magic_name__ : Union[str, Any] = scorer.score(_a , _a ) if use_aggregator: aggregator.add_scores(_a ) else: scores.append(_a ) if use_aggregator: __magic_name__ : Any = aggregator.aggregate() else: __magic_name__ : List[Any] = {} for key in scores[0]: __magic_name__ : str = [score[key] for score in scores] return result
281
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available snake_case : Dict = { "configuration_biogpt": ["BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BioGptConfig"], "tokenization_biogpt": ["BioGptTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Optional[Any] = [ "BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST", "BioGptForCausalLM", "BioGptForTokenClassification", "BioGptForSequenceClassification", "BioGptModel", "BioGptPreTrainedModel", ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys snake_case : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
281
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
1
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = tempfile.mkdtemp() # fmt: off __magic_name__ : Optional[int] = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on __magic_name__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) __magic_name__ : Dict = { "do_resize": True, "size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5], } __magic_name__ : List[str] = os.path.join(self.tmpdirname , _a ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(_a , _a ) def SCREAMING_SNAKE_CASE ( self , **_a ): return BertTokenizer.from_pretrained(self.tmpdirname , **_a ) def SCREAMING_SNAKE_CASE ( self , **_a ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_a ) def SCREAMING_SNAKE_CASE ( self ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __magic_name__ : Tuple = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = self.get_tokenizer() __magic_name__ : Tuple = self.get_image_processor() __magic_name__ : Tuple = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) processor.save_pretrained(self.tmpdirname ) __magic_name__ : Tuple = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __magic_name__ : Union[str, Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __magic_name__ : str = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) __magic_name__ : Union[str, Any] = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = self.get_image_processor() __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : Tuple = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) __magic_name__ : List[str] = self.prepare_image_inputs() __magic_name__ : Any = image_processor(_a , return_tensors="np" ) __magic_name__ : Optional[int] = processor(images=_a , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = self.get_image_processor() __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : List[Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) __magic_name__ : int = "lower newer" __magic_name__ : List[Any] = processor(text=_a ) __magic_name__ : Any = tokenizer(_a ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = self.get_image_processor() __magic_name__ : List[Any] = self.get_tokenizer() __magic_name__ : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) __magic_name__ : int = "lower newer" __magic_name__ : Tuple = self.prepare_image_inputs() __magic_name__ : List[Any] = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with self.assertRaises(_a ): processor() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = self.get_image_processor() __magic_name__ : List[str] = self.get_tokenizer() __magic_name__ : List[Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) __magic_name__ : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __magic_name__ : Optional[int] = processor.batch_decode(_a ) __magic_name__ : Union[str, Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = self.get_image_processor() __magic_name__ : Optional[Any] = self.get_tokenizer() __magic_name__ : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_a , image_processor=_a ) __magic_name__ : Union[str, Any] = "lower newer" __magic_name__ : Union[str, Any] = self.prepare_image_inputs() __magic_name__ : Any = processor(text=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
281
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _snake_case ( unittest.TestCase ): def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ): __magic_name__ : List[Any] = parent __magic_name__ : Optional[Any] = batch_size __magic_name__ : Dict = seq_length __magic_name__ : Union[str, Any] = is_training __magic_name__ : Optional[Any] = use_attention_mask __magic_name__ : Optional[Any] = use_token_type_ids __magic_name__ : int = use_labels __magic_name__ : List[Any] = vocab_size __magic_name__ : Union[str, Any] = hidden_size __magic_name__ : Optional[Any] = num_hidden_layers __magic_name__ : int = num_attention_heads __magic_name__ : Any = intermediate_size __magic_name__ : List[Any] = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : List[Any] = max_position_embeddings __magic_name__ : Tuple = type_vocab_size __magic_name__ : List[str] = type_sequence_label_size __magic_name__ : Dict = initializer_range __magic_name__ : List[Any] = num_choices def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : List[Any] = None if self.use_attention_mask: __magic_name__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : str = None if self.use_token_type_ids: __magic_name__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : List[str] = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : List[Any] = config_and_inputs __magic_name__ : List[str] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = config_and_inputs __magic_name__ : Tuple = True __magic_name__ : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __magic_name__ : Optional[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 # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = FlaxRobertaPreLayerNormModelTester(self ) @slow def SCREAMING_SNAKE_CASE ( self ): for model_class_name in self.all_model_classes: __magic_name__ : Optional[Any] = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Union[str, Any] = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) __magic_name__ : List[str] = model(_a )[0] __magic_name__ : str = [1, 11, 50_265] self.assertEqual(list(output.shape ) , _a ) # compare the actual values for a slice. __magic_name__ : List[str] = np.array( [[[40.48_80, 18.01_99, -5.23_67], [-1.88_77, -4.08_85, 10.70_85], [-2.26_13, -5.61_10, 7.26_65]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Tuple = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) __magic_name__ : Tuple = model(_a )[0] # compare the actual values for a slice. __magic_name__ : Dict = np.array( [[[0.02_08, -0.03_56, 0.02_37], [-0.15_69, -0.04_11, -0.26_26], [0.18_79, 0.01_25, -0.00_89]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=1e-4 ) )
281
1
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device snake_case : int = False class _snake_case ( unittest.TestCase ): pass @slow @require_torch_gpu class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = VersatileDiffusionImageVariationPipeline.from_pretrained("shi-labs/versatile-diffusion" ) pipe.to(_a ) pipe.set_progress_bar_config(disable=_a ) __magic_name__ : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __magic_name__ : Optional[Any] = torch.manual_seed(0 ) __magic_name__ : int = pipe( image=_a , generator=_a , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images __magic_name__ : List[str] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __magic_name__ : Union[str, Any] = np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
281
def lowerCAmelCase_ ( _snake_case : list[list[int | float]] ) -> int: '''simple docstring''' __magic_name__ : Any = len(_snake_case ) __magic_name__ : Optional[Any] = len(matrix[0] ) __magic_name__ : Union[str, Any] = min(_snake_case , _snake_case ) for row in range(_snake_case ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , _snake_case ): __magic_name__ : Optional[Any] = matrix[col][row] / matrix[row][row] for i in range(_snake_case , _snake_case ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __magic_name__ : str = True for i in range(row + 1 , _snake_case ): if matrix[i][row] != 0: __magic_name__ , __magic_name__ : List[str] = matrix[i], matrix[row] __magic_name__ : Union[str, Any] = False break if reduce: rank -= 1 for i in range(_snake_case ): __magic_name__ : Any = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
281
1
from itertools import product def lowerCAmelCase_ ( _snake_case : int , _snake_case : int ) -> list[int]: '''simple docstring''' __magic_name__ : Tuple = sides_number __magic_name__ : Optional[int] = max_face_number * dice_number __magic_name__ : List[str] = [0] * (max_total + 1) __magic_name__ : Tuple = 1 __magic_name__ : Tuple = range(_snake_case , max_face_number + 1 ) for dice_numbers in product(_snake_case , repeat=_snake_case ): __magic_name__ : Union[str, Any] = sum(_snake_case ) totals_frequencies[total] += 1 return totals_frequencies def lowerCAmelCase_ ( ) -> float: '''simple docstring''' __magic_name__ : int = total_frequency_distribution( sides_number=4 , dice_number=9 ) __magic_name__ : Optional[int] = total_frequency_distribution( sides_number=6 , dice_number=6 ) __magic_name__ : List[str] = 0 __magic_name__ : Optional[int] = 9 __magic_name__ : Tuple = 4 * 9 __magic_name__ : int = 6 for peter_total in range(_snake_case , max_peter_total + 1 ): peter_wins_count += peter_totals_frequencies[peter_total] * sum( colin_totals_frequencies[min_colin_total:peter_total] ) __magic_name__ : Tuple = (4**9) * (6**6) __magic_name__ : Union[str, Any] = peter_wins_count / total_games_number __magic_name__ : Any = round(_snake_case , ndigits=7 ) return rounded_peter_win_probability if __name__ == "__main__": print(F"{solution() = }")
281
import argparse import collections import json import os import re import string import sys import numpy as np snake_case : Dict = re.compile(R"\b(a|an|the)\b", re.UNICODE) snake_case : Optional[int] = None def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=_snake_case , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=_snake_case , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Tuple: '''simple docstring''' __magic_name__ : Optional[int] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : str = bool(qa["answers"]["text"] ) return qid_to_has_ans def lowerCAmelCase_ ( _snake_case : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' def remove_articles(_snake_case : List[str] ): return ARTICLES_REGEX.sub(" " , _snake_case ) def white_space_fix(_snake_case : Optional[int] ): return " ".join(text.split() ) def remove_punc(_snake_case : Optional[int] ): __magic_name__ : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_snake_case : str ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_snake_case ) ) ) ) def lowerCAmelCase_ ( _snake_case : Any ) -> Optional[Any]: '''simple docstring''' if not s: return [] return normalize_answer(_snake_case ).split() def lowerCAmelCase_ ( _snake_case : str , _snake_case : Dict ) -> Tuple: '''simple docstring''' return int(normalize_answer(_snake_case ) == normalize_answer(_snake_case ) ) def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : int ) -> str: '''simple docstring''' __magic_name__ : Any = get_tokens(_snake_case ) __magic_name__ : Optional[int] = get_tokens(_snake_case ) __magic_name__ : Tuple = collections.Counter(_snake_case ) & collections.Counter(_snake_case ) __magic_name__ : Tuple = sum(common.values() ) if len(_snake_case ) == 0 or len(_snake_case ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __magic_name__ : Dict = 1.0 * num_same / len(_snake_case ) __magic_name__ : Optional[Any] = 1.0 * num_same / len(_snake_case ) __magic_name__ : List[Any] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = {} __magic_name__ : int = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : Union[str, Any] = qa["id"] __magic_name__ : Any = [t for t in qa["answers"]["text"] if normalize_answer(_snake_case )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __magic_name__ : Tuple = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue __magic_name__ : Any = preds[qid] # Take max over all gold answers __magic_name__ : List[Any] = max(compute_exact(_snake_case , _snake_case ) for a in gold_answers ) __magic_name__ : int = max(compute_fa(_snake_case , _snake_case ) for a in gold_answers ) return exact_scores, fa_scores def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : Optional[int] , _snake_case : Dict ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : str = {} for qid, s in scores.items(): __magic_name__ : Dict = na_probs[qid] > na_prob_thresh if pred_na: __magic_name__ : str = float(not qid_to_has_ans[qid] ) else: __magic_name__ : Optional[int] = s return new_scores def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : List[str] , _snake_case : Tuple=None ) -> Tuple: '''simple docstring''' if not qid_list: __magic_name__ : Any = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: __magic_name__ : Tuple = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : str , _snake_case : str ) -> Dict: '''simple docstring''' for k in new_eval: __magic_name__ : int = new_eval[k] def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : Optional[Any] , _snake_case : Union[str, Any] ) -> str: '''simple docstring''' plt.step(_snake_case , _snake_case , color="b" , alpha=0.2 , where="post" ) plt.fill_between(_snake_case , _snake_case , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(_snake_case ) plt.savefig(_snake_case ) plt.clf() def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Any , _snake_case : Optional[int] , _snake_case : List[Any] , _snake_case : Optional[int]=None , _snake_case : int=None ) -> str: '''simple docstring''' __magic_name__ : Union[str, Any] = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) __magic_name__ : Optional[int] = 0.0 __magic_name__ : str = 1.0 __magic_name__ : str = 0.0 __magic_name__ : List[str] = [1.0] __magic_name__ : str = [0.0] __magic_name__ : Optional[Any] = 0.0 for i, qid in enumerate(_snake_case ): if qid_to_has_ans[qid]: true_pos += scores[qid] __magic_name__ : List[str] = true_pos / float(i + 1 ) __magic_name__ : Any = true_pos / float(_snake_case ) if i == len(_snake_case ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_snake_case ) recalls.append(_snake_case ) if out_image: plot_pr_curve(_snake_case , _snake_case , _snake_case , _snake_case ) return {"ap": 100.0 * avg_prec} def lowerCAmelCase_ ( _snake_case : Tuple , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : Any , _snake_case : List[Any] ) -> Union[str, Any]: '''simple docstring''' if out_image_dir and not os.path.exists(_snake_case ): os.makedirs(_snake_case ) __magic_name__ : Any = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) __magic_name__ : Union[str, Any] = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) __magic_name__ : str = {k: float(_snake_case ) for k, v in qid_to_has_ans.items()} __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(_snake_case , _snake_case , "pr_exact" ) merge_eval(_snake_case , _snake_case , "pr_f1" ) merge_eval(_snake_case , _snake_case , "pr_oracle" ) def lowerCAmelCase_ ( _snake_case : int , _snake_case : Optional[Any] , _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' if not qid_list: return __magic_name__ : Dict = [na_probs[k] for k in qid_list] __magic_name__ : str = np.ones_like(_snake_case ) / float(len(_snake_case ) ) plt.hist(_snake_case , weights=_snake_case , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(_snake_case , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Tuple , _snake_case : List[str] , _snake_case : Dict ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __magic_name__ : List[str] = num_no_ans __magic_name__ : Dict = cur_score __magic_name__ : Dict = 0.0 __magic_name__ : Any = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) for i, qid in enumerate(_snake_case ): if qid not in scores: continue if qid_to_has_ans[qid]: __magic_name__ : Union[str, Any] = scores[qid] else: if preds[qid]: __magic_name__ : List[Any] = -1 else: __magic_name__ : Optional[int] = 0 cur_score += diff if cur_score > best_score: __magic_name__ : Optional[int] = cur_score __magic_name__ : List[Any] = na_probs[qid] return 100.0 * best_score / len(_snake_case ), best_thresh def lowerCAmelCase_ ( _snake_case : int , _snake_case : str , _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Dict ) -> Optional[Any]: '''simple docstring''' __magic_name__ , __magic_name__ : List[str] = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ , __magic_name__ : int = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ : Optional[int] = best_exact __magic_name__ : List[Any] = exact_thresh __magic_name__ : Dict = best_fa __magic_name__ : Any = fa_thresh def lowerCAmelCase_ ( ) -> int: '''simple docstring''' with open(OPTS.data_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) __magic_name__ : List[Any] = dataset_json["data"] with open(OPTS.pred_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __magic_name__ : Any = json.load(_snake_case ) else: __magic_name__ : Any = {k: 0.0 for k in preds} __magic_name__ : str = make_qid_to_has_ans(_snake_case ) # maps qid to True/False __magic_name__ : Tuple = [k for k, v in qid_to_has_ans.items() if v] __magic_name__ : Optional[Any] = [k for k, v in qid_to_has_ans.items() if not v] __magic_name__ , __magic_name__ : Union[str, Any] = get_raw_scores(_snake_case , _snake_case ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case ) if has_ans_qids: __magic_name__ : int = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "HasAns" ) if no_ans_qids: __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , OPTS.out_image_dir ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(_snake_case , _snake_case ) else: print(json.dumps(_snake_case , indent=2 ) ) if __name__ == "__main__": snake_case : int = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
281
1
import cva import numpy as np class _snake_case : def __init__( self , _a , _a ): if k in (0.04, 0.06): __magic_name__ : Optional[Any] = k __magic_name__ : Any = window_size else: raise ValueError("invalid k value" ) def __str__( self ): return str(self.k ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : List[str] = cva.imread(_a , 0 ) __magic_name__ , __magic_name__ : Union[str, Any] = img.shape __magic_name__ : list[list[int]] = [] __magic_name__ : Optional[int] = img.copy() __magic_name__ : Any = cva.cvtColor(_a , cva.COLOR_GRAY2RGB ) __magic_name__ , __magic_name__ : Tuple = np.gradient(_a ) __magic_name__ : Optional[int] = dx**2 __magic_name__ : List[str] = dy**2 __magic_name__ : List[str] = dx * dy __magic_name__ : Any = 0.04 __magic_name__ : List[str] = self.window_size // 2 for y in range(_a , h - offset ): for x in range(_a , w - offset ): __magic_name__ : List[str] = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __magic_name__ : Dict = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __magic_name__ : List[str] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() __magic_name__ : Dict = (wxx * wyy) - (wxy**2) __magic_name__ : int = wxx + wyy __magic_name__ : Tuple = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": snake_case : List[Any] = HarrisCorner(0.04, 3) snake_case ,snake_case : Optional[Any] = edge_detect.detect("path_to_image") cva.imwrite("detect.png", color_img)
281
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin snake_case : str = "▁" snake_case : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = BigBirdTokenizer UpperCamelCase__ = BigBirdTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def SCREAMING_SNAKE_CASE ( self ): super().setUp() __magic_name__ : Optional[Any] = self.tokenizer_class(_a , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = "<s>" __magic_name__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(_a ) , 1_004 ) def SCREAMING_SNAKE_CASE ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def SCREAMING_SNAKE_CASE ( self ): if not self.test_rust_tokenizer: return __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Any = "I was born in 92000, and this is falsé." __magic_name__ : Dict = tokenizer.tokenize(_a ) __magic_name__ : Any = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) __magic_name__ : List[Any] = tokenizer.encode(_a , add_special_tokens=_a ) __magic_name__ : List[str] = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Dict = tokenizer.encode(_a ) __magic_name__ : Optional[int] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = BigBirdTokenizer(_a , keep_accents=_a ) __magic_name__ : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [285, 46, 10, 170, 382] , ) __magic_name__ : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _a , [ 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", "é", ".", ] , ) __magic_name__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __magic_name__ : int = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ 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 ): return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = "Hello World!" __magic_name__ : Dict = [65, 18_536, 2_260, 101, 66] self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ( "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 __magic_name__ : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __magic_name__ : Optional[Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] __magic_name__ : List[Any] = " ".join(_a ) __magic_name__ : Any = self.big_tokenizer.encode_plus(_a , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : Union[str, Any] = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : List[str] = BigBirdConfig(attention_type="original_full" ) __magic_name__ : Optional[int] = BigBirdModel(_a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_a ) model(**_a ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) __magic_name__ : int = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def SCREAMING_SNAKE_CASE ( self ): # fmt: off __magic_name__ : Optional[Any] = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
281
1
import argparse import math import traceback import dateutil.parser as date_parser import requests def lowerCAmelCase_ ( _snake_case : Any ) -> List[Any]: '''simple docstring''' __magic_name__ : Dict = {} __magic_name__ : Tuple = job["started_at"] __magic_name__ : Optional[int] = job["completed_at"] __magic_name__ : str = date_parser.parse(_snake_case ) __magic_name__ : List[str] = date_parser.parse(_snake_case ) __magic_name__ : List[str] = round((end_datetime - start_datetime).total_seconds() / 60.0 ) __magic_name__ : Optional[Any] = start __magic_name__ : Union[str, Any] = end __magic_name__ : Optional[Any] = duration_in_min return job_info def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Optional[Any]=None ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : int = None if token is not None: __magic_name__ : List[str] = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} __magic_name__ : str = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __magic_name__ : List[str] = requests.get(_snake_case , headers=_snake_case ).json() __magic_name__ : int = {} try: job_time.update({job["name"]: extract_time_from_single_job(_snake_case ) for job in result["jobs"]} ) __magic_name__ : Any = math.ceil((result["total_count"] - 100) / 100 ) for i in range(_snake_case ): __magic_name__ : Union[str, Any] = requests.get(url + F'''&page={i + 2}''' , headers=_snake_case ).json() job_time.update({job["name"]: extract_time_from_single_job(_snake_case ) for job in result["jobs"]} ) return job_time except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": snake_case : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") snake_case : Dict = parser.parse_args() snake_case : Optional[int] = get_job_time(args.workflow_run_id) snake_case : int = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F"{k}: {v['duration']}")
281
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case : int = logging.get_logger(__name__) snake_case : List[str] = {"vocab_file": "spiece.model"} snake_case : List[str] = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } snake_case : Tuple = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } snake_case : List[str] = "▁" class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a=True , _a=True , _a=False , _a="[CLS]" , _a="[SEP]" , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , _a = None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __magic_name__ : str = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) __magic_name__ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) __magic_name__ : Dict = do_lower_case __magic_name__ : Tuple = remove_space __magic_name__ : Union[str, Any] = keep_accents __magic_name__ : Tuple = vocab_file __magic_name__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def SCREAMING_SNAKE_CASE ( self ): return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __magic_name__ : List[str] = self.__dict__.copy() __magic_name__ : Any = None return state def __setstate__( self , _a ): __magic_name__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __magic_name__ : str = {} __magic_name__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , _a ): if self.remove_space: __magic_name__ : List[Any] = " ".join(inputs.strip().split() ) else: __magic_name__ : str = inputs __magic_name__ : int = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: __magic_name__ : str = unicodedata.normalize("NFKD" , _a ) __magic_name__ : Tuple = "".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: __magic_name__ : int = outputs.lower() return outputs def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = self.preprocess_text(_a ) __magic_name__ : Dict = self.sp_model.encode(_a , out_type=_a ) __magic_name__ : Any = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): __magic_name__ : Optional[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __magic_name__ : List[str] = cur_pieces[1:] else: __magic_name__ : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.PieceToId(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.IdToPiece(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Any = [] __magic_name__ : Union[str, Any] = "" __magic_name__ : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token __magic_name__ : List[Any] = True __magic_name__ : Optional[int] = [] else: current_sub_tokens.append(_a ) __magic_name__ : Optional[Any] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : List[str] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[int] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : List[str] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , "wb" ) as fi: __magic_name__ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
281
1
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin snake_case : str = "▁" snake_case : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = BigBirdTokenizer UpperCamelCase__ = BigBirdTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def SCREAMING_SNAKE_CASE ( self ): super().setUp() __magic_name__ : Optional[Any] = self.tokenizer_class(_a , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = "<s>" __magic_name__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(_a ) , 1_004 ) def SCREAMING_SNAKE_CASE ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def SCREAMING_SNAKE_CASE ( self ): if not self.test_rust_tokenizer: return __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Any = "I was born in 92000, and this is falsé." __magic_name__ : Dict = tokenizer.tokenize(_a ) __magic_name__ : Any = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) __magic_name__ : List[Any] = tokenizer.encode(_a , add_special_tokens=_a ) __magic_name__ : List[str] = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Dict = tokenizer.encode(_a ) __magic_name__ : Optional[int] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = BigBirdTokenizer(_a , keep_accents=_a ) __magic_name__ : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [285, 46, 10, 170, 382] , ) __magic_name__ : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _a , [ 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", "é", ".", ] , ) __magic_name__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __magic_name__ : int = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ 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 ): return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = "Hello World!" __magic_name__ : Dict = [65, 18_536, 2_260, 101, 66] self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ( "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 __magic_name__ : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __magic_name__ : Optional[Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] __magic_name__ : List[Any] = " ".join(_a ) __magic_name__ : Any = self.big_tokenizer.encode_plus(_a , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : Union[str, Any] = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : List[str] = BigBirdConfig(attention_type="original_full" ) __magic_name__ : Optional[int] = BigBirdModel(_a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_a ) model(**_a ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) __magic_name__ : int = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def SCREAMING_SNAKE_CASE ( self ): # fmt: off __magic_name__ : Optional[Any] = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
281
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if isinstance(_snake_case , _snake_case ): __magic_name__ : Union[str, Any] = np.full((len(_snake_case ), sequence_length, 2) , _snake_case ) else: __magic_name__ : List[Any] = np.full((len(_snake_case ), sequence_length) , _snake_case ) for i, tensor in enumerate(_snake_case ): if padding_side == "right": if isinstance(_snake_case , _snake_case ): __magic_name__ : Optional[Any] = tensor[:sequence_length] else: __magic_name__ : Union[str, Any] = tensor[:sequence_length] else: if isinstance(_snake_case , _snake_case ): __magic_name__ : List[Any] = tensor[:sequence_length] else: __magic_name__ : Optional[Any] = tensor[:sequence_length] return out_tensor.tolist() def lowerCAmelCase_ ( _snake_case : Optional[int] ) -> Tuple: '''simple docstring''' __magic_name__ : Union[str, Any] = ord(_snake_case ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True __magic_name__ : Any = unicodedata.category(_snake_case ) if cat.startswith("P" ): return True return False @dataclass class _snake_case ( snake_case ): UpperCamelCase__ = 42 UpperCamelCase__ = True UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = -100 UpperCamelCase__ = "pt" def SCREAMING_SNAKE_CASE ( self , _a ): import torch __magic_name__ : List[str] = "label" if "label" in features[0].keys() else "labels" __magic_name__ : Union[str, Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __magic_name__ : Optional[int] = self.tokenizer.pad( _a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" if labels is None else None , ) if labels is None: return batch __magic_name__ : Dict = torch.tensor(batch["entity_ids"] ).shape[1] __magic_name__ : List[Any] = self.tokenizer.padding_side if padding_side == "right": __magic_name__ : str = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: __magic_name__ : int = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] __magic_name__ : Dict = [feature["ner_tags"] for feature in features] __magic_name__ : List[Any] = padding_tensor(_a , -1 , _a , _a ) __magic_name__ : Any = [feature["original_entity_spans"] for feature in features] __magic_name__ : Any = padding_tensor(_a , (-1, -1) , _a , _a ) __magic_name__ : List[Any] = {k: torch.tensor(_a , dtype=torch.intaa ) for k, v in batch.items()} return batch
281
1
from __future__ import annotations def lowerCAmelCase_ ( _snake_case : int ) -> bool: '''simple docstring''' __magic_name__ : List[Any] = str(_snake_case ) return len(_snake_case ) == 9 and set(_snake_case ) == set("123456789" ) def lowerCAmelCase_ ( ) -> int | None: '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __magic_name__ : int = 100002 * base_num if is_9_pandigital(_snake_case ): return candidate for base_num in range(333 , 99 , -1 ): __magic_name__ : Tuple = 1002003 * base_num if is_9_pandigital(_snake_case ): return candidate return None if __name__ == "__main__": print(F"{solution() = }")
281
import math def lowerCAmelCase_ ( _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' return math.pow(_snake_case , 2 ) - a def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' return 2 * x def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' __magic_name__ : Optional[int] = 2.0 while start <= a: __magic_name__ : str = math.pow(_snake_case , 2 ) return start def lowerCAmelCase_ ( _snake_case : float , _snake_case : int = 9999 , _snake_case : float = 0.00_000_000_000_001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) __magic_name__ : Optional[int] = get_initial_point(_snake_case ) for _ in range(_snake_case ): __magic_name__ : int = value __magic_name__ : str = value - fx(_snake_case , _snake_case ) / fx_derivative(_snake_case ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
281
1
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : List[Any] = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg" __magic_name__ : Optional[int] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ).convert("RGB" ) return image def lowerCAmelCase_ ( _snake_case : List[Any] ) -> List[str]: '''simple docstring''' __magic_name__ : str = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.embeddings.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.embeddings.layernorm.bias") ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : str , _snake_case : int , _snake_case : str ) -> Tuple: '''simple docstring''' __magic_name__ : str = dct.pop(_snake_case ) __magic_name__ : Any = val def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : int ) -> List[Any]: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __magic_name__ : Union[str, Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) __magic_name__ : Dict = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict __magic_name__ : List[Any] = torch.cat((q_bias, torch.zeros_like(_snake_case , requires_grad=_snake_case ), v_bias) ) __magic_name__ : Any = qkv_bias def lowerCAmelCase_ ( _snake_case : str ) -> Tuple: '''simple docstring''' __magic_name__ : int = 364 if "coco" in model_name else 224 __magic_name__ : Dict = InstructBlipVisionConfig(image_size=_snake_case ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: __magic_name__ : Any = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __magic_name__ : str = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: __magic_name__ : Union[str, Any] = LlamaConfig.from_pretrained("decapoda-research/llama-7b-hf" , vocab_size=32001 ).to_dict() elif "vicuna-13b" in model_name: __magic_name__ : List[Any] = LlamaConfig.from_pretrained("decapoda-research/llama-13b-hf" , vocab_size=32001 ).to_dict() else: raise ValueError("Model name not supported" ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 __magic_name__ : List[Any] = InstructBlipQFormerConfig(vocab_size=30523 ).to_dict() __magic_name__ : str = InstructBlipConfig(vision_config=_snake_case , text_config=_snake_case , qformer_config=_snake_case ) return config, image_size @torch.no_grad() def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Dict=None , _snake_case : Tuple=False ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = AutoTokenizer.from_pretrained("bert-base-uncased" , truncation_side="left" ) qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"} ) if "t5" in model_name: __magic_name__ : Optional[Any] = TaTokenizerFast.from_pretrained("google/flan-t5-xl" , truncation_side="left" ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) __magic_name__ : List[Any] = LlamaTokenizerFast.from_pretrained( "huggyllama/llama-7b" , truncation_side="left" , bos_token="</s>" , unk_token="</s>" ) tokenizer.add_special_tokens({"pad_token": "[PAD]"} ) __magic_name__ , __magic_name__ : Dict = get_blipa_config(_snake_case ) __magic_name__ : int = InstructBlipForConditionalGeneration(_snake_case ).eval() __magic_name__ : Optional[int] = { "instructblip-vicuna-7b": ("blip2_vicuna_instruct", "vicuna7b"), "instructblip-vicuna-13b": ("blip2_vicuna_instruct", "vicuna13b"), "instructblip-flan-t5-xl": ("blip2_t5_instruct", "flant5xl"), "instructblip-flan-t5-xxl": ("blip2_t5_instruct", "flant5xxl"), } __magic_name__ , __magic_name__ : List[Any] = model_name_to_original[model_name] # load original model print("Loading original model..." ) __magic_name__ : str = "cuda:1" if torch.cuda.is_available() else "cpu" __magic_name__ : Optional[int] = "cuda:2" if torch.cuda.is_available() else "cpu" __magic_name__ , __magic_name__ , __magic_name__ : List[str] = load_model_and_preprocess( name=_snake_case , model_type=_snake_case , is_eval=_snake_case , device=_snake_case ) original_model.eval() print("Done!" ) # update state dict keys __magic_name__ : str = original_model.state_dict() __magic_name__ : Optional[int] = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __magic_name__ : int = state_dict.pop(_snake_case ) if key.startswith("Qformer.bert" ): __magic_name__ : Dict = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: __magic_name__ : str = key.replace("self" , "attention" ) if "llm_proj" in key: __magic_name__ : int = key.replace("llm_proj" , "language_projection" ) if "t5_proj" in key: __magic_name__ : Dict = key.replace("t5_proj" , "language_projection" ) if key.startswith("llm_model" ): __magic_name__ : Optional[int] = key.replace("llm_model" , "language_model" ) if key.startswith("t5" ): __magic_name__ : Optional[int] = key.replace("t5" , "language" ) __magic_name__ : Union[str, Any] = val # read in qv biases read_in_q_v_bias(_snake_case , _snake_case ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(_snake_case , strict=_snake_case ) __magic_name__ : Union[str, Any] = load_demo_image() __magic_name__ : Tuple = "What is unusual about this image?" # create processor __magic_name__ : str = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=_snake_case , image_std=_snake_case ) __magic_name__ : Tuple = InstructBlipProcessor( image_processor=_snake_case , tokenizer=_snake_case , qformer_tokenizer=_snake_case , ) __magic_name__ : List[str] = processor(images=_snake_case , text=_snake_case , return_tensors="pt" ).to(_snake_case ) # make sure processor creates exact same pixel values __magic_name__ : List[Any] = vis_processors["eval"](_snake_case ).unsqueeze(0 ).to(_snake_case ) __magic_name__ : Optional[Any] = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , _snake_case ) original_model.to(_snake_case ) hf_model.to(_snake_case ) with torch.no_grad(): if "vicuna" in model_name: __magic_name__ : Tuple = original_model({"image": original_pixel_values, "text_input": [prompt]} ).logits __magic_name__ : List[Any] = hf_model(**_snake_case ).logits else: __magic_name__ : int = original_model( {"image": original_pixel_values, "text_input": [prompt], "text_output": ["\n"]} ).logits __magic_name__ : Dict = tokenizer("\n" , return_tensors="pt" ).input_ids.to(_snake_case ) __magic_name__ : Optional[Any] = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) __magic_name__ : Optional[Any] = hf_model(**_snake_case , labels=_snake_case ).logits print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape __magic_name__ : List[str] = 1E-4 if "vicuna" in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device ) , _snake_case , atol=_snake_case ) print("Looks ok!" ) print("Generating with original model..." ) __magic_name__ : Dict = original_model.generate({"image": original_pixel_values, "prompt": prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print("Generating with HF model..." ) __magic_name__ : Optional[int] = hf_model.generate( **_snake_case , do_sample=_snake_case , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? __magic_name__ : Tuple = 2 print("Original generation:" , _snake_case ) __magic_name__ : Dict = processor.batch_decode(_snake_case , skip_special_tokens=_snake_case ) __magic_name__ : List[str] = [text.strip() for text in output_text] print("HF generation:" , _snake_case ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_snake_case ) hf_model.save_pretrained(_snake_case ) if push_to_hub: processor.push_to_hub(F'''Salesforce/{model_name}''' ) hf_model.push_to_hub(F'''Salesforce/{model_name}''' ) if __name__ == "__main__": snake_case : Union[str, Any] = argparse.ArgumentParser() snake_case : Tuple = [ "instructblip-vicuna-7b", "instructblip-vicuna-13b", "instructblip-flan-t5-xl", "instructblip-flan-t5-xxl", ] parser.add_argument( "--model_name", default="instructblip-flan-t5-xl", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) snake_case : Optional[int] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class _snake_case : UpperCamelCase__ = LEDConfig UpperCamelCase__ = {} UpperCamelCase__ = 'gelu' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , _a=4 , ): __magic_name__ : int = parent __magic_name__ : Optional[int] = batch_size __magic_name__ : Tuple = seq_length __magic_name__ : List[Any] = is_training __magic_name__ : Dict = use_labels __magic_name__ : Optional[Any] = vocab_size __magic_name__ : int = hidden_size __magic_name__ : Optional[int] = num_hidden_layers __magic_name__ : Optional[int] = num_attention_heads __magic_name__ : Tuple = intermediate_size __magic_name__ : Any = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : List[str] = max_position_embeddings __magic_name__ : Any = eos_token_id __magic_name__ : str = pad_token_id __magic_name__ : int = bos_token_id __magic_name__ : Optional[int] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after __magic_name__ : Tuple = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests __magic_name__ : Tuple = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __magic_name__ : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __magic_name__ : int = tf.concat([input_ids, eos_tensor] , axis=1 ) __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) __magic_name__ : List[str] = prepare_led_inputs_dict(_a , _a , _a ) __magic_name__ : Union[str, Any] = tf.concat( [tf.zeros_like(_a )[:, :-1], tf.ones_like(_a )[:, -1:]] , axis=-1 , ) __magic_name__ : List[Any] = global_attention_mask return config, inputs_dict def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Dict = TFLEDModel(config=_a ).get_decoder() __magic_name__ : Optional[int] = inputs_dict["input_ids"] __magic_name__ : Union[str, Any] = input_ids[:1, :] __magic_name__ : str = inputs_dict["attention_mask"][:1, :] __magic_name__ : int = 1 # first forward pass __magic_name__ : Tuple = model(_a , attention_mask=_a , use_cache=_a ) __magic_name__ , __magic_name__ : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __magic_name__ : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __magic_name__ : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __magic_name__ : Optional[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) __magic_name__ : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __magic_name__ : List[str] = model(_a , attention_mask=_a )[0] __magic_name__ : Dict = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __magic_name__ : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __magic_name__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] __magic_name__ : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : List[Any] , _snake_case : Any , _snake_case : str=None , _snake_case : List[str]=None , _snake_case : int=None , _snake_case : Any=None , ) -> int: '''simple docstring''' if attention_mask is None: __magic_name__ : str = tf.cast(tf.math.not_equal(_snake_case , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __magic_name__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __magic_name__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __magic_name__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () UpperCamelCase__ = (TFLEDForConditionalGeneration,) if is_tf_available() else () UpperCamelCase__ = ( { 'conversational': TFLEDForConditionalGeneration, 'feature-extraction': TFLEDModel, 'summarization': TFLEDForConditionalGeneration, 'text2text-generation': TFLEDForConditionalGeneration, 'translation': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = TFLEDModelTester(self ) __magic_name__ : List[Any] = ConfigTester(self , config_class=_a ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ , __magic_name__ : int = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ : List[str] = tf.zeros_like(inputs_dict["attention_mask"] ) __magic_name__ : Optional[Any] = 2 __magic_name__ : Tuple = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) __magic_name__ : Any = True __magic_name__ : str = self.model_tester.seq_length __magic_name__ : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_a ): __magic_name__ : str = outputs.decoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_a ): __magic_name__ : Any = [t.numpy() for t in outputs.encoder_attentions] __magic_name__ : Tuple = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = False __magic_name__ : Tuple = False __magic_name__ : Optional[int] = model_class(_a ) __magic_name__ : str = model(self._prepare_for_class(_a , _a ) ) __magic_name__ : Any = len(_a ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) if self.is_encoder_decoder: __magic_name__ : Tuple = model_class(_a ) __magic_name__ : Optional[Any] = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_decoder_attentions_output(_a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __magic_name__ : Dict = True __magic_name__ : str = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) # Check attention is always last and order is fine __magic_name__ : Union[str, Any] = True __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) ) self.assertEqual(model.config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): # TODO: Head-masking not yet implement pass def lowerCAmelCase_ ( _snake_case : int ) -> Optional[int]: '''simple docstring''' return tf.constant(_snake_case , dtype=tf.intaa ) snake_case : Optional[int] = 1E-4 @slow @require_tf class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here __magic_name__ : Optional[int] = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : str = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Any = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : List[Any] = model(**_a )[0] __magic_name__ : List[str] = (1, 1_024, 768) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : int = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here __magic_name__ : int = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Tuple = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Optional[Any] = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : Union[str, Any] = model(**_a )[0] __magic_name__ : Optional[int] = (1, 1_024, model.config.vocab_size) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : str = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 , rtol=1e-3 )
281
1
from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class _snake_case : def __init__( self , _a , _a=12 , _a=7 , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=512 , _a=0.02 , _a=0 , _a=None , ): __magic_name__ : Dict = parent __magic_name__ : List[Any] = batch_size __magic_name__ : List[Any] = seq_length __magic_name__ : Tuple = is_training __magic_name__ : Union[str, Any] = use_input_mask __magic_name__ : int = use_labels __magic_name__ : Optional[int] = vocab_size __magic_name__ : Optional[Any] = hidden_size __magic_name__ : str = projection_dim __magic_name__ : str = num_hidden_layers __magic_name__ : Optional[int] = num_attention_heads __magic_name__ : Tuple = intermediate_size __magic_name__ : Any = dropout __magic_name__ : List[str] = attention_dropout __magic_name__ : Optional[int] = max_position_embeddings __magic_name__ : Optional[int] = initializer_range __magic_name__ : Tuple = scope __magic_name__ : Union[str, Any] = bos_token_id def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Optional[int] = None if self.use_input_mask: __magic_name__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: __magic_name__ : Optional[Any] = input_mask.numpy() __magic_name__ , __magic_name__ : Union[str, Any] = input_mask.shape __magic_name__ : int = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(_a ): __magic_name__ : Optional[Any] = 1 __magic_name__ : int = 0 __magic_name__ : int = self.get_config() return config, input_ids, tf.convert_to_tensor(_a ) def SCREAMING_SNAKE_CASE ( self ): return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): __magic_name__ : int = TFBlipTextModel(config=_a ) __magic_name__ : Optional[Any] = model(_a , attention_mask=_a , training=_a ) __magic_name__ : Union[str, Any] = model(_a , training=_a ) 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 SCREAMING_SNAKE_CASE ( self ): __magic_name__ : str = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ : List[str] = config_and_inputs __magic_name__ : int = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = (TFBlipTextModel,) if is_tf_available() else () UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = BlipTextModelTester(self ) __magic_name__ : Optional[int] = ConfigTester(self , config_class=_a , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): pass @unittest.skip(reason="Blip does not use inputs_embeds" ) def SCREAMING_SNAKE_CASE ( self ): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def SCREAMING_SNAKE_CASE ( self ): pass @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING" ) def SCREAMING_SNAKE_CASE ( self ): pass @slow def SCREAMING_SNAKE_CASE ( self ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Dict = TFBlipTextModel.from_pretrained(_a ) self.assertIsNotNone(_a ) def SCREAMING_SNAKE_CASE ( self , _a=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=_a )
281
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() snake_case : Optional[Any] = logging.get_logger(__name__) def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Union[str, Any]=False ) -> List[str]: '''simple docstring''' __magic_name__ : Union[str, Any] = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" __magic_name__ : int = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Any , _snake_case : Dict=False ) -> int: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: __magic_name__ : int = "" else: __magic_name__ : Union[str, Any] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __magic_name__ : Optional[Any] = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) __magic_name__ : int = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __magic_name__ : Dict = in_proj_weight[ : config.hidden_size, : ] __magic_name__ : List[str] = in_proj_bias[: config.hidden_size] __magic_name__ : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __magic_name__ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __magic_name__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] __magic_name__ : int = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( _snake_case : List[str] ) -> List[str]: '''simple docstring''' __magic_name__ : List[str] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : int , _snake_case : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __magic_name__ : int = dct.pop(_snake_case ) __magic_name__ : List[Any] = val def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" __magic_name__ : List[str] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Any , _snake_case : int=False ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=_snake_case , ) __magic_name__ : List[str] = ViTHybridConfig(backbone_config=_snake_case , image_size=384 , num_labels=1000 ) __magic_name__ : str = False # load original model from timm __magic_name__ : Union[str, Any] = timm.create_model(_snake_case , pretrained=_snake_case ) timm_model.eval() # load state_dict of original model, remove and rename some keys __magic_name__ : List[Any] = timm_model.state_dict() if base_model: remove_classification_head_(_snake_case ) __magic_name__ : Tuple = create_rename_keys(_snake_case , _snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) read_in_q_k_v(_snake_case , _snake_case , _snake_case ) __magic_name__ : List[str] = "huggingface/label-files" __magic_name__ : int = "imagenet-1k-id2label.json" __magic_name__ : Optional[int] = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type="dataset" ) , "r" ) ) __magic_name__ : int = {int(_snake_case ): v for k, v in idalabel.items()} __magic_name__ : List[str] = idalabel __magic_name__ : List[str] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": __magic_name__ : List[str] = ViTHybridModel(_snake_case ).eval() else: __magic_name__ : str = ViTHybridForImageClassification(_snake_case ).eval() model.load_state_dict(_snake_case ) # create image processor __magic_name__ : List[Any] = create_transform(**resolve_data_config({} , model=_snake_case ) ) __magic_name__ : int = transform.transforms __magic_name__ : List[str] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } __magic_name__ : int = ViTHybridImageProcessor( do_resize=_snake_case , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_snake_case , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_snake_case , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) __magic_name__ : List[Any] = prepare_img() __magic_name__ : Any = transform(_snake_case ).unsqueeze(0 ) __magic_name__ : Tuple = processor(_snake_case , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(_snake_case , _snake_case ) # verify logits with torch.no_grad(): __magic_name__ : Optional[int] = model(_snake_case ) __magic_name__ : List[str] = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: __magic_name__ : List[str] = timm_model.forward_features(_snake_case ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_snake_case , outputs.pooler_output , atol=1E-3 ) else: __magic_name__ : Any = timm_model(_snake_case ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_snake_case , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_snake_case ) if push_to_hub: print(F'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(F'''ybelkada/{vit_name}''' ) processor.push_to_hub(F'''ybelkada/{vit_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) snake_case : List[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
import argparse import collections import json import os import re import string import sys import numpy as np snake_case : Dict = re.compile(R"\b(a|an|the)\b", re.UNICODE) snake_case : Optional[int] = None def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=_snake_case , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=_snake_case , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Tuple: '''simple docstring''' __magic_name__ : Optional[int] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : str = bool(qa["answers"]["text"] ) return qid_to_has_ans def lowerCAmelCase_ ( _snake_case : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' def remove_articles(_snake_case : List[str] ): return ARTICLES_REGEX.sub(" " , _snake_case ) def white_space_fix(_snake_case : Optional[int] ): return " ".join(text.split() ) def remove_punc(_snake_case : Optional[int] ): __magic_name__ : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_snake_case : str ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_snake_case ) ) ) ) def lowerCAmelCase_ ( _snake_case : Any ) -> Optional[Any]: '''simple docstring''' if not s: return [] return normalize_answer(_snake_case ).split() def lowerCAmelCase_ ( _snake_case : str , _snake_case : Dict ) -> Tuple: '''simple docstring''' return int(normalize_answer(_snake_case ) == normalize_answer(_snake_case ) ) def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : int ) -> str: '''simple docstring''' __magic_name__ : Any = get_tokens(_snake_case ) __magic_name__ : Optional[int] = get_tokens(_snake_case ) __magic_name__ : Tuple = collections.Counter(_snake_case ) & collections.Counter(_snake_case ) __magic_name__ : Tuple = sum(common.values() ) if len(_snake_case ) == 0 or len(_snake_case ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __magic_name__ : Dict = 1.0 * num_same / len(_snake_case ) __magic_name__ : Optional[Any] = 1.0 * num_same / len(_snake_case ) __magic_name__ : List[Any] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = {} __magic_name__ : int = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : Union[str, Any] = qa["id"] __magic_name__ : Any = [t for t in qa["answers"]["text"] if normalize_answer(_snake_case )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __magic_name__ : Tuple = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue __magic_name__ : Any = preds[qid] # Take max over all gold answers __magic_name__ : List[Any] = max(compute_exact(_snake_case , _snake_case ) for a in gold_answers ) __magic_name__ : int = max(compute_fa(_snake_case , _snake_case ) for a in gold_answers ) return exact_scores, fa_scores def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : Optional[int] , _snake_case : Dict ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : str = {} for qid, s in scores.items(): __magic_name__ : Dict = na_probs[qid] > na_prob_thresh if pred_na: __magic_name__ : str = float(not qid_to_has_ans[qid] ) else: __magic_name__ : Optional[int] = s return new_scores def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : List[str] , _snake_case : Tuple=None ) -> Tuple: '''simple docstring''' if not qid_list: __magic_name__ : Any = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: __magic_name__ : Tuple = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : str , _snake_case : str ) -> Dict: '''simple docstring''' for k in new_eval: __magic_name__ : int = new_eval[k] def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : Optional[Any] , _snake_case : Union[str, Any] ) -> str: '''simple docstring''' plt.step(_snake_case , _snake_case , color="b" , alpha=0.2 , where="post" ) plt.fill_between(_snake_case , _snake_case , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(_snake_case ) plt.savefig(_snake_case ) plt.clf() def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Any , _snake_case : Optional[int] , _snake_case : List[Any] , _snake_case : Optional[int]=None , _snake_case : int=None ) -> str: '''simple docstring''' __magic_name__ : Union[str, Any] = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) __magic_name__ : Optional[int] = 0.0 __magic_name__ : str = 1.0 __magic_name__ : str = 0.0 __magic_name__ : List[str] = [1.0] __magic_name__ : str = [0.0] __magic_name__ : Optional[Any] = 0.0 for i, qid in enumerate(_snake_case ): if qid_to_has_ans[qid]: true_pos += scores[qid] __magic_name__ : List[str] = true_pos / float(i + 1 ) __magic_name__ : Any = true_pos / float(_snake_case ) if i == len(_snake_case ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_snake_case ) recalls.append(_snake_case ) if out_image: plot_pr_curve(_snake_case , _snake_case , _snake_case , _snake_case ) return {"ap": 100.0 * avg_prec} def lowerCAmelCase_ ( _snake_case : Tuple , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : Any , _snake_case : List[Any] ) -> Union[str, Any]: '''simple docstring''' if out_image_dir and not os.path.exists(_snake_case ): os.makedirs(_snake_case ) __magic_name__ : Any = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) __magic_name__ : Union[str, Any] = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) __magic_name__ : str = {k: float(_snake_case ) for k, v in qid_to_has_ans.items()} __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(_snake_case , _snake_case , "pr_exact" ) merge_eval(_snake_case , _snake_case , "pr_f1" ) merge_eval(_snake_case , _snake_case , "pr_oracle" ) def lowerCAmelCase_ ( _snake_case : int , _snake_case : Optional[Any] , _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' if not qid_list: return __magic_name__ : Dict = [na_probs[k] for k in qid_list] __magic_name__ : str = np.ones_like(_snake_case ) / float(len(_snake_case ) ) plt.hist(_snake_case , weights=_snake_case , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(_snake_case , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Tuple , _snake_case : List[str] , _snake_case : Dict ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __magic_name__ : List[str] = num_no_ans __magic_name__ : Dict = cur_score __magic_name__ : Dict = 0.0 __magic_name__ : Any = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) for i, qid in enumerate(_snake_case ): if qid not in scores: continue if qid_to_has_ans[qid]: __magic_name__ : Union[str, Any] = scores[qid] else: if preds[qid]: __magic_name__ : List[Any] = -1 else: __magic_name__ : Optional[int] = 0 cur_score += diff if cur_score > best_score: __magic_name__ : Optional[int] = cur_score __magic_name__ : List[Any] = na_probs[qid] return 100.0 * best_score / len(_snake_case ), best_thresh def lowerCAmelCase_ ( _snake_case : int , _snake_case : str , _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Dict ) -> Optional[Any]: '''simple docstring''' __magic_name__ , __magic_name__ : List[str] = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ , __magic_name__ : int = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ : Optional[int] = best_exact __magic_name__ : List[Any] = exact_thresh __magic_name__ : Dict = best_fa __magic_name__ : Any = fa_thresh def lowerCAmelCase_ ( ) -> int: '''simple docstring''' with open(OPTS.data_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) __magic_name__ : List[Any] = dataset_json["data"] with open(OPTS.pred_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __magic_name__ : Any = json.load(_snake_case ) else: __magic_name__ : Any = {k: 0.0 for k in preds} __magic_name__ : str = make_qid_to_has_ans(_snake_case ) # maps qid to True/False __magic_name__ : Tuple = [k for k, v in qid_to_has_ans.items() if v] __magic_name__ : Optional[Any] = [k for k, v in qid_to_has_ans.items() if not v] __magic_name__ , __magic_name__ : Union[str, Any] = get_raw_scores(_snake_case , _snake_case ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case ) if has_ans_qids: __magic_name__ : int = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "HasAns" ) if no_ans_qids: __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , OPTS.out_image_dir ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(_snake_case , _snake_case ) else: print(json.dumps(_snake_case , indent=2 ) ) if __name__ == "__main__": snake_case : int = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
281
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration snake_case : List[str] = "facebook/wmt19-en-de" snake_case : Dict = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model snake_case : List[str] = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) snake_case : int = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test snake_case : Optional[Any] = tokenizer(["Making tiny model"], return_tensors="pt") snake_case : List[str] = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save snake_case : Dict = "tiny-wmt19-en-de" tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-de
281
1
def lowerCAmelCase_ ( _snake_case : int = 1000000 ) -> int: '''simple docstring''' __magic_name__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , _snake_case ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
281
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Union[str, Any] ) -> Tuple: '''simple docstring''' __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' with open(_snake_case , encoding="utf_8" ) as f: __magic_name__ : List[str] = csv.reader(_snake_case ) __magic_name__ : List[Any] = [] next(_snake_case ) # skip the first line for line in tqdm(_snake_case ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( _snake_case : str , _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : Optional[int] ) -> int: '''simple docstring''' __magic_name__ : Optional[int] = [] for dataset in encoded_datasets: __magic_name__ : Union[str, Any] = len(_snake_case ) __magic_name__ : Dict = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __magic_name__ : List[str] = np.zeros((n_batch, 2) , dtype=np.intaa ) __magic_name__ : Optional[int] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __magic_name__ : int = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(_snake_case ): __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : str = with_conta __magic_name__ : Tuple = with_conta __magic_name__ : Union[str, Any] = len(_snake_case ) - 1 __magic_name__ : int = len(_snake_case ) - 1 __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[int] = mc_label __magic_name__ : str = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(_snake_case ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser() parser.add_argument("--model_name" , type=_snake_case , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=_snake_case , default="" ) parser.add_argument("--eval_dataset" , type=_snake_case , default="" ) parser.add_argument("--seed" , type=_snake_case , default=42 ) parser.add_argument("--num_train_epochs" , type=_snake_case , default=3 ) parser.add_argument("--train_batch_size" , type=_snake_case , default=8 ) parser.add_argument("--eval_batch_size" , type=_snake_case , default=16 ) parser.add_argument("--adam_epsilon" , default=1E-8 , type=_snake_case , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=_snake_case , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=_snake_case , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=_snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=_snake_case , default=6.25E-5 ) parser.add_argument("--warmup_steps" , default=0 , type=_snake_case , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=_snake_case , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=_snake_case , default=0.01 ) parser.add_argument("--lm_coef" , type=_snake_case , default=0.9 ) parser.add_argument("--n_valid" , type=_snake_case , default=374 ) parser.add_argument("--server_ip" , type=_snake_case , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=_snake_case , default="" , help="Can be used for distant debugging." ) __magic_name__ : List[Any] = parser.parse_args() print(_snake_case ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __magic_name__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) __magic_name__ : Optional[int] = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(_snake_case , _snake_case ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __magic_name__ : List[Any] = ["_start_", "_delimiter_", "_classify_"] __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(_snake_case ) __magic_name__ : Optional[Any] = tokenizer.convert_tokens_to_ids(_snake_case ) __magic_name__ : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(_snake_case ) ) model.to(_snake_case ) # Load and encode the datasets def tokenize_and_encode(_snake_case : str ): if isinstance(_snake_case , _snake_case ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case ) ) elif isinstance(_snake_case , _snake_case ): return obj return [tokenize_and_encode(_snake_case ) for o in obj] logger.info("Encoding dataset..." ) __magic_name__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) __magic_name__ : str = load_rocstories_dataset(args.eval_dataset ) __magic_name__ : int = (train_dataset, eval_dataset) __magic_name__ : List[str] = tokenize_and_encode(_snake_case ) # Compute the max input length for the Transformer __magic_name__ : Optional[Any] = model.config.n_positions // 2 - 2 __magic_name__ : Optional[int] = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __magic_name__ : List[str] = min(_snake_case , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __magic_name__ : List[Any] = pre_process_datasets(_snake_case , _snake_case , _snake_case , *_snake_case ) __magic_name__ , __magic_name__ : Optional[int] = tensor_datasets[0], tensor_datasets[1] __magic_name__ : Tuple = TensorDataset(*_snake_case ) __magic_name__ : Union[str, Any] = RandomSampler(_snake_case ) __magic_name__ : Dict = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.train_batch_size ) __magic_name__ : Any = TensorDataset(*_snake_case ) __magic_name__ : Optional[Any] = SequentialSampler(_snake_case ) __magic_name__ : int = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __magic_name__ : Tuple = args.max_steps __magic_name__ : List[str] = args.max_steps // (len(_snake_case ) // args.gradient_accumulation_steps) + 1 else: __magic_name__ : List[str] = len(_snake_case ) // args.gradient_accumulation_steps * args.num_train_epochs __magic_name__ : str = list(model.named_parameters() ) __magic_name__ : Dict = ["bias", "LayerNorm.bias", "LayerNorm.weight"] __magic_name__ : str = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] __magic_name__ : str = AdamW(_snake_case , lr=args.learning_rate , eps=args.adam_epsilon ) __magic_name__ : List[str] = get_linear_schedule_with_warmup( _snake_case , num_warmup_steps=args.warmup_steps , num_training_steps=_snake_case ) if args.do_train: __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): __magic_name__ : List[str] = 0 __magic_name__ : Tuple = 0 __magic_name__ : Dict = tqdm(_snake_case , desc="Training" ) for step, batch in enumerate(_snake_case ): __magic_name__ : Optional[Any] = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = batch __magic_name__ : Optional[Any] = model(_snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __magic_name__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __magic_name__ : int = "Training loss: {:.2e} lr: {:.2e}".format(_snake_case , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __magic_name__ : Dict = model.module if hasattr(_snake_case , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __magic_name__ : List[Any] = os.path.join(args.output_dir , _snake_case ) __magic_name__ : Dict = os.path.join(args.output_dir , _snake_case ) torch.save(model_to_save.state_dict() , _snake_case ) model_to_save.config.to_json_file(_snake_case ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __magic_name__ : Dict = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(_snake_case ) if args.do_eval: model.eval() __magic_name__ , __magic_name__ : Any = 0, 0 __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0 for batch in tqdm(_snake_case , desc="Evaluating" ): __magic_name__ : int = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = batch with torch.no_grad(): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = model( _snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Tuple = mc_logits.detach().cpu().numpy() __magic_name__ : Any = mc_labels.to("cpu" ).numpy() __magic_name__ : str = accuracy(_snake_case , _snake_case ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __magic_name__ : Tuple = eval_loss / nb_eval_steps __magic_name__ : List[Any] = eval_accuracy / nb_eval_examples __magic_name__ : int = tr_loss / nb_tr_steps if args.do_train else None __magic_name__ : Any = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} __magic_name__ : int = os.path.join(args.output_dir , "eval_results.txt" ) with open(_snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , _snake_case , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
281
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case : Dict = { "configuration_bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "processing_bridgetower": ["BridgeTowerProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Optional[int] = ["BridgeTowerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case : Union[str, Any] = [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForContrastiveLearning", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys snake_case : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
281
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
281
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput snake_case : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase_ ( _snake_case : Union[List, PIL.Image.Image, torch.Tensor] ) -> Optional[int]: '''simple docstring''' warnings.warn( "The preprocess method is deprecated and will be removed in a future version. Please" " use VaeImageProcessor.preprocess instead" , _snake_case , ) if isinstance(_snake_case , torch.Tensor ): return image elif isinstance(_snake_case , PIL.Image.Image ): __magic_name__ : Dict = [image] if isinstance(image[0] , PIL.Image.Image ): __magic_name__ , __magic_name__ : Optional[int] = image[0].size __magic_name__ , __magic_name__ : Dict = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 __magic_name__ : Optional[int] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) )[None, :] for i in image] __magic_name__ : Union[str, Any] = np.concatenate(_snake_case , axis=0 ) __magic_name__ : Any = np.array(_snake_case ).astype(np.floataa ) / 255.0 __magic_name__ : List[Any] = image.transpose(0 , 3 , 1 , 2 ) __magic_name__ : int = 2.0 * image - 1.0 __magic_name__ : int = torch.from_numpy(_snake_case ) elif isinstance(image[0] , torch.Tensor ): __magic_name__ : Tuple = torch.cat(_snake_case , dim=0 ) return image def lowerCAmelCase_ ( _snake_case : Union[List, PIL.Image.Image, torch.Tensor] ) -> Optional[Any]: '''simple docstring''' if isinstance(_snake_case , torch.Tensor ): return mask elif isinstance(_snake_case , PIL.Image.Image ): __magic_name__ : Any = [mask] if isinstance(mask[0] , PIL.Image.Image ): __magic_name__ , __magic_name__ : Optional[int] = mask[0].size __magic_name__ , __magic_name__ : List[Any] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 __magic_name__ : List[Any] = [np.array(m.convert("L" ).resize((w, h) , resample=PIL_INTERPOLATION["nearest"] ) )[None, :] for m in mask] __magic_name__ : Tuple = np.concatenate(_snake_case , axis=0 ) __magic_name__ : List[str] = mask.astype(np.floataa ) / 255.0 __magic_name__ : str = 0 __magic_name__ : Dict = 1 __magic_name__ : Optional[int] = torch.from_numpy(_snake_case ) elif isinstance(mask[0] , torch.Tensor ): __magic_name__ : List[str] = torch.cat(_snake_case , dim=0 ) return mask class _snake_case ( snake_case ): UpperCamelCase__ = 42 UpperCamelCase__ = 42 def __init__( self , _a , _a ): super().__init__() self.register_modules(unet=_a , scheduler=_a ) @torch.no_grad() def __call__( self , _a , _a , _a = 250 , _a = 0.0 , _a = 10 , _a = 10 , _a = None , _a = "pil" , _a = True , ): __magic_name__ : int = image __magic_name__ : Tuple = _preprocess_image(_a ) __magic_name__ : Dict = original_image.to(device=self.device , dtype=self.unet.dtype ) __magic_name__ : Union[str, Any] = _preprocess_mask(_a ) __magic_name__ : str = mask_image.to(device=self.device , dtype=self.unet.dtype ) __magic_name__ : Any = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(_a , _a ) and len(_a ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_a )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) __magic_name__ : int = original_image.shape __magic_name__ : List[Any] = randn_tensor(_a , generator=_a , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_a , _a , _a , self.device ) __magic_name__ : Optional[int] = eta __magic_name__ : Tuple = self.scheduler.timesteps[0] + 1 __magic_name__ : Dict = generator[0] if isinstance(_a , _a ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual __magic_name__ : Optional[int] = self.unet(_a , _a ).sample # compute previous image: x_t -> x_t-1 __magic_name__ : Optional[int] = self.scheduler.step(_a , _a , _a , _a , _a , _a ).prev_sample else: # compute the reverse: x_t-1 -> x_t __magic_name__ : List[Any] = self.scheduler.undo_step(_a , _a , _a ) __magic_name__ : Any = t __magic_name__ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) __magic_name__ : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __magic_name__ : str = self.numpy_to_pil(_a ) if not return_dict: return (image,) return ImagePipelineOutput(images=_a )
281
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCAmelCase_ ( _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Tuple: '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Dict = "mock-s3-bucket" __magic_name__ : Any = F'''s3://{mock_bucket}''' __magic_name__ : str = extract_path_from_uri(_snake_case ) assert dataset_path.startswith("s3://" ) is False __magic_name__ : Tuple = "./local/path" __magic_name__ : Optional[Any] = extract_path_from_uri(_snake_case ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' __magic_name__ : str = is_remote_filesystem(_snake_case ) assert is_remote is True __magic_name__ : Optional[int] = fsspec.filesystem("file" ) __magic_name__ : int = is_remote_filesystem(_snake_case ) assert is_remote is False @pytest.mark.parametrize("compression_fs_class" , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : int , _snake_case : Tuple , _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Any ) -> int: '''simple docstring''' __magic_name__ : Any = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file} __magic_name__ : str = input_paths[compression_fs_class.protocol] if input_path is None: __magic_name__ : Dict = F'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_snake_case ) __magic_name__ : str = fsspec.filesystem(compression_fs_class.protocol , fo=_snake_case ) assert isinstance(_snake_case , _snake_case ) __magic_name__ : int = os.path.basename(_snake_case ) __magic_name__ : Optional[int] = expected_filename[: expected_filename.rindex("." )] assert fs.glob("*" ) == [expected_filename] with fs.open(_snake_case , "r" , encoding="utf-8" ) as f, open(_snake_case , encoding="utf-8" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol" , ["zip", "gzip"] ) def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] ) -> str: '''simple docstring''' __magic_name__ : int = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} __magic_name__ : int = compressed_file_paths[protocol] __magic_name__ : Tuple = "dataset.jsonl" __magic_name__ : List[str] = F'''{protocol}://{member_file_path}::{compressed_file_path}''' __magic_name__ , *__magic_name__ : Optional[Any] = fsspec.get_fs_token_paths(_snake_case ) assert fs.isfile(_snake_case ) assert not fs.isfile("non_existing_" + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : List[str] , _snake_case : Tuple ) -> str: '''simple docstring''' __magic_name__ : int = hf_api.dataset_info(_snake_case , token=_snake_case ) __magic_name__ : Optional[Any] = HfFileSystem(repo_info=_snake_case , token=_snake_case ) assert sorted(hffs.glob("*" ) ) == [".gitattributes", "data"] assert hffs.isdir("data" ) assert hffs.isfile(".gitattributes" ) and hffs.isfile("data/text_data.txt" ) with open(_snake_case ) as f: assert hffs.open("data/text_data.txt" , "r" ).read() == f.read() def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' __magic_name__ : Optional[Any] = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_snake_case , _snake_case , clobber=_snake_case ) with pytest.warns(_snake_case ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_snake_case ) == 1 assert ( str(warning_info[0].message ) == F'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
281
1
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : List[str] = jnp.ones((batch_size, length) ) / length return scores def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = None __magic_name__ : Tuple = 20 __magic_name__ : Optional[int] = self._get_uniform_logits(batch_size=2 , length=_a ) # tweak scores to not be uniform anymore __magic_name__ : Optional[int] = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch __magic_name__ : Any = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax __magic_name__ : Optional[int] = jax.nn.softmax(_a , axis=-1 ) __magic_name__ : List[str] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __magic_name__ : List[Any] = FlaxTemperatureLogitsWarper(temperature=1.3 ) __magic_name__ : List[str] = jax.nn.softmax(temp_dist_warper_sharper(_a , scores.copy() , cur_len=_a ) , axis=-1 ) __magic_name__ : Optional[Any] = jax.nn.softmax(temp_dist_warper_smoother(_a , scores.copy() , cur_len=_a ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = None __magic_name__ : Optional[Any] = 10 __magic_name__ : Union[str, Any] = 2 # create ramp distribution __magic_name__ : List[Any] = np.broadcast_to(np.arange(_a )[None, :] , (batch_size, vocab_size) ).copy() __magic_name__ : Optional[Any] = ramp_logits[1:, : vocab_size // 2] + vocab_size __magic_name__ : List[Any] = FlaxTopKLogitsWarper(3 ) __magic_name__ : Optional[Any] = top_k_warp(_a , _a , cur_len=_a ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case __magic_name__ : Dict = 5 __magic_name__ : Optional[Any] = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) __magic_name__ : Dict = np.broadcast_to(np.arange(_a )[None, :] , (batch_size, length) ).copy() __magic_name__ : str = top_k_warp_safety_check(_a , _a , cur_len=_a ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = None __magic_name__ : Optional[Any] = 10 __magic_name__ : Optional[Any] = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) __magic_name__ : List[str] = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) __magic_name__ : Optional[Any] = FlaxTopPLogitsWarper(0.8 ) __magic_name__ : Dict = np.exp(top_p_warp(_a , _a , cur_len=_a ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 __magic_name__ : int = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(_a , _a , atol=1e-3 ) ) # check edge cases with negative and extreme logits __magic_name__ : Optional[Any] = np.broadcast_to(np.arange(_a )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme __magic_name__ : Optional[Any] = ramp_logits[1] * 1_00.0 # make sure at least 2 tokens are kept __magic_name__ : Union[str, Any] = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) __magic_name__ : str = top_p_warp(_a , _a , cur_len=_a ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = 20 __magic_name__ : List[Any] = 4 __magic_name__ : Dict = 0 __magic_name__ : Dict = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_a ) # check that min length is applied at length 5 __magic_name__ : Union[str, Any] = ids_tensor((batch_size, 20) , vocab_size=20 ) __magic_name__ : Any = 5 __magic_name__ : Tuple = self._get_uniform_logits(_a , _a ) __magic_name__ : Union[str, Any] = min_dist_processor(_a , _a , cur_len=_a ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("inf" )] ) # check that min length is not applied anymore at length 15 __magic_name__ : Dict = self._get_uniform_logits(_a , _a ) __magic_name__ : List[str] = 15 __magic_name__ : str = min_dist_processor(_a , _a , cur_len=_a ) self.assertFalse(jnp.isinf(_a ).any() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = 20 __magic_name__ : Any = 4 __magic_name__ : Union[str, Any] = 0 __magic_name__ : Tuple = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a ) # check that all scores are -inf except the bos_token_id score __magic_name__ : Optional[Any] = ids_tensor((batch_size, 1) , vocab_size=20 ) __magic_name__ : Optional[Any] = 1 __magic_name__ : List[str] = self._get_uniform_logits(_a , _a ) __magic_name__ : Optional[int] = logits_processor(_a , _a , cur_len=_a ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 __magic_name__ : Optional[int] = 3 __magic_name__ : List[Any] = self._get_uniform_logits(_a , _a ) __magic_name__ : List[Any] = logits_processor(_a , _a , cur_len=_a ) self.assertFalse(jnp.isinf(_a ).any() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = 20 __magic_name__ : Optional[Any] = 4 __magic_name__ : Any = 0 __magic_name__ : Optional[Any] = 5 __magic_name__ : Dict = FlaxForcedEOSTokenLogitsProcessor(max_length=_a , eos_token_id=_a ) # check that all scores are -inf except the eos_token_id when max_length is reached __magic_name__ : Optional[int] = ids_tensor((batch_size, 4) , vocab_size=20 ) __magic_name__ : List[Any] = 4 __magic_name__ : Optional[int] = self._get_uniform_logits(_a , _a ) __magic_name__ : List[Any] = logits_processor(_a , _a , cur_len=_a ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached __magic_name__ : List[str] = 3 __magic_name__ : Union[str, Any] = self._get_uniform_logits(_a , _a ) __magic_name__ : List[Any] = logits_processor(_a , _a , cur_len=_a ) self.assertFalse(jnp.isinf(_a ).any() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = 4 __magic_name__ : Optional[int] = 10 __magic_name__ : str = 15 __magic_name__ : Tuple = 2 __magic_name__ : int = 1 __magic_name__ : Dict = 15 # dummy input_ids and scores __magic_name__ : Optional[Any] = ids_tensor((batch_size, sequence_length) , _a ) __magic_name__ : Optional[Any] = input_ids.copy() __magic_name__ : Tuple = self._get_uniform_logits(_a , _a ) __magic_name__ : Dict = scores.copy() # instantiate all dist processors __magic_name__ : Union[str, Any] = FlaxTemperatureLogitsWarper(temperature=0.5 ) __magic_name__ : int = FlaxTopKLogitsWarper(3 ) __magic_name__ : List[Any] = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __magic_name__ : str = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_a ) __magic_name__ : Any = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a ) __magic_name__ : Optional[int] = FlaxForcedEOSTokenLogitsProcessor(max_length=_a , eos_token_id=_a ) __magic_name__ : Optional[int] = 10 # no processor list __magic_name__ : List[str] = temp_dist_warp(_a , _a , cur_len=_a ) __magic_name__ : str = top_k_warp(_a , _a , cur_len=_a ) __magic_name__ : Tuple = top_p_warp(_a , _a , cur_len=_a ) __magic_name__ : str = min_dist_proc(_a , _a , cur_len=_a ) __magic_name__ : Tuple = bos_dist_proc(_a , _a , cur_len=_a ) __magic_name__ : str = eos_dist_proc(_a , _a , cur_len=_a ) # with processor list __magic_name__ : List[str] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __magic_name__ : Tuple = processor(_a , _a , cur_len=_a ) # scores should be equal self.assertTrue(jnp.allclose(_a , _a , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = 4 __magic_name__ : Dict = 10 __magic_name__ : str = 15 __magic_name__ : List[Any] = 2 __magic_name__ : List[Any] = 1 __magic_name__ : Dict = 15 # dummy input_ids and scores __magic_name__ : List[str] = ids_tensor((batch_size, sequence_length) , _a ) __magic_name__ : int = input_ids.copy() __magic_name__ : Optional[int] = self._get_uniform_logits(_a , _a ) __magic_name__ : Optional[int] = scores.copy() # instantiate all dist processors __magic_name__ : Dict = FlaxTemperatureLogitsWarper(temperature=0.5 ) __magic_name__ : Optional[int] = FlaxTopKLogitsWarper(3 ) __magic_name__ : Dict = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors __magic_name__ : Optional[Any] = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=_a ) __magic_name__ : Optional[int] = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=_a ) __magic_name__ : Union[str, Any] = FlaxForcedEOSTokenLogitsProcessor(max_length=_a , eos_token_id=_a ) __magic_name__ : List[Any] = 10 # no processor list def run_no_processor_list(_a , _a , _a ): __magic_name__ : List[str] = temp_dist_warp(_a , _a , cur_len=_a ) __magic_name__ : int = top_k_warp(_a , _a , cur_len=_a ) __magic_name__ : Any = top_p_warp(_a , _a , cur_len=_a ) __magic_name__ : str = min_dist_proc(_a , _a , cur_len=_a ) __magic_name__ : List[str] = bos_dist_proc(_a , _a , cur_len=_a ) __magic_name__ : Optional[int] = eos_dist_proc(_a , _a , cur_len=_a ) return scores # with processor list def run_processor_list(_a , _a , _a ): __magic_name__ : Optional[int] = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) __magic_name__ : int = processor(_a , _a , cur_len=_a ) return scores __magic_name__ : Optional[int] = jax.jit(_a ) __magic_name__ : List[str] = jax.jit(_a ) __magic_name__ : Optional[Any] = jitted_run_no_processor_list(_a , _a , _a ) __magic_name__ : Tuple = jitted_run_processor_list(_a , _a , _a ) # scores should be equal self.assertTrue(jnp.allclose(_a , _a , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
281
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : List[Any] = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _snake_case ( snake_case ): UpperCamelCase__ = 'convbert' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=1 , _a=0 , _a=2 , _a=768 , _a=2 , _a=9 , _a=1 , _a=None , **_a , ): super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) __magic_name__ : Tuple = vocab_size __magic_name__ : List[Any] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : List[Any] = num_attention_heads __magic_name__ : str = intermediate_size __magic_name__ : Any = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : Tuple = max_position_embeddings __magic_name__ : str = type_vocab_size __magic_name__ : List[str] = initializer_range __magic_name__ : Tuple = layer_norm_eps __magic_name__ : List[Any] = embedding_size __magic_name__ : List[Any] = head_ratio __magic_name__ : str = conv_kernel_size __magic_name__ : Dict = num_groups __magic_name__ : str = classifier_dropout class _snake_case ( snake_case ): @property def SCREAMING_SNAKE_CASE ( self ): if self.task == "multiple-choice": __magic_name__ : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: __magic_name__ : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
281
1
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version snake_case : Any = get_logger(__name__) class _snake_case : UpperCamelCase__ = 'dummy_data' UpperCamelCase__ = 'datasets' UpperCamelCase__ = False def __init__( self , _a , _a , _a , _a = None , _a = False , _a = True , _a = None , ): __magic_name__ : Optional[Any] = 0 __magic_name__ : str = dataset_name __magic_name__ : List[Any] = cache_dir __magic_name__ : Optional[int] = use_local_dummy_data __magic_name__ : Union[str, Any] = config # download_callbacks take a single url as input __magic_name__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __magic_name__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __magic_name__ : Optional[int] = str(_a ) # to be downloaded __magic_name__ : int = None __magic_name__ : List[Any] = None @property def SCREAMING_SNAKE_CASE ( self ): if self._dummy_file is None: __magic_name__ : int = self.download_dummy_data() return self._dummy_file @property def SCREAMING_SNAKE_CASE ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def SCREAMING_SNAKE_CASE ( self ): return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __magic_name__ : List[str] = cached_path( _a , cache_dir=self.cache_dir , extract_compressed_file=_a , force_extract=_a ) return os.path.join(_a , self.dummy_file_name ) @property def SCREAMING_SNAKE_CASE ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def SCREAMING_SNAKE_CASE ( self ): if self._bucket_url is None: __magic_name__ : str = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def SCREAMING_SNAKE_CASE ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def SCREAMING_SNAKE_CASE ( self , _a , *_a ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __magic_name__ : Optional[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __magic_name__ : Any = self.dummy_file_name # special case when data_url is a dict if isinstance(_a , _a ): return self.create_dummy_data_dict(_a , _a ) elif isinstance(_a , (list, tuple) ): return self.create_dummy_data_list(_a , _a ) else: return self.create_dummy_data_single(_a , _a ) def SCREAMING_SNAKE_CASE ( self , _a , *_a ): return self.download_and_extract(_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a ): return self.download_and_extract(_a ) def SCREAMING_SNAKE_CASE ( self , _a , *_a , **_a ): return path def SCREAMING_SNAKE_CASE ( self ): return {} def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : str = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(_a , _a ): for single_url in single_urls: download_callback(_a ) else: __magic_name__ : List[str] = single_urls download_callback(_a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(_a , _a ): __magic_name__ : Dict = [os.path.join(_a , urllib.parse.quote_plus(Path(_a ).name ) ) for x in single_urls] else: __magic_name__ : str = single_urls __magic_name__ : List[str] = os.path.join(_a , urllib.parse.quote_plus(Path(_a ).name ) ) __magic_name__ : Optional[int] = value # make sure that values are unique if all(isinstance(_a , _a ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __magic_name__ : int = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Union[str, Any] = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __magic_name__ : Tuple = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , _a ) ) for url in data_url ) __magic_name__ : List[str] = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __magic_name__ : List[str] = [data_url[0]] * len(_a ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(_a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __magic_name__ : Optional[int] = os.path.join(_a , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(_a ) return dummy_data_list def SCREAMING_SNAKE_CASE ( self , _a , _a ): for download_callback in self.download_callbacks: download_callback(_a ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __magic_name__ : List[Any] = os.path.join(_a , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(_a ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self , _a ): def _iter_archive_members(_a ): # this preserves the order of the members inside the ZIP archive __magic_name__ : Optional[Any] = Path(self.dummy_file ).parent __magic_name__ : List[str] = path.relative_to(_a ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __magic_name__ : List[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(_a ) __magic_name__ : Dict = Path(_a ) __magic_name__ : int = _iter_archive_members(_a ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(_a ).as_posix(), file_path.open("rb" ) def SCREAMING_SNAKE_CASE ( self , _a ): if not isinstance(_a , _a ): __magic_name__ : Dict = [paths] for path in paths: if os.path.isfile(_a ): if os.path.basename(_a ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(_a ): if os.path.basename(_a ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(_a ): if filename.startswith((".", "__") ): continue yield os.path.join(_a , _a )
281
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCAmelCase_ ( ) -> str: '''simple docstring''' __magic_name__ : int = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" __magic_name__ : Union[str, Any] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ).convert("RGB" ) return image def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias") ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Optional[Any] ) -> int: '''simple docstring''' __magic_name__ : Tuple = dct.pop(_snake_case ) __magic_name__ : int = val def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __magic_name__ : List[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) __magic_name__ : Optional[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict __magic_name__ : Optional[int] = torch.cat((q_bias, torch.zeros_like(_snake_case , requires_grad=_snake_case ), v_bias) ) __magic_name__ : Union[str, Any] = qkv_bias def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : str ) -> int: '''simple docstring''' __magic_name__ : List[Any] = 364 if "coco" in model_name else 224 __magic_name__ : Union[str, Any] = BlipaVisionConfig(image_size=_snake_case ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: __magic_name__ : List[str] = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=_snake_case ).to_dict() elif "opt-6.7b" in model_name: __magic_name__ : Any = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=_snake_case ).to_dict() elif "t5-xl" in model_name: __magic_name__ : Dict = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __magic_name__ : int = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() __magic_name__ : List[Any] = BlipaConfig(vision_config=_snake_case , text_config=_snake_case ) return config, image_size @torch.no_grad() def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : str=None , _snake_case : Dict=False ) -> List[Any]: '''simple docstring''' __magic_name__ : Optional[int] = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) __magic_name__ : List[Any] = tokenizer("\n" , add_special_tokens=_snake_case ).input_ids[0] __magic_name__ , __magic_name__ : Tuple = get_blipa_config(_snake_case , eos_token_id=_snake_case ) __magic_name__ : Union[str, Any] = BlipaForConditionalGeneration(_snake_case ).eval() __magic_name__ : Any = { "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"), "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"), "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"), "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"), "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"), "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"), "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"), } __magic_name__ , __magic_name__ : Union[str, Any] = model_name_to_original[model_name] # load original model print("Loading original model..." ) __magic_name__ : Union[str, Any] = "cuda" if torch.cuda.is_available() else "cpu" __magic_name__ , __magic_name__ , __magic_name__ : Optional[Any] = load_model_and_preprocess( name=_snake_case , model_type=_snake_case , is_eval=_snake_case , device=_snake_case ) original_model.eval() print("Done!" ) # update state dict keys __magic_name__ : Dict = original_model.state_dict() __magic_name__ : str = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __magic_name__ : Any = state_dict.pop(_snake_case ) if key.startswith("Qformer.bert" ): __magic_name__ : Optional[int] = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: __magic_name__ : Any = key.replace("self" , "attention" ) if "opt_proj" in key: __magic_name__ : Union[str, Any] = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: __magic_name__ : Optional[int] = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): __magic_name__ : List[str] = key.replace("opt" , "language" ) if key.startswith("t5" ): __magic_name__ : Tuple = key.replace("t5" , "language" ) __magic_name__ : Dict = val # read in qv biases read_in_q_v_bias(_snake_case , _snake_case ) __magic_name__ , __magic_name__ : Tuple = hf_model.load_state_dict(_snake_case , strict=_snake_case ) assert len(_snake_case ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __magic_name__ : List[Any] = load_demo_image() __magic_name__ : Tuple = vis_processors["eval"](_snake_case ).unsqueeze(0 ).to(_snake_case ) __magic_name__ : Dict = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(_snake_case ) # create processor __magic_name__ : Optional[Any] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=_snake_case , image_std=_snake_case ) __magic_name__ : Dict = BlipaProcessor(image_processor=_snake_case , tokenizer=_snake_case ) __magic_name__ : Union[str, Any] = processor(images=_snake_case , return_tensors="pt" ).pixel_values.to(_snake_case ) # make sure processor creates exact same pixel values assert torch.allclose(_snake_case , _snake_case ) original_model.to(_snake_case ) hf_model.to(_snake_case ) with torch.no_grad(): if "opt" in model_name: __magic_name__ : List[Any] = original_model({"image": original_pixel_values, "text_input": [""]} ).logits __magic_name__ : Optional[int] = hf_model(_snake_case , _snake_case ).logits else: __magic_name__ : int = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits __magic_name__ : Tuple = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) __magic_name__ : List[str] = hf_model(_snake_case , _snake_case , labels=_snake_case ).logits assert original_logits.shape == logits.shape print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": __magic_name__ : List[str] = torch.tensor( [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]] , device=_snake_case ) assert torch.allclose(logits[0, :3, :3] , _snake_case , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": __magic_name__ : Tuple = torch.tensor( [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]] , device=_snake_case ) else: # cast to same type __magic_name__ : str = logits.dtype assert torch.allclose(original_logits.to(_snake_case ) , _snake_case , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) __magic_name__ : Optional[int] = "" __magic_name__ : Dict = tokenizer(_snake_case , return_tensors="pt" ).input_ids.to(_snake_case ) __magic_name__ : int = original_model.generate({"image": original_pixel_values} ) __magic_name__ : Optional[Any] = hf_model.generate( _snake_case , _snake_case , do_sample=_snake_case , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("Original generation:" , _snake_case ) __magic_name__ : Tuple = input_ids.shape[1] __magic_name__ : int = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=_snake_case ) __magic_name__ : Union[str, Any] = [text.strip() for text in output_text] print("HF generation:" , _snake_case ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_snake_case ) hf_model.save_pretrained(_snake_case ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() snake_case : Union[str, Any] = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) snake_case : int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss snake_case : int = pytest.mark.integration @require_faiss class _snake_case ( snake_case ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(_a ) for x in np.arange(30 ).tolist()]} ) return dset def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : Dataset = self._create_dummy_dataset() __magic_name__ : Dict = dset.map( lambda _a , _a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=_a , keep_in_memory=_a ) __magic_name__ : int = dset.add_faiss_index("vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) __magic_name__ , __magic_name__ : List[Any] = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) dset.drop_index("vecs" ) def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) __magic_name__ , __magic_name__ : Union[str, Any] = dset.get_nearest_examples("vecs" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: dset.save_faiss_index("vecs" , tmp_file.name ) dset.load_faiss_index("vecs2" , tmp_file.name ) os.unlink(tmp_file.name ) __magic_name__ , __magic_name__ : Optional[int] = dset.get_nearest_examples("vecs2" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(_a , partial(dset.get_nearest_examples , "vecs2" , np.ones(5 , dtype=np.floataa ) ) ) def SCREAMING_SNAKE_CASE ( self ): from elasticsearch import Elasticsearch __magic_name__ : Dataset = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __magic_name__ : Union[str, Any] = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) __magic_name__ : Any = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} __magic_name__ : Union[str, Any] = Elasticsearch() dset.add_elasticsearch_index("filename" , es_client=_a ) __magic_name__ , __magic_name__ : Tuple = dset.get_nearest_examples("filename" , "my_name-train_29" ) self.assertEqual(examples["filename"][0] , "my_name-train_29" ) @require_faiss class _snake_case ( snake_case ): def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query __magic_name__ : List[str] = np.zeros(5 , dtype=np.floataa ) __magic_name__ : Tuple = 1 __magic_name__ , __magic_name__ : str = index.search(_a ) self.assertRaises(_a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries __magic_name__ : List[Any] = np.eye(5 , dtype=np.floataa )[::-1] __magic_name__ , __magic_name__ : List[Any] = index.search_batch(_a ) self.assertRaises(_a , index.search_batch , queries[0] ) __magic_name__ : Optional[Any] = [scores[0] for scores in total_scores] __magic_name__ : Optional[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , _a ) def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : Dict = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) __magic_name__ : int = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(_a ): __magic_name__ : str = FaissIndex(string_factory="Flat" , custom_index=faiss.IndexFlat(5 ) ) def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : int = faiss.IndexFlat(5 ) __magic_name__ : Union[str, Any] = FaissIndex(custom_index=_a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def SCREAMING_SNAKE_CASE ( self ): import faiss __magic_name__ : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: index.save(tmp_file.name ) __magic_name__ : List[str] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __magic_name__ : Optional[Any] = np.zeros(5 , dtype=np.floataa ) __magic_name__ : Dict = 1 __magic_name__ , __magic_name__ : str = index.search(_a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def lowerCAmelCase_ ( _snake_case : int ) -> List[Any]: '''simple docstring''' import faiss __magic_name__ : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) __magic_name__ : List[str] = "index.faiss" __magic_name__ : Optional[int] = F'''mock://{index_name}''' index.save(_snake_case , storage_options=mockfs.storage_options ) __magic_name__ : List[str] = FaissIndex.load(_snake_case , storage_options=mockfs.storage_options ) __magic_name__ : int = np.zeros(5 , dtype=np.floataa ) __magic_name__ : Union[str, Any] = 1 __magic_name__ , __magic_name__ : int = index.search(_snake_case ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class _snake_case ( snake_case ): def SCREAMING_SNAKE_CASE ( self ): from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __magic_name__ : Tuple = Elasticsearch() __magic_name__ : str = {"acknowledged": True} __magic_name__ : List[Any] = ElasticSearchIndex(es_client=_a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query __magic_name__ : Optional[int] = "foo" __magic_name__ : List[Any] = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __magic_name__ , __magic_name__ : Union[str, Any] = index.search(_a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout __magic_name__ : Dict = "foo" __magic_name__ : int = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __magic_name__ , __magic_name__ : int = index.search(_a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries __magic_name__ : Any = ["foo", "bar", "foobar"] __magic_name__ : int = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __magic_name__ , __magic_name__ : List[str] = index.search_batch(_a ) __magic_name__ : Any = [scores[0] for scores in total_scores] __magic_name__ : List[Any] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a ) # batched queries with timeout __magic_name__ : List[Any] = ["foo", "bar", "foobar"] __magic_name__ : Union[str, Any] = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __magic_name__ , __magic_name__ : Optional[Any] = index.search_batch(_a , request_timeout=30 ) __magic_name__ : Optional[int] = [scores[0] for scores in total_scores] __magic_name__ : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a )
281
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : Union[str, Any] = { "vocab_file": "vocab.txt", "merges_file": "bpe.codes", } snake_case : Dict = { "vocab_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt", }, "merges_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes", }, } snake_case : Union[str, Any] = { "vinai/phobert-base": 256, "vinai/phobert-large": 256, } def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = set() __magic_name__ : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __magic_name__ : int = char __magic_name__ : List[str] = set(_snake_case ) return pairs class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , **_a , ): super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , **_a , ) __magic_name__ : Dict = vocab_file __magic_name__ : Tuple = merges_file __magic_name__ : List[Any] = {} __magic_name__ : List[Any] = 0 __magic_name__ : Tuple = 1 __magic_name__ : int = 2 __magic_name__ : Union[str, Any] = 3 self.add_from_file(_a ) __magic_name__ : Optional[int] = {v: k for k, v in self.encoder.items()} with open(_a , encoding="utf-8" ) as merges_handle: __magic_name__ : List[str] = merges_handle.read().split("\n" )[:-1] __magic_name__ : Union[str, Any] = [tuple(merge.split()[:-1] ) for merge in merges] __magic_name__ : Union[str, Any] = dict(zip(_a , range(len(_a ) ) ) ) __magic_name__ : Optional[int] = {} def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __magic_name__ : Optional[Any] = [self.cls_token_id] __magic_name__ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[Any] = [self.sep_token_id] __magic_name__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ): return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self , _a ): if token in self.cache: return self.cache[token] __magic_name__ : List[Any] = tuple(_a ) __magic_name__ : List[Any] = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) __magic_name__ : Any = get_pairs(_a ) if not pairs: return token while True: __magic_name__ : str = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __magic_name__ , __magic_name__ : List[str] = bigram __magic_name__ : List[str] = [] __magic_name__ : List[str] = 0 while i < len(_a ): try: __magic_name__ : Any = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __magic_name__ : Tuple = 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 __magic_name__ : Union[str, Any] = tuple(_a ) __magic_name__ : Optional[int] = new_word if len(_a ) == 1: break else: __magic_name__ : List[Any] = get_pairs(_a ) __magic_name__ : Optional[int] = "@@ ".join(_a ) __magic_name__ : Tuple = word[:-4] __magic_name__ : str = word return word def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = [] __magic_name__ : Dict = re.findall(r"\S+\n?" , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(" " ) ) ) return split_tokens def SCREAMING_SNAKE_CASE ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.decoder.get(_a , self.unk_token ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Tuple = " ".join(_a ).replace("@@ " , "" ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : Optional[int] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __magic_name__ : Union[str, Any] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) if os.path.abspath(self.merges_file ) != os.path.abspath(_a ): copyfile(self.merges_file , _a ) return out_vocab_file, out_merge_file def SCREAMING_SNAKE_CASE ( self , _a ): if isinstance(_a , _a ): try: with open(_a , "r" , encoding="utf-8" ) as fd: self.add_from_file(_a ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return __magic_name__ : List[Any] = f.readlines() for lineTmp in lines: __magic_name__ : Optional[Any] = lineTmp.strip() __magic_name__ : Union[str, Any] = line.rfind(" " ) if idx == -1: raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'" ) __magic_name__ : Optional[int] = line[:idx] __magic_name__ : Dict = len(self.encoder )
281
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. snake_case : Optional[int] = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def lowerCAmelCase_ ( _snake_case : Tuple ) -> Any: '''simple docstring''' config.addinivalue_line( "markers" , "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested" ) config.addinivalue_line( "markers" , "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested" ) config.addinivalue_line("markers" , "is_pipeline_test: mark test to run only when pipelines are tested" ) config.addinivalue_line("markers" , "is_staging_test: mark test to run only in the staging environment" ) config.addinivalue_line("markers" , "accelerate_tests: mark test that require accelerate" ) config.addinivalue_line("markers" , "tool_tests: mark the tool tests that are run on their specific schedule" ) def lowerCAmelCase_ ( _snake_case : List[str] ) -> Dict: '''simple docstring''' from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_snake_case ) def lowerCAmelCase_ ( _snake_case : Any ) -> str: '''simple docstring''' from transformers.testing_utils import pytest_terminal_summary_main __magic_name__ : Any = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(_snake_case , id=_snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : Tuple ) -> Optional[int]: '''simple docstring''' if exitstatus == 5: __magic_name__ : Dict = 0 # Doctest custom flag to ignore output. snake_case : Optional[int] = doctest.register_optionflag("IGNORE_RESULT") snake_case : Tuple = doctest.OutputChecker class _snake_case ( snake_case ): def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , _a , _a , _a ) snake_case : List[str] = CustomOutputChecker snake_case : Any = HfDoctestModule snake_case : Union[str, Any] = HfDocTestParser
281
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( _snake_case : str = "laptop" ) -> DataFrame: '''simple docstring''' __magic_name__ : Tuple = F'''https://www.amazon.in/laptop/s?k={product}''' __magic_name__ : Dict = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } __magic_name__ : Tuple = BeautifulSoup(requests.get(_snake_case , headers=_snake_case ).text ) # Initialize a Pandas dataframe with the column titles __magic_name__ : int = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" , attrs={"class": "s-result-item", "data-component-type": "s-search-result"} , ) , soup.find_all("div" , attrs={"class": "a-row a-size-base a-color-base"} ) , ): try: __magic_name__ : Dict = item.ha.text __magic_name__ : Optional[int] = "https://www.amazon.in/" + item.ha.a["href"] __magic_name__ : Optional[Any] = item.find("span" , attrs={"class": "a-offscreen"} ).text try: __magic_name__ : Union[str, Any] = item.find("span" , attrs={"class": "a-icon-alt"} ).text except AttributeError: __magic_name__ : Dict = "Not available" try: __magic_name__ : Optional[int] = ( "₹" + item.find( "span" , attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: __magic_name__ : List[str] = "" try: __magic_name__ : int = float( ( ( float(product_mrp.strip("₹" ).replace("," , "" ) ) - float(product_price.strip("₹" ).replace("," , "" ) ) ) / float(product_mrp.strip("₹" ).replace("," , "" ) ) ) * 100 ) except ValueError: __magic_name__ : str = float("nan" ) except AttributeError: pass __magic_name__ : Optional[int] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __magic_name__ : Optional[Any] = " " __magic_name__ : str = " " data_frame.index += 1 return data_frame if __name__ == "__main__": snake_case : Any = "headphones" get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
281
1
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class _snake_case : def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=False , _a=True , _a="None" , _a=3 , _a=4 , _a=None , ): __magic_name__ : Any = parent __magic_name__ : Dict = batch_size __magic_name__ : Tuple = seq_length __magic_name__ : str = is_training __magic_name__ : List[Any] = use_input_mask __magic_name__ : Union[str, Any] = use_token_type_ids __magic_name__ : List[str] = use_labels __magic_name__ : Union[str, Any] = vocab_size __magic_name__ : Tuple = hidden_size __magic_name__ : Any = num_hidden_layers __magic_name__ : int = num_attention_heads __magic_name__ : Tuple = intermediate_size __magic_name__ : Any = hidden_act __magic_name__ : Optional[int] = hidden_dropout_prob __magic_name__ : List[str] = attention_probs_dropout_prob __magic_name__ : Tuple = max_position_embeddings __magic_name__ : Union[str, Any] = type_vocab_size __magic_name__ : List[Any] = type_sequence_label_size __magic_name__ : Any = initializer_range __magic_name__ : List[str] = num_labels __magic_name__ : Union[str, Any] = num_choices __magic_name__ : Tuple = relative_attention __magic_name__ : Dict = position_biased_input __magic_name__ : List[Any] = pos_att_type __magic_name__ : Dict = scope def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Union[str, Any] = None if self.use_input_mask: __magic_name__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : Optional[int] = None if self.use_token_type_ids: __magic_name__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : Optional[int] = None __magic_name__ : Optional[int] = None __magic_name__ : int = None if self.use_labels: __magic_name__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ : int = DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=_a , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a ): __magic_name__ : List[Any] = TFDebertaVaModel(config=_a ) __magic_name__ : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __magic_name__ : Union[str, Any] = [input_ids, input_mask] __magic_name__ : Any = model(_a ) __magic_name__ : Optional[Any] = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a ): __magic_name__ : Any = TFDebertaVaForMaskedLM(config=_a ) __magic_name__ : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __magic_name__ : Dict = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a ): __magic_name__ : Optional[int] = self.num_labels __magic_name__ : str = TFDebertaVaForSequenceClassification(config=_a ) __magic_name__ : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __magic_name__ : str = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a ): __magic_name__ : Union[str, Any] = self.num_labels __magic_name__ : Optional[int] = TFDebertaVaForTokenClassification(config=_a ) __magic_name__ : Tuple = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __magic_name__ : str = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a , _a , _a ): __magic_name__ : Union[str, Any] = TFDebertaVaForQuestionAnswering(config=_a ) __magic_name__ : Optional[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __magic_name__ : Optional[Any] = model(_a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) : Tuple = config_and_inputs __magic_name__ : Optional[int] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) UpperCamelCase__ = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = TFDebertaVaModelTester(self ) __magic_name__ : List[Any] = ConfigTester(self , config_class=_a , hidden_size=37 ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) self.assertIsNotNone(_a ) @require_tf class _snake_case ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def SCREAMING_SNAKE_CASE ( self ): pass @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) __magic_name__ : str = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) __magic_name__ : int = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __magic_name__ : str = model(_a , attention_mask=_a )[0] __magic_name__ : Any = tf.constant( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , _a , atol=1e-4 )
281
from __future__ import annotations class _snake_case : def __init__( self , _a ): __magic_name__ : Optional[Any] = data __magic_name__ : Node | None = None __magic_name__ : Node | None = None def lowerCAmelCase_ ( _snake_case : Node | None ) -> None: # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_ ( _snake_case : Node | None ) -> int: '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_ ( _snake_case : Node ) -> bool: '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_ ( ) -> None: # Main function for testing. '''simple docstring''' __magic_name__ : int = Node(1 ) __magic_name__ : Union[str, Any] = Node(2 ) __magic_name__ : Tuple = Node(3 ) __magic_name__ : Optional[Any] = Node(4 ) __magic_name__ : Union[str, Any] = Node(5 ) __magic_name__ : Any = Node(6 ) __magic_name__ : int = Node(7 ) __magic_name__ : List[str] = Node(8 ) __magic_name__ : Union[str, Any] = Node(9 ) print(is_full_binary_tree(_snake_case ) ) print(depth_of_tree(_snake_case ) ) print("Tree is: " ) display(_snake_case ) if __name__ == "__main__": main()
281
1
from __future__ import annotations class _snake_case : def __init__( self , _a ): __magic_name__ : Optional[Any] = data __magic_name__ : Node | None = None __magic_name__ : Node | None = None def lowerCAmelCase_ ( _snake_case : Node | None ) -> None: # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_ ( _snake_case : Node | None ) -> int: '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_ ( _snake_case : Node ) -> bool: '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_ ( ) -> None: # Main function for testing. '''simple docstring''' __magic_name__ : int = Node(1 ) __magic_name__ : Union[str, Any] = Node(2 ) __magic_name__ : Tuple = Node(3 ) __magic_name__ : Optional[Any] = Node(4 ) __magic_name__ : Union[str, Any] = Node(5 ) __magic_name__ : Any = Node(6 ) __magic_name__ : int = Node(7 ) __magic_name__ : List[str] = Node(8 ) __magic_name__ : Union[str, Any] = Node(9 ) print(is_full_binary_tree(_snake_case ) ) print(depth_of_tree(_snake_case ) ) print("Tree is: " ) display(_snake_case ) if __name__ == "__main__": main()
281
def lowerCAmelCase_ ( _snake_case : str , _snake_case : str ) -> bool: '''simple docstring''' __magic_name__ : Union[str, Any] = len(_snake_case ) + 1 __magic_name__ : List[str] = len(_snake_case ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. __magic_name__ : str = [[0 for i in range(_snake_case )] for j in range(_snake_case )] # since string of zero length match pattern of zero length __magic_name__ : Optional[int] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , _snake_case ): __magic_name__ : Optional[int] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , _snake_case ): __magic_name__ : Union[str, Any] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , _snake_case ): for j in range(1 , _snake_case ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": __magic_name__ : Optional[int] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: __magic_name__ : Optional[Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): __magic_name__ : List[Any] = dp[i - 1][j] else: __magic_name__ : Union[str, Any] = 0 else: __magic_name__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") snake_case : Optional[Any] = "aab" snake_case : List[str] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F"{input_string} matches the given pattern {pattern}") else: print(F"{input_string} does not match with the given pattern {pattern}")
281
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case : Optional[Any] = logging.get_logger(__name__) snake_case : List[Any] = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class _snake_case ( snake_case ): UpperCamelCase__ = 'data2vec-vision' def __init__( self , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.0 , _a=0.0 , _a=0.02 , _a=1e-12 , _a=224 , _a=16 , _a=3 , _a=False , _a=False , _a=False , _a=False , _a=0.1 , _a=0.1 , _a=True , _a=[3, 5, 7, 11] , _a=[1, 2, 3, 6] , _a=True , _a=0.4 , _a=256 , _a=1 , _a=False , _a=255 , **_a , ): super().__init__(**_a ) __magic_name__ : Optional[int] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : List[str] = num_attention_heads __magic_name__ : int = intermediate_size __magic_name__ : Tuple = hidden_act __magic_name__ : str = hidden_dropout_prob __magic_name__ : Union[str, Any] = attention_probs_dropout_prob __magic_name__ : str = initializer_range __magic_name__ : Optional[Any] = layer_norm_eps __magic_name__ : Tuple = image_size __magic_name__ : str = patch_size __magic_name__ : Tuple = num_channels __magic_name__ : Optional[Any] = use_mask_token __magic_name__ : Any = use_absolute_position_embeddings __magic_name__ : Union[str, Any] = use_relative_position_bias __magic_name__ : str = use_shared_relative_position_bias __magic_name__ : Tuple = layer_scale_init_value __magic_name__ : List[str] = drop_path_rate __magic_name__ : Any = use_mean_pooling # decode head attributes (semantic segmentation) __magic_name__ : Tuple = out_indices __magic_name__ : int = pool_scales # auxiliary head attributes (semantic segmentation) __magic_name__ : str = use_auxiliary_head __magic_name__ : Union[str, Any] = auxiliary_loss_weight __magic_name__ : Optional[Any] = auxiliary_channels __magic_name__ : Dict = auxiliary_num_convs __magic_name__ : Optional[int] = auxiliary_concat_input __magic_name__ : Dict = semantic_loss_ignore_index class _snake_case ( snake_case ): UpperCamelCase__ = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE ( self ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def SCREAMING_SNAKE_CASE ( self ): return 1e-4
281
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE ( *_a , **_a ): pass def lowerCAmelCase_ ( _snake_case : Image ) -> str: '''simple docstring''' __magic_name__ : Optional[int] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowerCAmelCase_ ( _snake_case : Image ) -> Dict: '''simple docstring''' __magic_name__ : List[Any] = np.array(_snake_case ) __magic_name__ : Optional[int] = npimg.shape return {"hash": hashimage(_snake_case ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _snake_case ( unittest.TestCase ): UpperCamelCase__ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase__ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): __magic_name__ : Dict = MaskGenerationPipeline(model=_a , image_processor=_a ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def SCREAMING_SNAKE_CASE ( self , _a , _a ): pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def SCREAMING_SNAKE_CASE ( self ): pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = pipeline("mask-generation" , model="facebook/sam-vit-huge" ) __magic_name__ : str = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Dict = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0_21}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, {"mask": {"hash": "e2d0b7a0b7", "shape": (480, 640)}, "scores": 0.99_67}, {"mask": {"hash": "453c7844bd", "shape": (480, 640)}, "scores": 0.9_93}, {"mask": {"hash": "3d44f2926d", "shape": (480, 640)}, "scores": 0.99_09}, {"mask": {"hash": "64033ddc3f", "shape": (480, 640)}, "scores": 0.98_79}, {"mask": {"hash": "801064ff79", "shape": (480, 640)}, "scores": 0.98_34}, {"mask": {"hash": "6172f276ef", "shape": (480, 640)}, "scores": 0.97_16}, {"mask": {"hash": "b49e60e084", "shape": (480, 640)}, "scores": 0.96_12}, {"mask": {"hash": "a811e775fd", "shape": (480, 640)}, "scores": 0.95_99}, {"mask": {"hash": "a6a8ebcf4b", "shape": (480, 640)}, "scores": 0.95_52}, {"mask": {"hash": "9d8257e080", "shape": (480, 640)}, "scores": 0.95_32}, {"mask": {"hash": "32de6454a8", "shape": (480, 640)}, "scores": 0.95_16}, {"mask": {"hash": "af3d4af2c8", "shape": (480, 640)}, "scores": 0.94_99}, {"mask": {"hash": "3c6db475fb", "shape": (480, 640)}, "scores": 0.94_83}, {"mask": {"hash": "c290813fb9", "shape": (480, 640)}, "scores": 0.94_64}, {"mask": {"hash": "b6f0b8f606", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "92ce16bfdf", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "c749b25868", "shape": (480, 640)}, "scores": 0.94_08}, {"mask": {"hash": "efb6cab859", "shape": (480, 640)}, "scores": 0.93_35}, {"mask": {"hash": "1ff2eafb30", "shape": (480, 640)}, "scores": 0.93_26}, {"mask": {"hash": "788b798e24", "shape": (480, 640)}, "scores": 0.92_62}, {"mask": {"hash": "abea804f0e", "shape": (480, 640)}, "scores": 0.89_99}, {"mask": {"hash": "7b9e8ddb73", "shape": (480, 640)}, "scores": 0.89_86}, {"mask": {"hash": "cd24047c8a", "shape": (480, 640)}, "scores": 0.89_84}, {"mask": {"hash": "6943e6bcbd", "shape": (480, 640)}, "scores": 0.88_73}, {"mask": {"hash": "b5f47c9191", "shape": (480, 640)}, "scores": 0.88_71} ] , ) # fmt: on @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : str = "facebook/sam-vit-huge" __magic_name__ : str = pipeline("mask-generation" , model=_a ) __magic_name__ : Tuple = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Any = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.02_10}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, ] , )
281
1
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( "stable diffusion controlnet", "0.22.0", "Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.", standard_warn=False, stacklevel=3, )
281
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets snake_case : List[Any] = "\\n@inproceedings{lin-2004-rouge,\n title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",\n author = \"Lin, Chin-Yew\",\n booktitle = \"Text Summarization Branches Out\",\n month = jul,\n year = \"2004\",\n address = \"Barcelona, Spain\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W04-1013\",\n pages = \"74--81\",\n}\n" snake_case : Any = "\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n" snake_case : str = "\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n `\"rougeL\"`: Longest common subsequence based scoring.\n `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric('rouge')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n >>> print(results[\"rouge1\"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results[\"rouge1\"].mid.fmeasure)\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/google-research/google-research/tree/master/rouge"] , reference_urls=[ "https://en.wikipedia.org/wiki/ROUGE_(metric)", "https://github.com/google-research/google-research/tree/master/rouge", ] , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a=None , _a=True , _a=False ): if rouge_types is None: __magic_name__ : str = ["rouge1", "rouge2", "rougeL", "rougeLsum"] __magic_name__ : List[str] = rouge_scorer.RougeScorer(rouge_types=_a , use_stemmer=_a ) if use_aggregator: __magic_name__ : Dict = scoring.BootstrapAggregator() else: __magic_name__ : str = [] for ref, pred in zip(_a , _a ): __magic_name__ : Union[str, Any] = scorer.score(_a , _a ) if use_aggregator: aggregator.add_scores(_a ) else: scores.append(_a ) if use_aggregator: __magic_name__ : Any = aggregator.aggregate() else: __magic_name__ : List[Any] = {} for key in scores[0]: __magic_name__ : str = [score[key] for score in scores] return result
281
1
def lowerCAmelCase_ ( _snake_case : int , _snake_case : int ) -> int: '''simple docstring''' __magic_name__ : Dict = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): __magic_name__ : Any = n - k # Calculate C(n,k) for i in range(_snake_case ): result *= n - i result //= i + 1 return result def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' return binomial_coefficient(2 * node_count , _snake_case ) // (node_count + 1) def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' if n < 0: raise ValueError("factorial() not defined for negative values" ) __magic_name__ : Optional[Any] = 1 for i in range(1 , n + 1 ): result *= i return result def lowerCAmelCase_ ( _snake_case : int ) -> int: '''simple docstring''' return catalan_number(_snake_case ) * factorial(_snake_case ) if __name__ == "__main__": snake_case : Dict = int(input("Enter the number of nodes: ").strip() or 0) if node_count <= 0: raise ValueError("We need some nodes to work with.") print( F"Given {node_count} nodes, there are {binary_tree_count(node_count)} " F"binary trees and {catalan_number(node_count)} binary search trees." )
281
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
1
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node snake_case : Dict = 4 snake_case : Optional[int] = 3 class _snake_case ( snake_case ): pass def lowerCAmelCase_ ( _snake_case : List[str] ) -> Union[str, Any]: '''simple docstring''' for shard in shards: for i in range(_snake_case ): yield {"i": i, "shard": shard} def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Optional[int] = int(os.environ["RANK"] ) __magic_name__ : Union[str, Any] = int(os.environ["WORLD_SIZE"] ) __magic_name__ : Optional[int] = ArgumentParser() parser.add_argument("--streaming" , type=_snake_case ) parser.add_argument("--local_rank" , type=_snake_case ) parser.add_argument("--num_workers" , type=_snake_case , default=0 ) __magic_name__ : Tuple = parser.parse_args() __magic_name__ : Optional[Any] = args.streaming __magic_name__ : Any = args.num_workers __magic_name__ : Optional[int] = {"shards": [F'''shard_{shard_idx}''' for shard_idx in range(_snake_case )]} __magic_name__ : List[Any] = IterableDataset.from_generator(_snake_case , gen_kwargs=_snake_case ) if not streaming: __magic_name__ : Dict = Dataset.from_list(list(_snake_case ) ) __magic_name__ : List[str] = split_dataset_by_node(_snake_case , rank=_snake_case , world_size=_snake_case ) __magic_name__ : Optional[Any] = torch.utils.data.DataLoader(_snake_case , num_workers=_snake_case ) __magic_name__ : Optional[int] = NUM_SHARDS * NUM_ITEMS_PER_SHARD __magic_name__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) __magic_name__ : Optional[int] = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
281
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class _snake_case ( unittest.TestCase ): def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=True , _a=True , _a=True , _a=99 , _a=32 , _a=5 , _a=4 , _a=37 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=16 , _a=2 , _a=0.02 , _a=4 , ): __magic_name__ : List[Any] = parent __magic_name__ : Optional[Any] = batch_size __magic_name__ : Dict = seq_length __magic_name__ : Union[str, Any] = is_training __magic_name__ : Optional[Any] = use_attention_mask __magic_name__ : Optional[Any] = use_token_type_ids __magic_name__ : int = use_labels __magic_name__ : List[Any] = vocab_size __magic_name__ : Union[str, Any] = hidden_size __magic_name__ : Optional[Any] = num_hidden_layers __magic_name__ : int = num_attention_heads __magic_name__ : Any = intermediate_size __magic_name__ : List[Any] = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : List[Any] = max_position_embeddings __magic_name__ : Tuple = type_vocab_size __magic_name__ : List[str] = type_sequence_label_size __magic_name__ : Dict = initializer_range __magic_name__ : List[Any] = num_choices def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : List[Any] = None if self.use_attention_mask: __magic_name__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : str = None if self.use_token_type_ids: __magic_name__ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : List[str] = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : List[Any] = config_and_inputs __magic_name__ : List[str] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = config_and_inputs __magic_name__ : Tuple = True __magic_name__ : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __magic_name__ : Optional[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 # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = True UpperCamelCase__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = FlaxRobertaPreLayerNormModelTester(self ) @slow def SCREAMING_SNAKE_CASE ( self ): for model_class_name in self.all_model_classes: __magic_name__ : Optional[Any] = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(_a ) @require_flax class _snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Union[str, Any] = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) __magic_name__ : List[str] = model(_a )[0] __magic_name__ : str = [1, 11, 50_265] self.assertEqual(list(output.shape ) , _a ) # compare the actual values for a slice. __magic_name__ : List[str] = np.array( [[[40.48_80, 18.01_99, -5.23_67], [-1.88_77, -4.08_85, 10.70_85], [-2.26_13, -5.61_10, 7.26_65]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=_a ) __magic_name__ : Tuple = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) __magic_name__ : Tuple = model(_a )[0] # compare the actual values for a slice. __magic_name__ : Dict = np.array( [[[0.02_08, -0.03_56, 0.02_37], [-0.15_69, -0.04_11, -0.26_26], [0.18_79, 0.01_25, -0.00_89]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , _a , atol=1e-4 ) )
281
1
class _snake_case : def __init__( self , _a ): __magic_name__ : Tuple = size __magic_name__ : Union[str, Any] = [0] * size __magic_name__ : int = [0] * size @staticmethod def SCREAMING_SNAKE_CASE ( _a ): return index | (index + 1) @staticmethod def SCREAMING_SNAKE_CASE ( _a ): return (index & (index + 1)) - 1 def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : str = value while index < self.size: __magic_name__ : Optional[int] = self.get_prev(_a ) + 1 if current_left_border == index: __magic_name__ : str = value else: __magic_name__ : Optional[Any] = max(_a , _a , _a ) __magic_name__ : int = self.get_next(_a ) def SCREAMING_SNAKE_CASE ( self , _a , _a ): right -= 1 # Because of right is exclusive __magic_name__ : Any = 0 while left <= right: __magic_name__ : List[Any] = self.get_prev(_a ) if left <= current_left: __magic_name__ : Tuple = max(_a , self.tree[right] ) __magic_name__ : int = current_left else: __magic_name__ : Optional[Any] = max(_a , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
281
def lowerCAmelCase_ ( _snake_case : list[list[int | float]] ) -> int: '''simple docstring''' __magic_name__ : Any = len(_snake_case ) __magic_name__ : Optional[Any] = len(matrix[0] ) __magic_name__ : Union[str, Any] = min(_snake_case , _snake_case ) for row in range(_snake_case ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , _snake_case ): __magic_name__ : Optional[Any] = matrix[col][row] / matrix[row][row] for i in range(_snake_case , _snake_case ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __magic_name__ : str = True for i in range(row + 1 , _snake_case ): if matrix[i][row] != 0: __magic_name__ , __magic_name__ : List[str] = matrix[i], matrix[row] __magic_name__ : Union[str, Any] = False break if reduce: rank -= 1 for i in range(_snake_case ): __magic_name__ : Any = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
281
1
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Union[str, Any] ) -> Tuple: '''simple docstring''' __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' with open(_snake_case , encoding="utf_8" ) as f: __magic_name__ : List[str] = csv.reader(_snake_case ) __magic_name__ : List[Any] = [] next(_snake_case ) # skip the first line for line in tqdm(_snake_case ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( _snake_case : str , _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : Optional[int] ) -> int: '''simple docstring''' __magic_name__ : Optional[int] = [] for dataset in encoded_datasets: __magic_name__ : Union[str, Any] = len(_snake_case ) __magic_name__ : Dict = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __magic_name__ : List[str] = np.zeros((n_batch, 2) , dtype=np.intaa ) __magic_name__ : Optional[int] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __magic_name__ : int = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(_snake_case ): __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : str = with_conta __magic_name__ : Tuple = with_conta __magic_name__ : Union[str, Any] = len(_snake_case ) - 1 __magic_name__ : int = len(_snake_case ) - 1 __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[int] = mc_label __magic_name__ : str = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(_snake_case ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser() parser.add_argument("--model_name" , type=_snake_case , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=_snake_case , default="" ) parser.add_argument("--eval_dataset" , type=_snake_case , default="" ) parser.add_argument("--seed" , type=_snake_case , default=42 ) parser.add_argument("--num_train_epochs" , type=_snake_case , default=3 ) parser.add_argument("--train_batch_size" , type=_snake_case , default=8 ) parser.add_argument("--eval_batch_size" , type=_snake_case , default=16 ) parser.add_argument("--adam_epsilon" , default=1E-8 , type=_snake_case , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=_snake_case , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=_snake_case , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=_snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=_snake_case , default=6.25E-5 ) parser.add_argument("--warmup_steps" , default=0 , type=_snake_case , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=_snake_case , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=_snake_case , default=0.01 ) parser.add_argument("--lm_coef" , type=_snake_case , default=0.9 ) parser.add_argument("--n_valid" , type=_snake_case , default=374 ) parser.add_argument("--server_ip" , type=_snake_case , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=_snake_case , default="" , help="Can be used for distant debugging." ) __magic_name__ : List[Any] = parser.parse_args() print(_snake_case ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __magic_name__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) __magic_name__ : Optional[int] = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(_snake_case , _snake_case ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __magic_name__ : List[Any] = ["_start_", "_delimiter_", "_classify_"] __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(_snake_case ) __magic_name__ : Optional[Any] = tokenizer.convert_tokens_to_ids(_snake_case ) __magic_name__ : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(_snake_case ) ) model.to(_snake_case ) # Load and encode the datasets def tokenize_and_encode(_snake_case : str ): if isinstance(_snake_case , _snake_case ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case ) ) elif isinstance(_snake_case , _snake_case ): return obj return [tokenize_and_encode(_snake_case ) for o in obj] logger.info("Encoding dataset..." ) __magic_name__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) __magic_name__ : str = load_rocstories_dataset(args.eval_dataset ) __magic_name__ : int = (train_dataset, eval_dataset) __magic_name__ : List[str] = tokenize_and_encode(_snake_case ) # Compute the max input length for the Transformer __magic_name__ : Optional[Any] = model.config.n_positions // 2 - 2 __magic_name__ : Optional[int] = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __magic_name__ : List[str] = min(_snake_case , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __magic_name__ : List[Any] = pre_process_datasets(_snake_case , _snake_case , _snake_case , *_snake_case ) __magic_name__ , __magic_name__ : Optional[int] = tensor_datasets[0], tensor_datasets[1] __magic_name__ : Tuple = TensorDataset(*_snake_case ) __magic_name__ : Union[str, Any] = RandomSampler(_snake_case ) __magic_name__ : Dict = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.train_batch_size ) __magic_name__ : Any = TensorDataset(*_snake_case ) __magic_name__ : Optional[Any] = SequentialSampler(_snake_case ) __magic_name__ : int = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __magic_name__ : Tuple = args.max_steps __magic_name__ : List[str] = args.max_steps // (len(_snake_case ) // args.gradient_accumulation_steps) + 1 else: __magic_name__ : List[str] = len(_snake_case ) // args.gradient_accumulation_steps * args.num_train_epochs __magic_name__ : str = list(model.named_parameters() ) __magic_name__ : Dict = ["bias", "LayerNorm.bias", "LayerNorm.weight"] __magic_name__ : str = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] __magic_name__ : str = AdamW(_snake_case , lr=args.learning_rate , eps=args.adam_epsilon ) __magic_name__ : List[str] = get_linear_schedule_with_warmup( _snake_case , num_warmup_steps=args.warmup_steps , num_training_steps=_snake_case ) if args.do_train: __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): __magic_name__ : List[str] = 0 __magic_name__ : Tuple = 0 __magic_name__ : Dict = tqdm(_snake_case , desc="Training" ) for step, batch in enumerate(_snake_case ): __magic_name__ : Optional[Any] = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = batch __magic_name__ : Optional[Any] = model(_snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __magic_name__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __magic_name__ : int = "Training loss: {:.2e} lr: {:.2e}".format(_snake_case , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __magic_name__ : Dict = model.module if hasattr(_snake_case , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __magic_name__ : List[Any] = os.path.join(args.output_dir , _snake_case ) __magic_name__ : Dict = os.path.join(args.output_dir , _snake_case ) torch.save(model_to_save.state_dict() , _snake_case ) model_to_save.config.to_json_file(_snake_case ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __magic_name__ : Dict = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(_snake_case ) if args.do_eval: model.eval() __magic_name__ , __magic_name__ : Any = 0, 0 __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0 for batch in tqdm(_snake_case , desc="Evaluating" ): __magic_name__ : int = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = batch with torch.no_grad(): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = model( _snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Tuple = mc_logits.detach().cpu().numpy() __magic_name__ : Any = mc_labels.to("cpu" ).numpy() __magic_name__ : str = accuracy(_snake_case , _snake_case ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __magic_name__ : Tuple = eval_loss / nb_eval_steps __magic_name__ : List[Any] = eval_accuracy / nb_eval_examples __magic_name__ : int = tr_loss / nb_tr_steps if args.do_train else None __magic_name__ : Any = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} __magic_name__ : int = os.path.join(args.output_dir , "eval_results.txt" ) with open(_snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , _snake_case , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
281
import argparse import collections import json import os import re import string import sys import numpy as np snake_case : Dict = re.compile(R"\b(a|an|the)\b", re.UNICODE) snake_case : Optional[int] = None def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=_snake_case , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=_snake_case , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Tuple: '''simple docstring''' __magic_name__ : Optional[int] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : str = bool(qa["answers"]["text"] ) return qid_to_has_ans def lowerCAmelCase_ ( _snake_case : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' def remove_articles(_snake_case : List[str] ): return ARTICLES_REGEX.sub(" " , _snake_case ) def white_space_fix(_snake_case : Optional[int] ): return " ".join(text.split() ) def remove_punc(_snake_case : Optional[int] ): __magic_name__ : Dict = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_snake_case : str ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_snake_case ) ) ) ) def lowerCAmelCase_ ( _snake_case : Any ) -> Optional[Any]: '''simple docstring''' if not s: return [] return normalize_answer(_snake_case ).split() def lowerCAmelCase_ ( _snake_case : str , _snake_case : Dict ) -> Tuple: '''simple docstring''' return int(normalize_answer(_snake_case ) == normalize_answer(_snake_case ) ) def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : int ) -> str: '''simple docstring''' __magic_name__ : Any = get_tokens(_snake_case ) __magic_name__ : Optional[int] = get_tokens(_snake_case ) __magic_name__ : Tuple = collections.Counter(_snake_case ) & collections.Counter(_snake_case ) __magic_name__ : Tuple = sum(common.values() ) if len(_snake_case ) == 0 or len(_snake_case ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __magic_name__ : Dict = 1.0 * num_same / len(_snake_case ) __magic_name__ : Optional[Any] = 1.0 * num_same / len(_snake_case ) __magic_name__ : List[Any] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = {} __magic_name__ : int = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __magic_name__ : Union[str, Any] = qa["id"] __magic_name__ : Any = [t for t in qa["answers"]["text"] if normalize_answer(_snake_case )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __magic_name__ : Tuple = [""] if qid not in preds: print(F'''Missing prediction for {qid}''' ) continue __magic_name__ : Any = preds[qid] # Take max over all gold answers __magic_name__ : List[Any] = max(compute_exact(_snake_case , _snake_case ) for a in gold_answers ) __magic_name__ : int = max(compute_fa(_snake_case , _snake_case ) for a in gold_answers ) return exact_scores, fa_scores def lowerCAmelCase_ ( _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : Optional[int] , _snake_case : Dict ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : str = {} for qid, s in scores.items(): __magic_name__ : Dict = na_probs[qid] > na_prob_thresh if pred_na: __magic_name__ : str = float(not qid_to_has_ans[qid] ) else: __magic_name__ : Optional[int] = s return new_scores def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : List[str] , _snake_case : Tuple=None ) -> Tuple: '''simple docstring''' if not qid_list: __magic_name__ : Any = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: __magic_name__ : Tuple = len(_snake_case ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : str , _snake_case : str ) -> Dict: '''simple docstring''' for k in new_eval: __magic_name__ : int = new_eval[k] def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : Optional[Any] , _snake_case : Union[str, Any] ) -> str: '''simple docstring''' plt.step(_snake_case , _snake_case , color="b" , alpha=0.2 , where="post" ) plt.fill_between(_snake_case , _snake_case , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(_snake_case ) plt.savefig(_snake_case ) plt.clf() def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Any , _snake_case : Optional[int] , _snake_case : List[Any] , _snake_case : Optional[int]=None , _snake_case : int=None ) -> str: '''simple docstring''' __magic_name__ : Union[str, Any] = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) __magic_name__ : Optional[int] = 0.0 __magic_name__ : str = 1.0 __magic_name__ : str = 0.0 __magic_name__ : List[str] = [1.0] __magic_name__ : str = [0.0] __magic_name__ : Optional[Any] = 0.0 for i, qid in enumerate(_snake_case ): if qid_to_has_ans[qid]: true_pos += scores[qid] __magic_name__ : List[str] = true_pos / float(i + 1 ) __magic_name__ : Any = true_pos / float(_snake_case ) if i == len(_snake_case ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(_snake_case ) recalls.append(_snake_case ) if out_image: plot_pr_curve(_snake_case , _snake_case , _snake_case , _snake_case ) return {"ap": 100.0 * avg_prec} def lowerCAmelCase_ ( _snake_case : Tuple , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : Any , _snake_case : List[Any] ) -> Union[str, Any]: '''simple docstring''' if out_image_dir and not os.path.exists(_snake_case ): os.makedirs(_snake_case ) __magic_name__ : Any = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) __magic_name__ : Union[str, Any] = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) __magic_name__ : str = {k: float(_snake_case ) for k, v in qid_to_has_ans.items()} __magic_name__ : str = make_precision_recall_eval( _snake_case , _snake_case , _snake_case , _snake_case , out_image=os.path.join(_snake_case , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(_snake_case , _snake_case , "pr_exact" ) merge_eval(_snake_case , _snake_case , "pr_f1" ) merge_eval(_snake_case , _snake_case , "pr_oracle" ) def lowerCAmelCase_ ( _snake_case : int , _snake_case : Optional[Any] , _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' if not qid_list: return __magic_name__ : Dict = [na_probs[k] for k in qid_list] __magic_name__ : str = np.ones_like(_snake_case ) / float(len(_snake_case ) ) plt.hist(_snake_case , weights=_snake_case , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(F'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(_snake_case , F'''na_prob_hist_{name}.png''' ) ) plt.clf() def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Tuple , _snake_case : List[str] , _snake_case : Dict ) -> List[Any]: '''simple docstring''' __magic_name__ : Union[str, Any] = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __magic_name__ : List[str] = num_no_ans __magic_name__ : Dict = cur_score __magic_name__ : Dict = 0.0 __magic_name__ : Any = sorted(_snake_case , key=lambda _snake_case : na_probs[k] ) for i, qid in enumerate(_snake_case ): if qid not in scores: continue if qid_to_has_ans[qid]: __magic_name__ : Union[str, Any] = scores[qid] else: if preds[qid]: __magic_name__ : List[Any] = -1 else: __magic_name__ : Optional[int] = 0 cur_score += diff if cur_score > best_score: __magic_name__ : Optional[int] = cur_score __magic_name__ : List[Any] = na_probs[qid] return 100.0 * best_score / len(_snake_case ), best_thresh def lowerCAmelCase_ ( _snake_case : int , _snake_case : str , _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Dict ) -> Optional[Any]: '''simple docstring''' __magic_name__ , __magic_name__ : List[str] = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ , __magic_name__ : int = find_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case ) __magic_name__ : Optional[int] = best_exact __magic_name__ : List[Any] = exact_thresh __magic_name__ : Dict = best_fa __magic_name__ : Any = fa_thresh def lowerCAmelCase_ ( ) -> int: '''simple docstring''' with open(OPTS.data_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) __magic_name__ : List[Any] = dataset_json["data"] with open(OPTS.pred_file ) as f: __magic_name__ : Optional[Any] = json.load(_snake_case ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __magic_name__ : Any = json.load(_snake_case ) else: __magic_name__ : Any = {k: 0.0 for k in preds} __magic_name__ : str = make_qid_to_has_ans(_snake_case ) # maps qid to True/False __magic_name__ : Tuple = [k for k, v in qid_to_has_ans.items() if v] __magic_name__ : Optional[Any] = [k for k, v in qid_to_has_ans.items() if not v] __magic_name__ , __magic_name__ : Union[str, Any] = get_raw_scores(_snake_case , _snake_case ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : Optional[Any] = apply_no_ans_threshold(_snake_case , _snake_case , _snake_case , OPTS.na_prob_thresh ) __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case ) if has_ans_qids: __magic_name__ : int = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "HasAns" ) if no_ans_qids: __magic_name__ : List[Any] = make_eval_dict(_snake_case , _snake_case , qid_list=_snake_case ) merge_eval(_snake_case , _snake_case , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case , OPTS.out_image_dir ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(_snake_case , _snake_case , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(_snake_case , _snake_case ) else: print(json.dumps(_snake_case , indent=2 ) ) if __name__ == "__main__": snake_case : int = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
281
1
def lowerCAmelCase_ ( _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' return price * (1 + tax_rate) if __name__ == "__main__": print(F"{price_plus_tax(100, 0.25) = }") print(F"{price_plus_tax(1_25.50, 0.05) = }")
281
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin snake_case : str = "▁" snake_case : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = BigBirdTokenizer UpperCamelCase__ = BigBirdTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def SCREAMING_SNAKE_CASE ( self ): super().setUp() __magic_name__ : Optional[Any] = self.tokenizer_class(_a , keep_accents=_a ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = "<s>" __magic_name__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_a ) , _a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_a ) , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "[MASK]" ) self.assertEqual(len(_a ) , 1_004 ) def SCREAMING_SNAKE_CASE ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def SCREAMING_SNAKE_CASE ( self ): if not self.test_rust_tokenizer: return __magic_name__ : Dict = self.get_tokenizer() __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Any = "I was born in 92000, and this is falsé." __magic_name__ : Dict = tokenizer.tokenize(_a ) __magic_name__ : Any = rust_tokenizer.tokenize(_a ) self.assertListEqual(_a , _a ) __magic_name__ : List[Any] = tokenizer.encode(_a , add_special_tokens=_a ) __magic_name__ : List[str] = rust_tokenizer.encode(_a , add_special_tokens=_a ) self.assertListEqual(_a , _a ) __magic_name__ : str = self.get_rust_tokenizer() __magic_name__ : Dict = tokenizer.encode(_a ) __magic_name__ : Optional[int] = rust_tokenizer.encode(_a ) self.assertListEqual(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = BigBirdTokenizer(_a , keep_accents=_a ) __magic_name__ : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(_a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_a ) , [285, 46, 10, 170, 382] , ) __magic_name__ : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _a , [ 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", "é", ".", ] , ) __magic_name__ : Union[str, Any] = tokenizer.convert_tokens_to_ids(_a ) self.assertListEqual( _a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __magic_name__ : int = tokenizer.convert_ids_to_tokens(_a ) self.assertListEqual( _a , [ 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 ): return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = "Hello World!" __magic_name__ : Dict = [65, 18_536, 2_260, 101, 66] self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = ( "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 __magic_name__ : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231 # fmt: on self.assertListEqual(_a , self.big_tokenizer.encode(_a ) ) @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __magic_name__ : Optional[Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] __magic_name__ : List[Any] = " ".join(_a ) __magic_name__ : Any = self.big_tokenizer.encode_plus(_a , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : Union[str, Any] = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=_a ) __magic_name__ : List[str] = BigBirdConfig(attention_type="original_full" ) __magic_name__ : Optional[int] = BigBirdModel(_a ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**_a ) model(**_a ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) __magic_name__ : int = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def SCREAMING_SNAKE_CASE ( self ): # fmt: off __magic_name__ : Optional[Any] = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_a , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , )
281
1
def lowerCAmelCase_ ( _snake_case : str ) -> list: '''simple docstring''' if n_term == "": return [] __magic_name__ : list = [] for temp in range(int(_snake_case ) ): series.append(F'''1/{temp + 1}''' if series else "1" ) return series if __name__ == "__main__": snake_case : Tuple = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
281
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case : int = logging.get_logger(__name__) snake_case : List[str] = {"vocab_file": "spiece.model"} snake_case : List[str] = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } snake_case : Tuple = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } snake_case : List[str] = "▁" class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a=True , _a=True , _a=False , _a="[CLS]" , _a="[SEP]" , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , _a = None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __magic_name__ : str = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) __magic_name__ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) __magic_name__ : Dict = do_lower_case __magic_name__ : Tuple = remove_space __magic_name__ : Union[str, Any] = keep_accents __magic_name__ : Tuple = vocab_file __magic_name__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def SCREAMING_SNAKE_CASE ( self ): return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __magic_name__ : List[str] = self.__dict__.copy() __magic_name__ : Any = None return state def __setstate__( self , _a ): __magic_name__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __magic_name__ : str = {} __magic_name__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , _a ): if self.remove_space: __magic_name__ : List[Any] = " ".join(inputs.strip().split() ) else: __magic_name__ : str = inputs __magic_name__ : int = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: __magic_name__ : str = unicodedata.normalize("NFKD" , _a ) __magic_name__ : Tuple = "".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: __magic_name__ : int = outputs.lower() return outputs def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = self.preprocess_text(_a ) __magic_name__ : Dict = self.sp_model.encode(_a , out_type=_a ) __magic_name__ : Any = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): __magic_name__ : Optional[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __magic_name__ : List[str] = cur_pieces[1:] else: __magic_name__ : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.PieceToId(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.IdToPiece(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Any = [] __magic_name__ : Union[str, Any] = "" __magic_name__ : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token __magic_name__ : List[Any] = True __magic_name__ : Optional[int] = [] else: current_sub_tokens.append(_a ) __magic_name__ : Optional[Any] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : List[str] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[int] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : List[str] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , "wb" ) as fi: __magic_name__ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
281
1
def lowerCAmelCase_ ( _snake_case : list ) -> list: '''simple docstring''' def merge(_snake_case : list , _snake_case : list ) -> list: def _merge(): while left and right: yield (left if left[0] <= right[0] else right).pop(0 ) yield from left yield from right return list(_merge() ) if len(_snake_case ) <= 1: return collection __magic_name__ : Any = len(_snake_case ) // 2 return merge(merge_sort(collection[:mid] ) , merge_sort(collection[mid:] ) ) if __name__ == "__main__": import doctest doctest.testmod() snake_case : Tuple = input("Enter numbers separated by a comma:\n").strip() snake_case : Optional[int] = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
281
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Tuple , _snake_case : List[Any] , _snake_case : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if isinstance(_snake_case , _snake_case ): __magic_name__ : Union[str, Any] = np.full((len(_snake_case ), sequence_length, 2) , _snake_case ) else: __magic_name__ : List[Any] = np.full((len(_snake_case ), sequence_length) , _snake_case ) for i, tensor in enumerate(_snake_case ): if padding_side == "right": if isinstance(_snake_case , _snake_case ): __magic_name__ : Optional[Any] = tensor[:sequence_length] else: __magic_name__ : Union[str, Any] = tensor[:sequence_length] else: if isinstance(_snake_case , _snake_case ): __magic_name__ : List[Any] = tensor[:sequence_length] else: __magic_name__ : Optional[Any] = tensor[:sequence_length] return out_tensor.tolist() def lowerCAmelCase_ ( _snake_case : Optional[int] ) -> Tuple: '''simple docstring''' __magic_name__ : Union[str, Any] = ord(_snake_case ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True __magic_name__ : Any = unicodedata.category(_snake_case ) if cat.startswith("P" ): return True return False @dataclass class _snake_case ( snake_case ): UpperCamelCase__ = 42 UpperCamelCase__ = True UpperCamelCase__ = None UpperCamelCase__ = None UpperCamelCase__ = -100 UpperCamelCase__ = "pt" def SCREAMING_SNAKE_CASE ( self , _a ): import torch __magic_name__ : List[str] = "label" if "label" in features[0].keys() else "labels" __magic_name__ : Union[str, Any] = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __magic_name__ : Optional[int] = self.tokenizer.pad( _a , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" if labels is None else None , ) if labels is None: return batch __magic_name__ : Dict = torch.tensor(batch["entity_ids"] ).shape[1] __magic_name__ : List[Any] = self.tokenizer.padding_side if padding_side == "right": __magic_name__ : str = [ list(_a ) + [self.label_pad_token_id] * (sequence_length - len(_a )) for label in labels ] else: __magic_name__ : int = [ [self.label_pad_token_id] * (sequence_length - len(_a )) + list(_a ) for label in labels ] __magic_name__ : Dict = [feature["ner_tags"] for feature in features] __magic_name__ : List[Any] = padding_tensor(_a , -1 , _a , _a ) __magic_name__ : Any = [feature["original_entity_spans"] for feature in features] __magic_name__ : Any = padding_tensor(_a , (-1, -1) , _a , _a ) __magic_name__ : List[Any] = {k: torch.tensor(_a , dtype=torch.intaa ) for k, v in batch.items()} return batch
281
1
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_ ( ) -> str: '''simple docstring''' __magic_name__ : int = 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() snake_case : Optional[int] = load("accuracy") def lowerCAmelCase_ ( _snake_case : Tuple ) -> int: '''simple docstring''' __magic_name__ , __magic_name__ : Any = eval_pred __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return metric.compute(predictions=_snake_case , references=_snake_case ) class _snake_case ( snake_case ): def __init__( self , _a ): super().__init__() __magic_name__ : Tuple = trainer def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , **_a ): if control.should_evaluate: __magic_name__ : Any = deepcopy(_a ) self._trainer.evaluate(eval_dataset=self._trainer.train_dataset , metric_key_prefix="train" ) return control_copy def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' __magic_name__ : Optional[Any] = get_args() set_seed(args.seed ) __magic_name__ : Union[str, Any] = load_dataset("codeparrot/codecomplex" , split="train" ) __magic_name__ : Union[str, Any] = dataset.train_test_split(test_size=0.2 ) __magic_name__ : Tuple = train_test["test"].train_test_split(test_size=0.5 ) __magic_name__ : Optional[Any] = DatasetDict( { "train": train_test["train"], "test": test_validation["train"], "valid": test_validation["test"], } ) print("Loading tokenizer and model" ) __magic_name__ : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) __magic_name__ : Union[str, Any] = tokenizer.eos_token __magic_name__ : str = AutoModelForSequenceClassification.from_pretrained(args.model_ckpt , num_labels=7 ) __magic_name__ : Tuple = model.config.eos_token_id if args.freeze: for param in model.roberta.parameters(): __magic_name__ : Dict = False __magic_name__ : str = ClassLabel(num_classes=7 , names=list(set(train_test_validation["train"]["complexity"] ) ) ) def tokenize(_snake_case : List[Any] ): __magic_name__ : Dict = tokenizer(example["src"] , truncation=_snake_case , max_length=1024 ) __magic_name__ : Union[str, Any] = labels.straint(example["complexity"] ) return { "input_ids": inputs["input_ids"], "attention_mask": inputs["attention_mask"], "label": label, } __magic_name__ : Optional[int] = train_test_validation.map( _snake_case , batched=_snake_case , remove_columns=train_test_validation["train"].column_names , ) __magic_name__ : str = DataCollatorWithPadding(tokenizer=_snake_case ) __magic_name__ : 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" , ) __magic_name__ : 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()
281
import math def lowerCAmelCase_ ( _snake_case : float , _snake_case : float ) -> float: '''simple docstring''' return math.pow(_snake_case , 2 ) - a def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' return 2 * x def lowerCAmelCase_ ( _snake_case : float ) -> float: '''simple docstring''' __magic_name__ : Optional[int] = 2.0 while start <= a: __magic_name__ : str = math.pow(_snake_case , 2 ) return start def lowerCAmelCase_ ( _snake_case : float , _snake_case : int = 9999 , _snake_case : float = 0.00_000_000_000_001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) __magic_name__ : Optional[int] = get_initial_point(_snake_case ) for _ in range(_snake_case ): __magic_name__ : int = value __magic_name__ : str = value - fx(_snake_case , _snake_case ) / fx_derivative(_snake_case ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
281
1
def lowerCAmelCase_ ( _snake_case : Optional[int]=28123 ) -> Optional[Any]: '''simple docstring''' __magic_name__ : Optional[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i __magic_name__ : int = set() __magic_name__ : List[str] = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(_snake_case ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
281
from __future__ import annotations import unittest from transformers import LEDConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFLEDForConditionalGeneration, TFLEDModel @require_tf class _snake_case : UpperCamelCase__ = LEDConfig UpperCamelCase__ = {} UpperCamelCase__ = 'gelu' def __init__( self , _a , _a=13 , _a=7 , _a=True , _a=False , _a=99 , _a=32 , _a=2 , _a=4 , _a=37 , _a=0.1 , _a=0.1 , _a=20 , _a=2 , _a=1 , _a=0 , _a=4 , ): __magic_name__ : int = parent __magic_name__ : Optional[int] = batch_size __magic_name__ : Tuple = seq_length __magic_name__ : List[Any] = is_training __magic_name__ : Dict = use_labels __magic_name__ : Optional[Any] = vocab_size __magic_name__ : int = hidden_size __magic_name__ : Optional[int] = num_hidden_layers __magic_name__ : Optional[int] = num_attention_heads __magic_name__ : Tuple = intermediate_size __magic_name__ : Any = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : List[str] = max_position_embeddings __magic_name__ : Any = eos_token_id __magic_name__ : str = pad_token_id __magic_name__ : int = bos_token_id __magic_name__ : Optional[int] = attention_window # `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size # [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention # returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1] # because its local attention only attends to `self.attention_window` and one before and one after __magic_name__ : Tuple = self.attention_window + 2 # because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for # the `test_attention_outputs` and `test_hidden_states_output` tests __magic_name__ : Tuple = ( self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) __magic_name__ : int = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) __magic_name__ : int = tf.concat([input_ids, eos_tensor] , axis=1 ) __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Dict = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , attention_window=self.attention_window , **self.config_updates , ) __magic_name__ : List[str] = prepare_led_inputs_dict(_a , _a , _a ) __magic_name__ : Union[str, Any] = tf.concat( [tf.zeros_like(_a )[:, :-1], tf.ones_like(_a )[:, -1:]] , axis=-1 , ) __magic_name__ : List[Any] = global_attention_mask return config, inputs_dict def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Dict = TFLEDModel(config=_a ).get_decoder() __magic_name__ : Optional[int] = inputs_dict["input_ids"] __magic_name__ : Union[str, Any] = input_ids[:1, :] __magic_name__ : str = inputs_dict["attention_mask"][:1, :] __magic_name__ : int = 1 # first forward pass __magic_name__ : Tuple = model(_a , attention_mask=_a , use_cache=_a ) __magic_name__ , __magic_name__ : str = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __magic_name__ : Optional[int] = ids_tensor((self.batch_size, 3) , config.vocab_size ) __magic_name__ : Any = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and __magic_name__ : Optional[Any] = tf.concat([input_ids, next_tokens] , axis=-1 ) __magic_name__ : List[Any] = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) __magic_name__ : List[str] = model(_a , attention_mask=_a )[0] __magic_name__ : Dict = model(_a , attention_mask=_a , past_key_values=_a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice __magic_name__ : List[Any] = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) __magic_name__ : Union[str, Any] = output_from_no_past[:, -3:, random_slice_idx] __magic_name__ : List[str] = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(_a , _a , rtol=1e-3 ) def lowerCAmelCase_ ( _snake_case : Any , _snake_case : List[Any] , _snake_case : Any , _snake_case : str=None , _snake_case : List[str]=None , _snake_case : int=None , _snake_case : Any=None , ) -> int: '''simple docstring''' if attention_mask is None: __magic_name__ : str = tf.cast(tf.math.not_equal(_snake_case , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: __magic_name__ : List[Any] = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: __magic_name__ : Dict = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: __magic_name__ : Any = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, } @require_tf class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else () UpperCamelCase__ = (TFLEDForConditionalGeneration,) if is_tf_available() else () UpperCamelCase__ = ( { 'conversational': TFLEDForConditionalGeneration, 'feature-extraction': TFLEDModel, 'summarization': TFLEDForConditionalGeneration, 'text2text-generation': TFLEDForConditionalGeneration, 'translation': TFLEDForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase__ = True UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = TFLEDModelTester(self ) __magic_name__ : List[Any] = ConfigTester(self , config_class=_a ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ , __magic_name__ : int = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ : List[str] = tf.zeros_like(inputs_dict["attention_mask"] ) __magic_name__ : Optional[Any] = 2 __magic_name__ : Tuple = tf.where( tf.range(self.model_tester.seq_length )[None, :] < num_global_attn_indices , 1 , inputs_dict["global_attention_mask"] , ) __magic_name__ : Any = True __magic_name__ : str = self.model_tester.seq_length __magic_name__ : Dict = self.model_tester.encoder_seq_length def check_decoder_attentions_output(_a ): __magic_name__ : str = outputs.decoder_attentions self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) def check_encoder_attentions_output(_a ): __magic_name__ : Any = [t.numpy() for t in outputs.encoder_attentions] __magic_name__ : Tuple = [t.numpy() for t in outputs.encoder_global_attentions] self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertEqual(len(_a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_length, seq_length] , ) self.assertListEqual( list(global_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices] , ) for model_class in self.all_model_classes: __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = False __magic_name__ : Tuple = False __magic_name__ : Optional[int] = model_class(_a ) __magic_name__ : str = model(self._prepare_for_class(_a , _a ) ) __magic_name__ : Any = len(_a ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) if self.is_encoder_decoder: __magic_name__ : Tuple = model_class(_a ) __magic_name__ : Optional[Any] = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_decoder_attentions_output(_a ) # Check that output attentions can also be changed via the config del inputs_dict["output_attentions"] __magic_name__ : Dict = True __magic_name__ : str = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) # Check attention is always last and order is fine __magic_name__ : Union[str, Any] = True __magic_name__ : Union[str, Any] = True __magic_name__ : List[str] = model_class(_a ) __magic_name__ : Any = model(self._prepare_for_class(_a , _a ) ) self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(_a ) ) self.assertEqual(model.config.output_hidden_states , _a ) check_encoder_attentions_output(_a ) @unittest.skip("LED keeps using potentially symbolic tensors in conditionals and breaks tracing." ) def SCREAMING_SNAKE_CASE ( self ): pass def SCREAMING_SNAKE_CASE ( self ): # TODO: Head-masking not yet implement pass def lowerCAmelCase_ ( _snake_case : int ) -> Optional[int]: '''simple docstring''' return tf.constant(_snake_case , dtype=tf.intaa ) snake_case : Optional[int] = 1E-4 @slow @require_tf class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[Any] = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ).led # change to intended input here __magic_name__ : Optional[int] = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : str = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Any = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : List[Any] = model(**_a )[0] __magic_name__ : List[str] = (1, 1_024, 768) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : int = tf.convert_to_tensor( [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = TFLEDForConditionalGeneration.from_pretrained("allenai/led-base-16384" ) # change to intended input here __magic_name__ : int = _long_tensor([512 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Tuple = _long_tensor([128 * [0, 31_414, 232, 328, 740, 1_140, 12_695, 69]] ) __magic_name__ : Optional[Any] = prepare_led_inputs_dict(model.config , _a , _a ) __magic_name__ : Union[str, Any] = model(**_a )[0] __magic_name__ : Optional[int] = (1, 1_024, model.config.vocab_size) self.assertEqual(output.shape , _a ) # change to expected output here __magic_name__ : str = tf.convert_to_tensor( [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]] , ) tf.debugging.assert_near(output[:, :3, :3] , _a , atol=1e-3 , rtol=1e-3 )
281
1
import json import os import sys import tempfile import unittest from pathlib import Path from shutil import copyfile from huggingface_hub import HfFolder, Repository, create_repo, delete_repo from requests.exceptions import HTTPError import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, PROCESSOR_MAPPING, TOKENIZER_MAPPING, AutoConfig, AutoFeatureExtractor, AutoProcessor, AutoTokenizer, BertTokenizer, ProcessorMixin, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaProcessor, ) from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 from test_module.custom_processing import CustomProcessor # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 snake_case : Optional[int] = get_tests_dir("fixtures/dummy_feature_extractor_config.json") snake_case : List[str] = get_tests_dir("fixtures/vocab.json") snake_case : Tuple = get_tests_dir("fixtures") class _snake_case ( unittest.TestCase ): UpperCamelCase__ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = 0 def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Tuple = WavaVecaConfig() __magic_name__ : int = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h" ) # save in new folder model_config.save_pretrained(_a ) processor.save_pretrained(_a ) __magic_name__ : int = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: # copy relevant files copyfile(_a , os.path.join(_a , _a ) ) copyfile(_a , os.path.join(_a , "vocab.json" ) ) __magic_name__ : List[Any] = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Optional[int] = WavaVecaFeatureExtractor() __magic_name__ : Dict = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" ) __magic_name__ : Dict = WavaVecaProcessor(_a , _a ) # save in new folder processor.save_pretrained(_a ) # drop `processor_class` in tokenizer with open(os.path.join(_a , _a ) , "r" ) as f: __magic_name__ : Optional[Any] = json.load(_a ) config_dict.pop("processor_class" ) with open(os.path.join(_a , _a ) , "w" ) as f: f.write(json.dumps(_a ) ) __magic_name__ : Any = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Dict = WavaVecaFeatureExtractor() __magic_name__ : Dict = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h" ) __magic_name__ : List[str] = WavaVecaProcessor(_a , _a ) # save in new folder processor.save_pretrained(_a ) # drop `processor_class` in feature extractor with open(os.path.join(_a , _a ) , "r" ) as f: __magic_name__ : List[str] = json.load(_a ) config_dict.pop("processor_class" ) with open(os.path.join(_a , _a ) , "w" ) as f: f.write(json.dumps(_a ) ) __magic_name__ : int = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : int = WavaVecaConfig(processor_class="Wav2Vec2Processor" ) model_config.save_pretrained(_a ) # copy relevant files copyfile(_a , os.path.join(_a , "vocab.json" ) ) # create emtpy sample processor with open(os.path.join(_a , _a ) , "w" ) as f: f.write("{}" ) __magic_name__ : str = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_a ): __magic_name__ : Tuple = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): __magic_name__ : Any = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=_a ) __magic_name__ : Any = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" , trust_remote_code=_a ) self.assertTrue(processor.special_attribute_present ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) __magic_name__ : str = processor.feature_extractor self.assertTrue(feature_extractor.special_attribute_present ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) __magic_name__ : Dict = processor.tokenizer self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizerFast" ) # Test we can also load the slow version __magic_name__ : str = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=_a , use_fast=_a ) __magic_name__ : int = new_processor.tokenizer self.assertTrue(new_tokenizer.special_attribute_present ) self.assertEqual(new_tokenizer.__class__.__name__ , "NewTokenizer" ) else: self.assertEqual(tokenizer.__class__.__name__ , "NewTokenizer" ) def SCREAMING_SNAKE_CASE ( self ): try: AutoConfig.register("custom" , _a ) AutoFeatureExtractor.register(_a , _a ) AutoTokenizer.register(_a , slow_tokenizer_class=_a ) AutoProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoProcessor.register(_a , _a ) # Now that the config is registered, it can be used as any other config with the auto-API __magic_name__ : str = CustomFeatureExtractor.from_pretrained(_a ) with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : Dict = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __magic_name__ : int = CustomTokenizer(_a ) __magic_name__ : Optional[Any] = CustomProcessor(_a , _a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained(_a ) __magic_name__ : Optional[Any] = AutoProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE ( self ): class _snake_case ( snake_case ): UpperCamelCase__ = False class _snake_case ( snake_case ): UpperCamelCase__ = False class _snake_case ( snake_case ): UpperCamelCase__ = 'AutoFeatureExtractor' UpperCamelCase__ = 'AutoTokenizer' UpperCamelCase__ = False try: AutoConfig.register("custom" , _a ) AutoFeatureExtractor.register(_a , _a ) AutoTokenizer.register(_a , slow_tokenizer_class=_a ) AutoProcessor.register(_a , _a ) # If remote code is not set, the default is to use local classes. __magic_name__ : Optional[Any] = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor" ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote code is disabled, we load the local ones. __magic_name__ : int = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=_a ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertFalse(processor.special_attribute_present ) self.assertFalse(processor.feature_extractor.special_attribute_present ) self.assertFalse(processor.tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub. __magic_name__ : Optional[int] = AutoProcessor.from_pretrained( "hf-internal-testing/test_dynamic_processor" , trust_remote_code=_a ) self.assertEqual(processor.__class__.__name__ , "NewProcessor" ) self.assertTrue(processor.special_attribute_present ) self.assertTrue(processor.feature_extractor.special_attribute_present ) self.assertTrue(processor.tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] if CustomConfig in PROCESSOR_MAPPING._extra_content: del PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert" ) self.assertEqual(processor.__class__.__name__ , "BertTokenizerFast" ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext" ) self.assertEqual(processor.__class__.__name__ , "ConvNextImageProcessor" ) @is_staging_test class _snake_case ( unittest.TestCase ): UpperCamelCase__ = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def SCREAMING_SNAKE_CASE ( cls ): __magic_name__ : List[str] = TOKEN HfFolder.save_token(_a ) @classmethod def SCREAMING_SNAKE_CASE ( cls ): try: delete_repo(token=cls._token , repo_id="test-processor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-processor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-processor" ) except HTTPError: pass def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = WavaVecaProcessor.from_pretrained(_a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(_a , "test-processor" ) , push_to_hub=_a , use_auth_token=self._token ) __magic_name__ : int = WavaVecaProcessor.from_pretrained(f'''{USER}/test-processor''' ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(new_processor.feature_extractor , _a ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[Any] = WavaVecaProcessor.from_pretrained(_a ) with tempfile.TemporaryDirectory() as tmp_dir: processor.save_pretrained( os.path.join(_a , "test-processor-org" ) , push_to_hub=_a , use_auth_token=self._token , organization="valid_org" , ) __magic_name__ : Dict = WavaVecaProcessor.from_pretrained("valid_org/test-processor-org" ) for k, v in processor.feature_extractor.__dict__.items(): self.assertEqual(_a , getattr(new_processor.feature_extractor , _a ) ) self.assertDictEqual(new_processor.tokenizer.get_vocab() , processor.tokenizer.get_vocab() ) def SCREAMING_SNAKE_CASE ( self ): CustomFeatureExtractor.register_for_auto_class() CustomTokenizer.register_for_auto_class() CustomProcessor.register_for_auto_class() __magic_name__ : str = CustomFeatureExtractor.from_pretrained(_a ) with tempfile.TemporaryDirectory() as tmp_dir: __magic_name__ : List[str] = os.path.join(_a , "vocab.txt" ) with open(_a , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens] ) ) __magic_name__ : List[Any] = CustomTokenizer(_a ) __magic_name__ : Union[str, Any] = CustomProcessor(_a , _a ) with tempfile.TemporaryDirectory() as tmp_dir: create_repo(f'''{USER}/test-dynamic-processor''' , token=self._token ) __magic_name__ : Optional[int] = Repository(_a , clone_from=f'''{USER}/test-dynamic-processor''' , token=self._token ) processor.save_pretrained(_a ) # This has added the proper auto_map field to the feature extractor config self.assertDictEqual( processor.feature_extractor.auto_map , { "AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor", "AutoProcessor": "custom_processing.CustomProcessor", } , ) # This has added the proper auto_map field to the tokenizer config with open(os.path.join(_a , "tokenizer_config.json" ) ) as f: __magic_name__ : Optional[int] = json.load(_a ) self.assertDictEqual( tokenizer_config["auto_map"] , { "AutoTokenizer": ["custom_tokenization.CustomTokenizer", None], "AutoProcessor": "custom_processing.CustomProcessor", } , ) # The code has been copied from fixtures self.assertTrue(os.path.isfile(os.path.join(_a , "custom_feature_extraction.py" ) ) ) self.assertTrue(os.path.isfile(os.path.join(_a , "custom_tokenization.py" ) ) ) self.assertTrue(os.path.isfile(os.path.join(_a , "custom_processing.py" ) ) ) repo.push_to_hub() __magic_name__ : List[str] = AutoProcessor.from_pretrained(f'''{USER}/test-dynamic-processor''' , trust_remote_code=_a ) # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module self.assertEqual(new_processor.__class__.__name__ , "CustomProcessor" )
281
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() snake_case : Optional[Any] = logging.get_logger(__name__) def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Union[str, Any]=False ) -> List[str]: '''simple docstring''' __magic_name__ : Union[str, Any] = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((F'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', F'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((F'''blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" __magic_name__ : int = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Any , _snake_case : Dict=False ) -> int: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: __magic_name__ : int = "" else: __magic_name__ : Union[str, Any] = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __magic_name__ : Optional[Any] = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) __magic_name__ : int = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict __magic_name__ : Dict = in_proj_weight[ : config.hidden_size, : ] __magic_name__ : List[str] = in_proj_bias[: config.hidden_size] __magic_name__ : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __magic_name__ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __magic_name__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] __magic_name__ : int = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( _snake_case : List[str] ) -> List[str]: '''simple docstring''' __magic_name__ : List[str] = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(_snake_case , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : int , _snake_case : Union[str, Any] ) -> Optional[int]: '''simple docstring''' __magic_name__ : int = dct.pop(_snake_case ) __magic_name__ : List[Any] = val def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" __magic_name__ : List[str] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Any , _snake_case : int=False ) -> Dict: '''simple docstring''' __magic_name__ : List[str] = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=_snake_case , ) __magic_name__ : List[str] = ViTHybridConfig(backbone_config=_snake_case , image_size=384 , num_labels=1000 ) __magic_name__ : str = False # load original model from timm __magic_name__ : Union[str, Any] = timm.create_model(_snake_case , pretrained=_snake_case ) timm_model.eval() # load state_dict of original model, remove and rename some keys __magic_name__ : List[Any] = timm_model.state_dict() if base_model: remove_classification_head_(_snake_case ) __magic_name__ : Tuple = create_rename_keys(_snake_case , _snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) read_in_q_k_v(_snake_case , _snake_case , _snake_case ) __magic_name__ : List[str] = "huggingface/label-files" __magic_name__ : int = "imagenet-1k-id2label.json" __magic_name__ : Optional[int] = json.load(open(hf_hub_download(_snake_case , _snake_case , repo_type="dataset" ) , "r" ) ) __magic_name__ : int = {int(_snake_case ): v for k, v in idalabel.items()} __magic_name__ : List[str] = idalabel __magic_name__ : List[str] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": __magic_name__ : List[str] = ViTHybridModel(_snake_case ).eval() else: __magic_name__ : str = ViTHybridForImageClassification(_snake_case ).eval() model.load_state_dict(_snake_case ) # create image processor __magic_name__ : List[Any] = create_transform(**resolve_data_config({} , model=_snake_case ) ) __magic_name__ : int = transform.transforms __magic_name__ : List[str] = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } __magic_name__ : int = ViTHybridImageProcessor( do_resize=_snake_case , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=_snake_case , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=_snake_case , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) __magic_name__ : List[Any] = prepare_img() __magic_name__ : Any = transform(_snake_case ).unsqueeze(0 ) __magic_name__ : Tuple = processor(_snake_case , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(_snake_case , _snake_case ) # verify logits with torch.no_grad(): __magic_name__ : Optional[int] = model(_snake_case ) __magic_name__ : List[str] = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: __magic_name__ : List[str] = timm_model.forward_features(_snake_case ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(_snake_case , outputs.pooler_output , atol=1E-3 ) else: __magic_name__ : Any = timm_model(_snake_case ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(_snake_case , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(_snake_case ).mkdir(exist_ok=_snake_case ) print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(_snake_case ) print(F'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(_snake_case ) if push_to_hub: print(F'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(F'''ybelkada/{vit_name}''' ) processor.push_to_hub(F'''ybelkada/{vit_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) snake_case : List[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## snake_case : Any = 16 snake_case : Any = 32 def lowerCAmelCase_ ( _snake_case : Accelerator , _snake_case : int = 16 ) -> Tuple: '''simple docstring''' __magic_name__ : Any = AutoTokenizer.from_pretrained("bert-base-cased" ) __magic_name__ : List[str] = load_dataset("glue" , "mrpc" ) def tokenize_function(_snake_case : Any ): # max_length=None => use the model max length (it's actually the default) __magic_name__ : str = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_snake_case , max_length=_snake_case ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): __magic_name__ : Dict = datasets.map( _snake_case , batched=_snake_case , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library __magic_name__ : Any = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(_snake_case : Tuple ): # On TPU it's best to pad everything to the same length or training will be very slow. __magic_name__ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": __magic_name__ : Dict = 16 elif accelerator.mixed_precision != "no": __magic_name__ : Optional[Any] = 8 else: __magic_name__ : Optional[int] = None return tokenizer.pad( _snake_case , padding="longest" , max_length=_snake_case , pad_to_multiple_of=_snake_case , return_tensors="pt" , ) # Instantiate dataloaders. __magic_name__ : int = DataLoader( tokenized_datasets["train"] , shuffle=_snake_case , collate_fn=_snake_case , batch_size=_snake_case ) __magic_name__ : Union[str, Any] = DataLoader( tokenized_datasets["validation"] , shuffle=_snake_case , collate_fn=_snake_case , batch_size=_snake_case ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders snake_case : Tuple = mocked_dataloaders # noqa: F811 def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : List[str] ) -> Union[str, Any]: '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , _snake_case ) == "1": __magic_name__ : Dict = 2 # Initialize accelerator __magic_name__ : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __magic_name__ : List[str] = config["lr"] __magic_name__ : Dict = int(config["num_epochs"] ) __magic_name__ : List[Any] = int(config["seed"] ) __magic_name__ : Tuple = int(config["batch_size"] ) __magic_name__ : Optional[int] = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=_snake_case ) def inner_training_loop(_snake_case : int ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(_snake_case ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __magic_name__ : Optional[int] = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_snake_case ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). __magic_name__ : Optional[Any] = model.to(accelerator.device ) # Instantiate optimizer __magic_name__ : int = AdamW(params=model.parameters() , lr=_snake_case ) __magic_name__ , __magic_name__ : int = get_dataloaders(_snake_case , _snake_case ) # Instantiate scheduler __magic_name__ : Any = get_linear_schedule_with_warmup( optimizer=_snake_case , num_warmup_steps=100 , num_training_steps=(len(_snake_case ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : str = accelerator.prepare( _snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) # Now we train the model for epoch in range(_snake_case ): model.train() for step, batch in enumerate(_snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __magic_name__ : Dict = model(**_snake_case ) __magic_name__ : List[str] = outputs.loss accelerator.backward(_snake_case ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_snake_case ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __magic_name__ : str = model(**_snake_case ) __magic_name__ : Tuple = outputs.logits.argmax(dim=-1 ) __magic_name__ , __magic_name__ : Optional[Any] = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=_snake_case , references=_snake_case , ) __magic_name__ : str = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , _snake_case ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : str = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=_snake_case , default=_snake_case , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) __magic_name__ : List[Any] = parser.parse_args() __magic_name__ : Tuple = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_snake_case , _snake_case ) if __name__ == "__main__": main()
281
# This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration snake_case : List[str] = "facebook/wmt19-en-de" snake_case : Dict = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model snake_case : List[str] = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) snake_case : int = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test snake_case : Optional[Any] = tokenizer(["Making tiny model"], return_tensors="pt") snake_case : List[str] = tiny_model(**batch) print("test output:", len(outputs.logits[0])) # Save snake_case : Dict = "tiny-wmt19-en-de" tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-de
281
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class _snake_case ( snake_case ): UpperCamelCase__ = 'Salesforce/blip-image-captioning-base' UpperCamelCase__ = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) UpperCamelCase__ = 'image_captioner' UpperCamelCase__ = AutoModelForVisionaSeq UpperCamelCase__ = ['image'] UpperCamelCase__ = ['text'] def __init__( self , *_a , **_a ): requires_backends(self , ["vision"] ) super().__init__(*_a , **_a ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.pre_processor(images=_a , return_tensors="pt" ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.model.generate(**_a ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.pre_processor.batch_decode(_a , skip_special_tokens=_a )[0].strip()
281
import argparse import csv import logging import os import random import numpy as np import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from tqdm import tqdm, trange from transformers import ( CONFIG_NAME, WEIGHTS_NAME, AdamW, OpenAIGPTDoubleHeadsModel, OpenAIGPTTokenizer, get_linear_schedule_with_warmup, ) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case : Optional[int] = logging.getLogger(__name__) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Union[str, Any] ) -> Tuple: '''simple docstring''' __magic_name__ : List[str] = np.argmax(_snake_case , axis=1 ) return np.sum(outputs == labels ) def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' with open(_snake_case , encoding="utf_8" ) as f: __magic_name__ : List[str] = csv.reader(_snake_case ) __magic_name__ : List[Any] = [] next(_snake_case ) # skip the first line for line in tqdm(_snake_case ): output.append((" ".join(line[1:5] ), line[5], line[6], int(line[-1] ) - 1) ) return output def lowerCAmelCase_ ( _snake_case : str , _snake_case : Tuple , _snake_case : Union[str, Any] , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : Optional[int] ) -> int: '''simple docstring''' __magic_name__ : Optional[int] = [] for dataset in encoded_datasets: __magic_name__ : Union[str, Any] = len(_snake_case ) __magic_name__ : Dict = np.zeros((n_batch, 2, input_len) , dtype=np.intaa ) __magic_name__ : List[str] = np.zeros((n_batch, 2) , dtype=np.intaa ) __magic_name__ : Optional[int] = np.full((n_batch, 2, input_len) , fill_value=-100 , dtype=np.intaa ) __magic_name__ : int = np.zeros((n_batch,) , dtype=np.intaa ) for ( i, (story, conta, conta, mc_label), ) in enumerate(_snake_case ): __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : Dict = [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token] __magic_name__ : str = with_conta __magic_name__ : Tuple = with_conta __magic_name__ : Union[str, Any] = len(_snake_case ) - 1 __magic_name__ : int = len(_snake_case ) - 1 __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[Any] = with_conta __magic_name__ : Optional[int] = mc_label __magic_name__ : str = (input_ids, mc_token_ids, lm_labels, mc_labels) tensor_datasets.append(tuple(torch.tensor(_snake_case ) for t in all_inputs ) ) return tensor_datasets def lowerCAmelCase_ ( ) -> List[Any]: '''simple docstring''' __magic_name__ : Any = argparse.ArgumentParser() parser.add_argument("--model_name" , type=_snake_case , default="openai-gpt" , help="pretrained model name" ) parser.add_argument("--do_train" , action="store_true" , help="Whether to run training." ) parser.add_argument("--do_eval" , action="store_true" , help="Whether to run eval on the dev set." ) parser.add_argument( "--output_dir" , default=_snake_case , type=_snake_case , required=_snake_case , help="The output directory where the model predictions and checkpoints will be written." , ) parser.add_argument("--train_dataset" , type=_snake_case , default="" ) parser.add_argument("--eval_dataset" , type=_snake_case , default="" ) parser.add_argument("--seed" , type=_snake_case , default=42 ) parser.add_argument("--num_train_epochs" , type=_snake_case , default=3 ) parser.add_argument("--train_batch_size" , type=_snake_case , default=8 ) parser.add_argument("--eval_batch_size" , type=_snake_case , default=16 ) parser.add_argument("--adam_epsilon" , default=1E-8 , type=_snake_case , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , type=_snake_case , default=1 ) parser.add_argument( "--max_steps" , default=-1 , type=_snake_case , help=( "If > 0: set total number of training steps to perform. Override num_train_epochs." ) , ) parser.add_argument( "--gradient_accumulation_steps" , type=_snake_case , default=1 , help="Number of updates steps to accumulate before performing a backward/update pass." , ) parser.add_argument("--learning_rate" , type=_snake_case , default=6.25E-5 ) parser.add_argument("--warmup_steps" , default=0 , type=_snake_case , help="Linear warmup over warmup_steps." ) parser.add_argument("--lr_schedule" , type=_snake_case , default="warmup_linear" ) parser.add_argument("--weight_decay" , type=_snake_case , default=0.01 ) parser.add_argument("--lm_coef" , type=_snake_case , default=0.9 ) parser.add_argument("--n_valid" , type=_snake_case , default=374 ) parser.add_argument("--server_ip" , type=_snake_case , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=_snake_case , default="" , help="Can be used for distant debugging." ) __magic_name__ : List[Any] = parser.parse_args() print(_snake_case ) if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=_snake_case ) ptvsd.wait_for_attach() random.seed(args.seed ) np.random.seed(args.seed ) torch.manual_seed(args.seed ) torch.cuda.manual_seed_all(args.seed ) __magic_name__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) __magic_name__ : Optional[int] = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(_snake_case , _snake_case ) ) if not args.do_train and not args.do_eval: raise ValueError("At least one of `do_train` or `do_eval` must be True." ) if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) # Load tokenizer and model # This loading functions also add new tokens and embeddings called `special tokens` # These new embeddings will be fine-tuned on the RocStories dataset __magic_name__ : List[Any] = ["_start_", "_delimiter_", "_classify_"] __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.model_name ) tokenizer.add_tokens(_snake_case ) __magic_name__ : Optional[Any] = tokenizer.convert_tokens_to_ids(_snake_case ) __magic_name__ : List[str] = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name ) model.resize_token_embeddings(len(_snake_case ) ) model.to(_snake_case ) # Load and encode the datasets def tokenize_and_encode(_snake_case : str ): if isinstance(_snake_case , _snake_case ): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case ) ) elif isinstance(_snake_case , _snake_case ): return obj return [tokenize_and_encode(_snake_case ) for o in obj] logger.info("Encoding dataset..." ) __magic_name__ : Optional[int] = load_rocstories_dataset(args.train_dataset ) __magic_name__ : str = load_rocstories_dataset(args.eval_dataset ) __magic_name__ : int = (train_dataset, eval_dataset) __magic_name__ : List[str] = tokenize_and_encode(_snake_case ) # Compute the max input length for the Transformer __magic_name__ : Optional[Any] = model.config.n_positions // 2 - 2 __magic_name__ : Optional[int] = max( len(story[:max_length] ) + max(len(conta[:max_length] ) , len(conta[:max_length] ) ) + 3 for dataset in encoded_datasets for story, conta, conta, _ in dataset ) __magic_name__ : List[str] = min(_snake_case , model.config.n_positions ) # Max size of input for the pre-trained model # Prepare inputs tensors and dataloaders __magic_name__ : List[Any] = pre_process_datasets(_snake_case , _snake_case , _snake_case , *_snake_case ) __magic_name__ , __magic_name__ : Optional[int] = tensor_datasets[0], tensor_datasets[1] __magic_name__ : Tuple = TensorDataset(*_snake_case ) __magic_name__ : Union[str, Any] = RandomSampler(_snake_case ) __magic_name__ : Dict = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.train_batch_size ) __magic_name__ : Any = TensorDataset(*_snake_case ) __magic_name__ : Optional[Any] = SequentialSampler(_snake_case ) __magic_name__ : int = DataLoader(_snake_case , sampler=_snake_case , batch_size=args.eval_batch_size ) # Prepare optimizer if args.do_train: if args.max_steps > 0: __magic_name__ : Tuple = args.max_steps __magic_name__ : List[str] = args.max_steps // (len(_snake_case ) // args.gradient_accumulation_steps) + 1 else: __magic_name__ : List[str] = len(_snake_case ) // args.gradient_accumulation_steps * args.num_train_epochs __magic_name__ : str = list(model.named_parameters() ) __magic_name__ : Dict = ["bias", "LayerNorm.bias", "LayerNorm.weight"] __magic_name__ : str = [ { "params": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay )], "weight_decay": args.weight_decay, }, {"params": [p for n, p in param_optimizer if any(nd in n for nd in no_decay )], "weight_decay": 0.0}, ] __magic_name__ : str = AdamW(_snake_case , lr=args.learning_rate , eps=args.adam_epsilon ) __magic_name__ : List[str] = get_linear_schedule_with_warmup( _snake_case , num_warmup_steps=args.warmup_steps , num_training_steps=_snake_case ) if args.do_train: __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0, None model.train() for _ in trange(int(args.num_train_epochs ) , desc="Epoch" ): __magic_name__ : List[str] = 0 __magic_name__ : Tuple = 0 __magic_name__ : Dict = tqdm(_snake_case , desc="Training" ) for step, batch in enumerate(_snake_case ): __magic_name__ : Optional[Any] = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = batch __magic_name__ : Optional[Any] = model(_snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Optional[Any] = args.lm_coef * losses[0] + losses[1] loss.backward() optimizer.step() scheduler.step() optimizer.zero_grad() tr_loss += loss.item() __magic_name__ : List[str] = ( loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item() ) nb_tr_steps += 1 __magic_name__ : int = "Training loss: {:.2e} lr: {:.2e}".format(_snake_case , scheduler.get_lr()[0] ) # Save a trained model if args.do_train: # Save a trained model, configuration and tokenizer __magic_name__ : Dict = model.module if hasattr(_snake_case , "module" ) else model # Only save the model itself # If we save using the predefined names, we can load using `from_pretrained` __magic_name__ : List[Any] = os.path.join(args.output_dir , _snake_case ) __magic_name__ : Dict = os.path.join(args.output_dir , _snake_case ) torch.save(model_to_save.state_dict() , _snake_case ) model_to_save.config.to_json_file(_snake_case ) tokenizer.save_vocabulary(args.output_dir ) # Load a trained model and vocabulary that you have fine-tuned __magic_name__ : Dict = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir ) __magic_name__ : Optional[int] = OpenAIGPTTokenizer.from_pretrained(args.output_dir ) model.to(_snake_case ) if args.do_eval: model.eval() __magic_name__ , __magic_name__ : Any = 0, 0 __magic_name__ , __magic_name__ : Union[str, Any] = 0, 0 for batch in tqdm(_snake_case , desc="Evaluating" ): __magic_name__ : int = tuple(t.to(_snake_case ) for t in batch ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] = batch with torch.no_grad(): __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Dict = model( _snake_case , mc_token_ids=_snake_case , lm_labels=_snake_case , mc_labels=_snake_case ) __magic_name__ : Tuple = mc_logits.detach().cpu().numpy() __magic_name__ : Any = mc_labels.to("cpu" ).numpy() __magic_name__ : str = accuracy(_snake_case , _snake_case ) eval_loss += mc_loss.mean().item() eval_accuracy += tmp_eval_accuracy nb_eval_examples += input_ids.size(0 ) nb_eval_steps += 1 __magic_name__ : Tuple = eval_loss / nb_eval_steps __magic_name__ : List[Any] = eval_accuracy / nb_eval_examples __magic_name__ : int = tr_loss / nb_tr_steps if args.do_train else None __magic_name__ : Any = {"eval_loss": eval_loss, "eval_accuracy": eval_accuracy, "train_loss": train_loss} __magic_name__ : int = os.path.join(args.output_dir , "eval_results.txt" ) with open(_snake_case , "w" ) as writer: logger.info("***** Eval results *****" ) for key in sorted(result.keys() ): logger.info(" %s = %s" , _snake_case , str(result[key] ) ) writer.write("%s = %s\n" % (key, str(result[key] )) ) if __name__ == "__main__": main()
281
1
from __future__ import annotations import random import unittest from transformers import TransfoXLConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST, TFTransfoXLForSequenceClassification, TFTransfoXLLMHeadModel, TFTransfoXLModel, ) class _snake_case : def __init__( self , _a , ): __magic_name__ : Optional[int] = parent __magic_name__ : Tuple = 13 __magic_name__ : Optional[int] = 7 __magic_name__ : Any = 30 __magic_name__ : List[Any] = self.seq_length + self.mem_len __magic_name__ : int = 15 __magic_name__ : int = True __magic_name__ : Optional[Any] = True __magic_name__ : str = 99 __magic_name__ : Any = [10, 50, 80] __magic_name__ : Optional[Any] = 32 __magic_name__ : str = 32 __magic_name__ : int = 4 __magic_name__ : Optional[Any] = 8 __magic_name__ : str = 128 __magic_name__ : Optional[int] = 2 __magic_name__ : Union[str, Any] = 2 __magic_name__ : int = None __magic_name__ : int = 1 __magic_name__ : Optional[int] = 0 __magic_name__ : int = 3 __magic_name__ : Union[str, Any] = self.vocab_size - 1 __magic_name__ : Any = 0.01 def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : str = None if self.use_labels: __magic_name__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : str = TransfoXLConfig( vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , ) return (config, input_ids_a, input_ids_a, lm_labels) def SCREAMING_SNAKE_CASE ( self ): random.seed(self.seed ) tf.random.set_seed(self.seed ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a ): __magic_name__ : List[Any] = TFTransfoXLModel(_a ) __magic_name__ , __magic_name__ : Optional[Any] = model(_a ).to_tuple() __magic_name__ : Dict = {"input_ids": input_ids_a, "mems": mems_a} __magic_name__ , __magic_name__ : Any = model(_a ).to_tuple() self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a ): __magic_name__ : Optional[int] = TFTransfoXLLMHeadModel(_a ) __magic_name__ , __magic_name__ : List[Any] = model(_a ).to_tuple() __magic_name__ : int = {"input_ids": input_ids_a, "labels": lm_labels} __magic_name__ , __magic_name__ : Dict = model(_a ).to_tuple() __magic_name__ , __magic_name__ : Optional[Any] = model([input_ids_a, mems_a] ).to_tuple() __magic_name__ : Any = {"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels} __magic_name__ , __magic_name__ : Any = model(_a ).to_tuple() self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertListEqual( [mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a ): __magic_name__ : List[str] = TFTransfoXLForSequenceClassification(_a ) __magic_name__ : int = model(_a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = self.prepare_config_and_inputs() ((__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__)) : Optional[Any] = config_and_inputs __magic_name__ : Optional[Any] = {"input_ids": input_ids_a} return config, inputs_dict @require_tf class _snake_case ( snake_case , snake_case , unittest.TestCase ): UpperCamelCase__ = ( (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else () ) UpperCamelCase__ = () if is_tf_available() else () UpperCamelCase__ = ( { 'feature-extraction': TFTransfoXLModel, 'text-classification': TFTransfoXLForSequenceClassification, 'text-generation': TFTransfoXLLMHeadModel, 'zero-shot': TFTransfoXLForSequenceClassification, } if is_tf_available() else {} ) # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False UpperCamelCase__ = False def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a , _a ): if pipeline_test_casse_name == "TextGenerationPipelineTests": # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`. # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple # tokenizer. return True return False def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = TFTransfoXLModelTester(self ) __magic_name__ : str = ConfigTester(self , config_class=_a , d_embed=37 ) def SCREAMING_SNAKE_CASE ( self ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self ): self.model_tester.set_seed() __magic_name__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_model(*_a ) def SCREAMING_SNAKE_CASE ( self ): self.model_tester.set_seed() __magic_name__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_lm_head(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*_a ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ , __magic_name__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ : List[str] = [TFTransfoXLForSequenceClassification] for model_class in self.all_model_classes: __magic_name__ : List[str] = model_class(_a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class in list_other_models_with_output_ebd: __magic_name__ : List[Any] = model.get_output_embeddings() assert isinstance(_a , tf.keras.layers.Layer ) __magic_name__ : str = model.get_bias() assert name is None else: __magic_name__ : str = model.get_output_embeddings() assert x is None __magic_name__ : List[str] = model.get_bias() assert name is None def SCREAMING_SNAKE_CASE ( self ): # TODO JP: Make TransfoXL XLA compliant pass @slow def SCREAMING_SNAKE_CASE ( self ): for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : List[Any] = TFTransfoXLModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss." ) def SCREAMING_SNAKE_CASE ( self ): pass @require_tf class _snake_case ( unittest.TestCase ): @unittest.skip("Skip test until #12651 is resolved." ) @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Any = TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103" ) # fmt: off __magic_name__ : Tuple = tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231 # fmt: on # In 1991 , the remains of Russian Tsar Nicholas II and his family # ( except for Alexei and Maria ) are discovered . # The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the # remainder of the story . 1883 Western Siberia , # a young Grigori Rasputin is asked by his father and a group of men to perform magic . # Rasputin has a vision and denounces one of the men as a horse thief . Although his # father initially slaps him for making such an accusation , Rasputin watches as the # man is chased outside and beaten . Twenty years later , Rasputin sees a vision of # the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous , # with people , even a bishop , begging for his blessing . <eod> </s> <eos> # fmt: off __magic_name__ : List[str] = [33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0] # noqa: E231 # fmt: on # In 1991, the remains of Russian Tsar Nicholas II and his family ( # except for Alexei and Maria ) are discovered. The voice of young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story. # 1883 Western Siberia, a young Grigori Rasputin is asked by his father # and a group of men to perform magic. Rasputin has a vision and # denounces one of the men as a horse thief. Although his father initially # slaps him for making such an accusation, Rasputin watches as the man # is chased outside and beaten. Twenty years later, Rasputin sees a vision # of the Virgin Mary, prompting him to become a priest. # Rasputin quickly becomes famous, with people, even a bishop, begging for # his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar # Nicholas II and his family were discovered. The voice of <unk> young son, # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos> __magic_name__ : str = model.generate(_a , max_length=200 , do_sample=_a ) self.assertListEqual(output_ids[0].numpy().tolist() , _a )
281
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
281
1
import glob import os import random from string import ascii_lowercase, digits import cva snake_case : int = "" snake_case : Optional[int] = "" snake_case : List[str] = "" snake_case : int = 1 # (0 is vertical, 1 is horizontal) def lowerCAmelCase_ ( ) -> None: '''simple docstring''' __magic_name__ , __magic_name__ : List[str] = get_dataset(_snake_case , _snake_case ) print("Processing..." ) __magic_name__ , __magic_name__ , __magic_name__ : Dict = update_image_and_anno(_snake_case , _snake_case , _snake_case ) for index, image in enumerate(_snake_case ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' __magic_name__ : Any = random_chars(32 ) __magic_name__ : Any = paths[index].split(os.sep )[-1].rsplit("." , 1 )[0] __magic_name__ : Tuple = F'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(F'''/{file_root}.jpg''' , _snake_case , [cva.IMWRITE_JPEG_QUALITY, 85] ) print(F'''Success {index+1}/{len(_snake_case )} with {file_name}''' ) __magic_name__ : List[str] = [] for anno in new_annos[index]: __magic_name__ : Optional[int] = F'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(_snake_case ) with open(F'''/{file_root}.txt''' , "w" ) as outfile: outfile.write("\n".join(line for line in annos_list ) ) def lowerCAmelCase_ ( _snake_case : str , _snake_case : str ) -> tuple[list, list]: '''simple docstring''' __magic_name__ : Tuple = [] __magic_name__ : str = [] for label_file in glob.glob(os.path.join(_snake_case , "*.txt" ) ): __magic_name__ : List[str] = label_file.split(os.sep )[-1].rsplit("." , 1 )[0] with open(_snake_case ) as in_file: __magic_name__ : List[Any] = in_file.readlines() __magic_name__ : Tuple = os.path.join(_snake_case , F'''{label_name}.jpg''' ) __magic_name__ : int = [] for obj_list in obj_lists: __magic_name__ : Optional[Any] = obj_list.rstrip("\n" ).split(" " ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(_snake_case ) labels.append(_snake_case ) return img_paths, labels def lowerCAmelCase_ ( _snake_case : list , _snake_case : list , _snake_case : int = 1 ) -> tuple[list, list, list]: '''simple docstring''' __magic_name__ : Union[str, Any] = [] __magic_name__ : Tuple = [] __magic_name__ : int = [] for idx in range(len(_snake_case ) ): __magic_name__ : Tuple = [] __magic_name__ : List[Any] = img_list[idx] path_list.append(_snake_case ) __magic_name__ : int = anno_list[idx] __magic_name__ : Optional[int] = cva.imread(_snake_case ) if flip_type == 1: __magic_name__ : List[Any] = cva.flip(_snake_case , _snake_case ) for bbox in img_annos: __magic_name__ : Optional[int] = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: __magic_name__ : Union[str, Any] = cva.flip(_snake_case , _snake_case ) for bbox in img_annos: __magic_name__ : Tuple = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(_snake_case ) new_imgs_list.append(_snake_case ) return new_imgs_list, new_annos_lists, path_list def lowerCAmelCase_ ( _snake_case : int = 32 ) -> str: '''simple docstring''' assert number_char > 1, "The number of character should greater than 1" __magic_name__ : List[str] = ascii_lowercase + digits return "".join(random.choice(_snake_case ) for _ in range(_snake_case ) ) if __name__ == "__main__": main() print("DONE ✅")
281
import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def lowerCAmelCase_ ( _snake_case : List[Any] ) -> List[Any]: '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Tuple: '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : Dict = "mock-s3-bucket" __magic_name__ : Any = F'''s3://{mock_bucket}''' __magic_name__ : str = extract_path_from_uri(_snake_case ) assert dataset_path.startswith("s3://" ) is False __magic_name__ : Tuple = "./local/path" __magic_name__ : Optional[Any] = extract_path_from_uri(_snake_case ) assert dataset_path == new_dataset_path def lowerCAmelCase_ ( _snake_case : List[str] ) -> Optional[Any]: '''simple docstring''' __magic_name__ : str = is_remote_filesystem(_snake_case ) assert is_remote is True __magic_name__ : Optional[int] = fsspec.filesystem("file" ) __magic_name__ : int = is_remote_filesystem(_snake_case ) assert is_remote is False @pytest.mark.parametrize("compression_fs_class" , _snake_case ) def lowerCAmelCase_ ( _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : int , _snake_case : Tuple , _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Any ) -> int: '''simple docstring''' __magic_name__ : Any = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file} __magic_name__ : str = input_paths[compression_fs_class.protocol] if input_path is None: __magic_name__ : Dict = F'''for \'{compression_fs_class.protocol}\' compression protocol, ''' if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(_snake_case ) __magic_name__ : str = fsspec.filesystem(compression_fs_class.protocol , fo=_snake_case ) assert isinstance(_snake_case , _snake_case ) __magic_name__ : int = os.path.basename(_snake_case ) __magic_name__ : Optional[int] = expected_filename[: expected_filename.rindex("." )] assert fs.glob("*" ) == [expected_filename] with fs.open(_snake_case , "r" , encoding="utf-8" ) as f, open(_snake_case , encoding="utf-8" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol" , ["zip", "gzip"] ) def lowerCAmelCase_ ( _snake_case : List[Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] ) -> str: '''simple docstring''' __magic_name__ : int = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} __magic_name__ : int = compressed_file_paths[protocol] __magic_name__ : Tuple = "dataset.jsonl" __magic_name__ : List[str] = F'''{protocol}://{member_file_path}::{compressed_file_path}''' __magic_name__ , *__magic_name__ : Optional[Any] = fsspec.get_fs_token_paths(_snake_case ) assert fs.isfile(_snake_case ) assert not fs.isfile("non_existing_" + member_file_path ) @pytest.mark.integration def lowerCAmelCase_ ( _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : List[str] , _snake_case : Tuple ) -> str: '''simple docstring''' __magic_name__ : int = hf_api.dataset_info(_snake_case , token=_snake_case ) __magic_name__ : Optional[Any] = HfFileSystem(repo_info=_snake_case , token=_snake_case ) assert sorted(hffs.glob("*" ) ) == [".gitattributes", "data"] assert hffs.isdir("data" ) assert hffs.isfile(".gitattributes" ) and hffs.isfile("data/text_data.txt" ) with open(_snake_case ) as f: assert hffs.open("data/text_data.txt" , "r" ).read() == f.read() def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' __magic_name__ : Optional[Any] = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(_snake_case , _snake_case , clobber=_snake_case ) with pytest.warns(_snake_case ) as warning_info: importlib.reload(datasets.filesystems ) assert len(_snake_case ) == 1 assert ( str(warning_info[0].message ) == F'''A filesystem protocol was already set for {protocol} and will be overwritten.''' )
281
1
from __future__ import annotations from dataclasses import dataclass @dataclass class _snake_case : UpperCamelCase__ = 42 UpperCamelCase__ = None UpperCamelCase__ = None def lowerCAmelCase_ ( _snake_case : TreeNode | None ) -> bool: '''simple docstring''' def is_valid_tree(_snake_case : TreeNode | None ) -> bool: if node is None: return True if not isinstance(_snake_case , _snake_case ): return False try: float(node.data ) except (TypeError, ValueError): return False return is_valid_tree(node.left ) and is_valid_tree(node.right ) if not is_valid_tree(_snake_case ): raise ValueError( "Each node should be type of TreeNode and data should be float." ) def is_binary_search_tree_recursive_check( _snake_case : TreeNode | None , _snake_case : float , _snake_case : float ) -> bool: if node is None: return True return ( left_bound < node.data < right_bound and is_binary_search_tree_recursive_check(node.left , _snake_case , node.data ) and is_binary_search_tree_recursive_check( node.right , node.data , _snake_case ) ) return is_binary_search_tree_recursive_check(_snake_case , -float("inf" ) , float("inf" ) ) if __name__ == "__main__": import doctest doctest.testmod()
281
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : List[Any] = { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json", # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class _snake_case ( snake_case ): UpperCamelCase__ = 'convbert' def __init__( self , _a=30_522 , _a=768 , _a=12 , _a=12 , _a=3_072 , _a="gelu" , _a=0.1 , _a=0.1 , _a=512 , _a=2 , _a=0.02 , _a=1e-12 , _a=1 , _a=0 , _a=2 , _a=768 , _a=2 , _a=9 , _a=1 , _a=None , **_a , ): super().__init__( pad_token_id=_a , bos_token_id=_a , eos_token_id=_a , **_a , ) __magic_name__ : Tuple = vocab_size __magic_name__ : List[Any] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : List[Any] = num_attention_heads __magic_name__ : str = intermediate_size __magic_name__ : Any = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Optional[int] = attention_probs_dropout_prob __magic_name__ : Tuple = max_position_embeddings __magic_name__ : str = type_vocab_size __magic_name__ : List[str] = initializer_range __magic_name__ : Tuple = layer_norm_eps __magic_name__ : List[Any] = embedding_size __magic_name__ : List[Any] = head_ratio __magic_name__ : str = conv_kernel_size __magic_name__ : Dict = num_groups __magic_name__ : str = classifier_dropout class _snake_case ( snake_case ): @property def SCREAMING_SNAKE_CASE ( self ): if self.task == "multiple-choice": __magic_name__ : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: __magic_name__ : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
281
1
def lowerCAmelCase_ ( _snake_case : int = 100 ) -> int: '''simple docstring''' __magic_name__ : List[Any] = 0 __magic_name__ : Union[str, Any] = 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() = }")
281
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCAmelCase_ ( ) -> str: '''simple docstring''' __magic_name__ : int = "https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png" __magic_name__ : Union[str, Any] = Image.open(requests.get(_snake_case , stream=_snake_case ).raw ).convert("RGB" ) return image def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.weight''', F'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm1.bias''', F'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.weight''', F'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.norm2.bias''', F'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.qkv.weight''', F'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.weight''', F'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((F'''visual_encoder.blocks.{i}.attn.proj.bias''', F'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc1.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.weight''', F'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((F'''visual_encoder.blocks.{i}.mlp.fc2.bias''', F'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.layernorm.bias") ) # fmt: on return rename_keys def lowerCAmelCase_ ( _snake_case : Any , _snake_case : Union[str, Any] , _snake_case : Optional[Any] ) -> int: '''simple docstring''' __magic_name__ : Tuple = dct.pop(_snake_case ) __magic_name__ : int = val def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : Optional[Any] ) -> Dict: '''simple docstring''' for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases __magic_name__ : List[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.q_bias''' ) __magic_name__ : Optional[Any] = state_dict.pop(F'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict __magic_name__ : Optional[int] = torch.cat((q_bias, torch.zeros_like(_snake_case , requires_grad=_snake_case ), v_bias) ) __magic_name__ : Union[str, Any] = qkv_bias def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : str ) -> int: '''simple docstring''' __magic_name__ : List[Any] = 364 if "coco" in model_name else 224 __magic_name__ : Union[str, Any] = BlipaVisionConfig(image_size=_snake_case ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: __magic_name__ : List[str] = OPTConfig.from_pretrained("facebook/opt-2.7b" , eos_token_id=_snake_case ).to_dict() elif "opt-6.7b" in model_name: __magic_name__ : Any = OPTConfig.from_pretrained("facebook/opt-6.7b" , eos_token_id=_snake_case ).to_dict() elif "t5-xl" in model_name: __magic_name__ : Dict = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: __magic_name__ : int = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() __magic_name__ : List[Any] = BlipaConfig(vision_config=_snake_case , text_config=_snake_case ) return config, image_size @torch.no_grad() def lowerCAmelCase_ ( _snake_case : List[str] , _snake_case : str=None , _snake_case : Dict=False ) -> List[Any]: '''simple docstring''' __magic_name__ : Optional[int] = ( AutoTokenizer.from_pretrained("facebook/opt-2.7b" ) if "opt" in model_name else AutoTokenizer.from_pretrained("google/flan-t5-xl" ) ) __magic_name__ : List[Any] = tokenizer("\n" , add_special_tokens=_snake_case ).input_ids[0] __magic_name__ , __magic_name__ : Tuple = get_blipa_config(_snake_case , eos_token_id=_snake_case ) __magic_name__ : Union[str, Any] = BlipaForConditionalGeneration(_snake_case ).eval() __magic_name__ : Any = { "blip2-opt-2.7b": ("blip2_opt", "pretrain_opt2.7b"), "blip2-opt-6.7b": ("blip2_opt", "pretrain_opt6.7b"), "blip2-opt-2.7b-coco": ("blip2_opt", "caption_coco_opt2.7b"), "blip2-opt-6.7b-coco": ("blip2_opt", "caption_coco_opt6.7b"), "blip2-flan-t5-xl": ("blip2_t5", "pretrain_flant5xl"), "blip2-flan-t5-xl-coco": ("blip2_t5", "caption_coco_flant5xl"), "blip2-flan-t5-xxl": ("blip2_t5", "pretrain_flant5xxl"), } __magic_name__ , __magic_name__ : Union[str, Any] = model_name_to_original[model_name] # load original model print("Loading original model..." ) __magic_name__ : Union[str, Any] = "cuda" if torch.cuda.is_available() else "cpu" __magic_name__ , __magic_name__ , __magic_name__ : Optional[Any] = load_model_and_preprocess( name=_snake_case , model_type=_snake_case , is_eval=_snake_case , device=_snake_case ) original_model.eval() print("Done!" ) # update state dict keys __magic_name__ : Dict = original_model.state_dict() __magic_name__ : str = create_rename_keys(_snake_case ) for src, dest in rename_keys: rename_key(_snake_case , _snake_case , _snake_case ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): __magic_name__ : Any = state_dict.pop(_snake_case ) if key.startswith("Qformer.bert" ): __magic_name__ : Optional[int] = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: __magic_name__ : Any = key.replace("self" , "attention" ) if "opt_proj" in key: __magic_name__ : Union[str, Any] = key.replace("opt_proj" , "language_projection" ) if "t5_proj" in key: __magic_name__ : Optional[int] = key.replace("t5_proj" , "language_projection" ) if key.startswith("opt" ): __magic_name__ : List[str] = key.replace("opt" , "language" ) if key.startswith("t5" ): __magic_name__ : Tuple = key.replace("t5" , "language" ) __magic_name__ : Dict = val # read in qv biases read_in_q_v_bias(_snake_case , _snake_case ) __magic_name__ , __magic_name__ : Tuple = hf_model.load_state_dict(_snake_case , strict=_snake_case ) assert len(_snake_case ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] __magic_name__ : List[Any] = load_demo_image() __magic_name__ : Tuple = vis_processors["eval"](_snake_case ).unsqueeze(0 ).to(_snake_case ) __magic_name__ : Dict = tokenizer(["\n"] , return_tensors="pt" ).input_ids.to(_snake_case ) # create processor __magic_name__ : Optional[Any] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=_snake_case , image_std=_snake_case ) __magic_name__ : Dict = BlipaProcessor(image_processor=_snake_case , tokenizer=_snake_case ) __magic_name__ : Union[str, Any] = processor(images=_snake_case , return_tensors="pt" ).pixel_values.to(_snake_case ) # make sure processor creates exact same pixel values assert torch.allclose(_snake_case , _snake_case ) original_model.to(_snake_case ) hf_model.to(_snake_case ) with torch.no_grad(): if "opt" in model_name: __magic_name__ : List[Any] = original_model({"image": original_pixel_values, "text_input": [""]} ).logits __magic_name__ : Optional[int] = hf_model(_snake_case , _snake_case ).logits else: __magic_name__ : int = original_model( {"image": original_pixel_values, "text_input": ["\n"], "text_output": ["\n"]} ).logits __magic_name__ : Tuple = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) __magic_name__ : List[str] = hf_model(_snake_case , _snake_case , labels=_snake_case ).logits assert original_logits.shape == logits.shape print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": __magic_name__ : List[str] = torch.tensor( [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]] , device=_snake_case ) assert torch.allclose(logits[0, :3, :3] , _snake_case , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": __magic_name__ : Tuple = torch.tensor( [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]] , device=_snake_case ) else: # cast to same type __magic_name__ : str = logits.dtype assert torch.allclose(original_logits.to(_snake_case ) , _snake_case , atol=1E-2 ) print("Looks ok!" ) print("Generating a caption..." ) __magic_name__ : Optional[int] = "" __magic_name__ : Dict = tokenizer(_snake_case , return_tensors="pt" ).input_ids.to(_snake_case ) __magic_name__ : int = original_model.generate({"image": original_pixel_values} ) __magic_name__ : Optional[Any] = hf_model.generate( _snake_case , _snake_case , do_sample=_snake_case , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print("Original generation:" , _snake_case ) __magic_name__ : Tuple = input_ids.shape[1] __magic_name__ : int = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=_snake_case ) __magic_name__ : Union[str, Any] = [text.strip() for text in output_text] print("HF generation:" , _snake_case ) if pytorch_dump_folder_path is not None: processor.save_pretrained(_snake_case ) hf_model.save_pretrained(_snake_case ) if push_to_hub: processor.push_to_hub(F'''nielsr/{model_name}''' ) hf_model.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": snake_case : Any = argparse.ArgumentParser() snake_case : Union[str, Any] = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", choices=choices, type=str, help="Path to hf config.json of model to convert", ) parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub after converting", ) snake_case : int = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
281
1
from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS snake_case : Optional[Any] = logging.get_logger(__name__) snake_case : Union[str, Any] = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class _snake_case ( snake_case ): def __init__( self , _a=None , _a=None , *_a , **_a ): super().__init__(*_a , **_a ) if config is None: assert isinstance(self.model , _a ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f''' {self.model.__class__}''' ) __magic_name__ : List[Any] = self.model.config else: __magic_name__ : Optional[Any] = config __magic_name__ : str = data_args __magic_name__ : int = self.config.tgt_vocab_size if isinstance(self.config , _a ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f'''The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for''' " padding.." ) if self.args.label_smoothing == 0: __magic_name__ : Tuple = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss __magic_name__ : Optional[Any] = label_smoothed_nll_loss def SCREAMING_SNAKE_CASE ( self , _a ): if self.optimizer is None: __magic_name__ : Optional[Any] = ["bias", "LayerNorm.weight"] __magic_name__ : Optional[int] = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], "weight_decay": 0.0, }, ] __magic_name__ : List[str] = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: __magic_name__ : Any = Adafactor __magic_name__ : Tuple = {"scale_parameter": False, "relative_step": False} else: __magic_name__ : Any = AdamW __magic_name__ : str = { "betas": (self.args.adam_betaa, self.args.adam_betaa), "eps": self.args.adam_epsilon, } __magic_name__ : Optional[Any] = self.args.learning_rate if self.sharded_ddp: __magic_name__ : Dict = OSS( params=_a , optim=_a , **_a , ) else: __magic_name__ : List[str] = optimizer_cls(_a , **_a ) if self.lr_scheduler is None: __magic_name__ : str = self._get_lr_scheduler(_a ) else: # ignoring --lr_scheduler logger.warning("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored." ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Dict = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": __magic_name__ : int = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": __magic_name__ : Optional[Any] = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: __magic_name__ : Optional[Any] = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=_a ) return scheduler def SCREAMING_SNAKE_CASE ( self ): if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token __magic_name__ : Optional[int] = model(**_a , use_cache=_a )[0] __magic_name__ : str = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models __magic_name__ , __magic_name__ : Union[str, Any] = model(**_a , labels=_a , use_cache=_a )[:2] else: # compute label smoothed loss __magic_name__ : Any = model(**_a , use_cache=_a )[0] __magic_name__ : str = torch.nn.functional.log_softmax(_a , dim=-1 ) __magic_name__ , __magic_name__ : Tuple = self.loss_fn(_a , _a , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def SCREAMING_SNAKE_CASE ( self , _a , _a ): __magic_name__ : Optional[int] = inputs.pop("labels" ) __magic_name__ , __magic_name__ : Optional[int] = self._compute_loss(_a , _a , _a ) return loss def SCREAMING_SNAKE_CASE ( self , _a , _a , _a , _a = None , ): __magic_name__ : List[str] = self._prepare_inputs(_a ) __magic_name__ : List[str] = { "max_length": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, "num_beams": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: __magic_name__ : Optional[int] = self.model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , **_a , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: __magic_name__ : Dict = self._pad_tensors_to_max_len(_a , gen_kwargs["max_length"] ) __magic_name__ : List[str] = inputs.pop("labels" ) with torch.no_grad(): # compute loss on predict data __magic_name__ , __magic_name__ : Optional[Any] = self._compute_loss(_a , _a , _a ) __magic_name__ : List[Any] = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) __magic_name__ : Dict = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: __magic_name__ : int = self._pad_tensors_to_max_len(_a , gen_kwargs["max_length"] ) return (loss, logits, labels) def SCREAMING_SNAKE_CASE ( self , _a , _a ): # If PAD token is not defined at least EOS token has to be defined __magic_name__ : int = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( "Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be" f''' padded to `max_length`={max_length}''' ) __magic_name__ : int = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) __magic_name__ : Optional[int] = tensor return padded_tensor
281
import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case : Dict = logging.get_logger(__name__) snake_case : Union[str, Any] = { "vocab_file": "vocab.txt", "merges_file": "bpe.codes", } snake_case : Dict = { "vocab_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt", }, "merges_file": { "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes", "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes", }, } snake_case : Union[str, Any] = { "vinai/phobert-base": 256, "vinai/phobert-large": 256, } def lowerCAmelCase_ ( _snake_case : str ) -> Union[str, Any]: '''simple docstring''' __magic_name__ : List[str] = set() __magic_name__ : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __magic_name__ : int = char __magic_name__ : List[str] = set(_snake_case ) return pairs class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , **_a , ): super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , **_a , ) __magic_name__ : Dict = vocab_file __magic_name__ : Tuple = merges_file __magic_name__ : List[Any] = {} __magic_name__ : List[Any] = 0 __magic_name__ : Tuple = 1 __magic_name__ : int = 2 __magic_name__ : Union[str, Any] = 3 self.add_from_file(_a ) __magic_name__ : Optional[int] = {v: k for k, v in self.encoder.items()} with open(_a , encoding="utf-8" ) as merges_handle: __magic_name__ : List[str] = merges_handle.read().split("\n" )[:-1] __magic_name__ : Union[str, Any] = [tuple(merge.split()[:-1] ) for merge in merges] __magic_name__ : Union[str, Any] = dict(zip(_a , range(len(_a ) ) ) ) __magic_name__ : Optional[int] = {} def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __magic_name__ : Optional[Any] = [self.cls_token_id] __magic_name__ : Union[str, Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[Any] = [self.sep_token_id] __magic_name__ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def SCREAMING_SNAKE_CASE ( self ): return len(self.encoder ) def SCREAMING_SNAKE_CASE ( self ): return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE ( self , _a ): if token in self.cache: return self.cache[token] __magic_name__ : List[Any] = tuple(_a ) __magic_name__ : List[Any] = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) __magic_name__ : Any = get_pairs(_a ) if not pairs: return token while True: __magic_name__ : str = min(_a , key=lambda _a : self.bpe_ranks.get(_a , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __magic_name__ , __magic_name__ : List[str] = bigram __magic_name__ : List[str] = [] __magic_name__ : List[str] = 0 while i < len(_a ): try: __magic_name__ : Any = word.index(_a , _a ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __magic_name__ : Tuple = 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 __magic_name__ : Union[str, Any] = tuple(_a ) __magic_name__ : Optional[int] = new_word if len(_a ) == 1: break else: __magic_name__ : List[Any] = get_pairs(_a ) __magic_name__ : Optional[int] = "@@ ".join(_a ) __magic_name__ : Tuple = word[:-4] __magic_name__ : str = word return word def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = [] __magic_name__ : Dict = re.findall(r"\S+\n?" , _a ) for token in words: split_tokens.extend(list(self.bpe(_a ).split(" " ) ) ) return split_tokens def SCREAMING_SNAKE_CASE ( self , _a ): return self.encoder.get(_a , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.decoder.get(_a , self.unk_token ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Tuple = " ".join(_a ).replace("@@ " , "" ).strip() return out_string def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : Optional[int] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __magic_name__ : Union[str, Any] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) if os.path.abspath(self.merges_file ) != os.path.abspath(_a ): copyfile(self.merges_file , _a ) return out_vocab_file, out_merge_file def SCREAMING_SNAKE_CASE ( self , _a ): if isinstance(_a , _a ): try: with open(_a , "r" , encoding="utf-8" ) as fd: self.add_from_file(_a ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset''' ) return __magic_name__ : List[Any] = f.readlines() for lineTmp in lines: __magic_name__ : Optional[Any] = lineTmp.strip() __magic_name__ : Union[str, Any] = line.rfind(" " ) if idx == -1: raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'" ) __magic_name__ : Optional[int] = line[:idx] __magic_name__ : Dict = len(self.encoder )
281
1
# flake8: noqa # Lint as: python3 snake_case : Optional[Any] = [ "VerificationMode", "Version", "disable_progress_bar", "enable_progress_bar", "is_progress_bar_enabled", "experimental", ] from .info_utils import VerificationMode from .logging import disable_progress_bar, enable_progress_bar, is_progress_bar_enabled from .version import Version from .experimental import experimental
281
from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCAmelCase_ ( _snake_case : str = "laptop" ) -> DataFrame: '''simple docstring''' __magic_name__ : Tuple = F'''https://www.amazon.in/laptop/s?k={product}''' __magic_name__ : Dict = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36", "Accept-Language": "en-US, en;q=0.5", } __magic_name__ : Tuple = BeautifulSoup(requests.get(_snake_case , headers=_snake_case ).text ) # Initialize a Pandas dataframe with the column titles __magic_name__ : int = DataFrame( columns=[ "Product Title", "Product Link", "Current Price of the product", "Product Rating", "MRP of the product", "Discount", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( "div" , attrs={"class": "s-result-item", "data-component-type": "s-search-result"} , ) , soup.find_all("div" , attrs={"class": "a-row a-size-base a-color-base"} ) , ): try: __magic_name__ : Dict = item.ha.text __magic_name__ : Optional[int] = "https://www.amazon.in/" + item.ha.a["href"] __magic_name__ : Optional[Any] = item.find("span" , attrs={"class": "a-offscreen"} ).text try: __magic_name__ : Union[str, Any] = item.find("span" , attrs={"class": "a-icon-alt"} ).text except AttributeError: __magic_name__ : Dict = "Not available" try: __magic_name__ : Optional[int] = ( "₹" + item.find( "span" , attrs={"class": "a-price a-text-price"} ).text.split("₹" )[1] ) except AttributeError: __magic_name__ : List[str] = "" try: __magic_name__ : int = float( ( ( float(product_mrp.strip("₹" ).replace("," , "" ) ) - float(product_price.strip("₹" ).replace("," , "" ) ) ) / float(product_mrp.strip("₹" ).replace("," , "" ) ) ) * 100 ) except ValueError: __magic_name__ : str = float("nan" ) except AttributeError: pass __magic_name__ : Optional[int] = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] __magic_name__ : Optional[Any] = " " __magic_name__ : str = " " data_frame.index += 1 return data_frame if __name__ == "__main__": snake_case : Any = "headphones" get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
281
1
import os import pytest from transformers.dynamic_module_utils import get_imports snake_case : Dict = "\nimport os\n" snake_case : Optional[Any] = "\ndef foo():\n import os\n return False\n" snake_case : List[str] = "\ndef foo():\n def bar():\n if True:\n import os\n return False\n return bar()\n" snake_case : Optional[int] = "\nimport os\n\ntry:\n import bar\nexcept ImportError:\n raise ValueError()\n" snake_case : Tuple = "\nimport os\n\ndef foo():\n try:\n import bar\n except ImportError:\n raise ValueError()\n" snake_case : Union[str, Any] = "\nimport os\n\ntry:\n import bar\nexcept (ImportError, AttributeError):\n raise ValueError()\n" snake_case : Optional[int] = "\nimport os\n\ntry:\n import bar\nexcept ImportError as e:\n raise ValueError()\n" snake_case : int = "\nimport os\n\ntry:\n import bar\nexcept:\n raise ValueError()\n" snake_case : List[Any] = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n raise ValueError()\n" snake_case : int = "\nimport os\n\ntry:\n import bar\n import baz\nexcept ImportError:\n x = 1\n raise ValueError()\n" snake_case : Tuple = [ TOP_LEVEL_IMPORT, IMPORT_IN_FUNCTION, DEEPLY_NESTED_IMPORT, TOP_LEVEL_TRY_IMPORT, GENERIC_EXCEPT_IMPORT, MULTILINE_TRY_IMPORT, MULTILINE_BOTH_IMPORT, MULTIPLE_EXCEPTS_IMPORT, EXCEPT_AS_IMPORT, TRY_IMPORT_IN_FUNCTION, ] @pytest.mark.parametrize("case" , _snake_case ) def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : List[str] ) -> Any: '''simple docstring''' __magic_name__ : Optional[Any] = os.path.join(_snake_case , "test_file.py" ) with open(_snake_case , "w" ) as _tmp_file: _tmp_file.write(_snake_case ) __magic_name__ : Tuple = get_imports(_snake_case ) assert parsed_imports == ["os"]
281
from __future__ import annotations class _snake_case : def __init__( self , _a ): __magic_name__ : Optional[Any] = data __magic_name__ : Node | None = None __magic_name__ : Node | None = None def lowerCAmelCase_ ( _snake_case : Node | None ) -> None: # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def lowerCAmelCase_ ( _snake_case : Node | None ) -> int: '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def lowerCAmelCase_ ( _snake_case : Node ) -> bool: '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def lowerCAmelCase_ ( ) -> None: # Main function for testing. '''simple docstring''' __magic_name__ : int = Node(1 ) __magic_name__ : Union[str, Any] = Node(2 ) __magic_name__ : Tuple = Node(3 ) __magic_name__ : Optional[Any] = Node(4 ) __magic_name__ : Union[str, Any] = Node(5 ) __magic_name__ : Any = Node(6 ) __magic_name__ : int = Node(7 ) __magic_name__ : List[str] = Node(8 ) __magic_name__ : Union[str, Any] = Node(9 ) print(is_full_binary_tree(_snake_case ) ) print(depth_of_tree(_snake_case ) ) print("Tree is: " ) display(_snake_case ) if __name__ == "__main__": main()
281
1
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : Any = logging.get_logger(__name__) snake_case : Optional[int] = { "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 _snake_case ( snake_case ): UpperCamelCase__ = 'gpt_neox' def __init__( self , _a=50_432 , _a=6_144 , _a=44 , _a=64 , _a=24_576 , _a="gelu" , _a=0.25 , _a=10_000 , _a=0.0 , _a=0.0 , _a=0.1 , _a=2_048 , _a=0.02 , _a=1e-5 , _a=True , _a=0 , _a=2 , _a=False , _a=True , _a=None , **_a , ): super().__init__(bos_token_id=_a , eos_token_id=_a , **_a ) __magic_name__ : List[Any] = vocab_size __magic_name__ : List[Any] = max_position_embeddings __magic_name__ : Optional[Any] = hidden_size __magic_name__ : Union[str, Any] = num_hidden_layers __magic_name__ : Optional[Any] = num_attention_heads __magic_name__ : List[Any] = intermediate_size __magic_name__ : List[str] = hidden_act __magic_name__ : Union[str, Any] = rotary_pct __magic_name__ : Any = rotary_emb_base __magic_name__ : int = attention_dropout __magic_name__ : Optional[int] = hidden_dropout __magic_name__ : List[str] = classifier_dropout __magic_name__ : List[Any] = initializer_range __magic_name__ : str = layer_norm_eps __magic_name__ : Optional[int] = use_cache __magic_name__ : Any = tie_word_embeddings __magic_name__ : Optional[Any] = use_parallel_residual __magic_name__ : Dict = 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 SCREAMING_SNAKE_CASE ( self ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , _a ) or len(self.rope_scaling ) != 2: raise ValueError( "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, " f'''got {self.rope_scaling}''' ) __magic_name__ : Dict = self.rope_scaling.get("type" , _a ) __magic_name__ : int = self.rope_scaling.get("factor" , _a ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(_a , _a ) or rope_scaling_factor <= 1.0: raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
281
def lowerCAmelCase_ ( _snake_case : str , _snake_case : str ) -> bool: '''simple docstring''' __magic_name__ : Union[str, Any] = len(_snake_case ) + 1 __magic_name__ : List[str] = len(_snake_case ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. __magic_name__ : str = [[0 for i in range(_snake_case )] for j in range(_snake_case )] # since string of zero length match pattern of zero length __magic_name__ : Optional[int] = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , _snake_case ): __magic_name__ : Optional[int] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , _snake_case ): __magic_name__ : Union[str, Any] = dp[0][j - 2] if pattern[j - 1] == "*" else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , _snake_case ): for j in range(1 , _snake_case ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": __magic_name__ : Optional[int] = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: __magic_name__ : Optional[Any] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): __magic_name__ : List[Any] = dp[i - 1][j] else: __magic_name__ : Union[str, Any] = 0 else: __magic_name__ : Dict = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") snake_case : Optional[Any] = "aab" snake_case : List[str] = "c*a*b" # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(F"{input_string} matches the given pattern {pattern}") else: print(F"{input_string} does not match with the given pattern {pattern}")
281
1
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case : int = logging.get_logger(__name__) snake_case : List[str] = {"vocab_file": "spiece.model"} snake_case : List[str] = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", } } snake_case : Tuple = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } snake_case : List[str] = "▁" class _snake_case ( snake_case ): UpperCamelCase__ = VOCAB_FILES_NAMES UpperCamelCase__ = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , _a , _a=True , _a=True , _a=False , _a="[CLS]" , _a="[SEP]" , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , _a = None , **_a , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __magic_name__ : str = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) __magic_name__ : Union[str, Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_a , remove_space=_a , keep_accents=_a , bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) __magic_name__ : Dict = do_lower_case __magic_name__ : Tuple = remove_space __magic_name__ : Union[str, Any] = keep_accents __magic_name__ : Tuple = vocab_file __magic_name__ : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) @property def SCREAMING_SNAKE_CASE ( self ): return len(self.sp_model ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): __magic_name__ : List[str] = self.__dict__.copy() __magic_name__ : Any = None return state def __setstate__( self , _a ): __magic_name__ : Union[str, Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __magic_name__ : str = {} __magic_name__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE ( self , _a ): if self.remove_space: __magic_name__ : List[Any] = " ".join(inputs.strip().split() ) else: __magic_name__ : str = inputs __magic_name__ : int = outputs.replace("``" , "\"" ).replace("''" , "\"" ) if not self.keep_accents: __magic_name__ : str = unicodedata.normalize("NFKD" , _a ) __magic_name__ : Tuple = "".join([c for c in outputs if not unicodedata.combining(_a )] ) if self.do_lower_case: __magic_name__ : int = outputs.lower() return outputs def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Optional[Any] = self.preprocess_text(_a ) __magic_name__ : Dict = self.sp_model.encode(_a , out_type=_a ) __magic_name__ : Any = [] for piece in pieces: if len(_a ) > 1 and piece[-1] == str("," ) and piece[-2].isdigit(): __magic_name__ : Optional[Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(_a , "" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __magic_name__ : List[str] = cur_pieces[1:] else: __magic_name__ : Optional[int] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_a ) else: new_pieces.append(_a ) return new_pieces def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.PieceToId(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): return self.sp_model.IdToPiece(_a ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : Any = [] __magic_name__ : Union[str, Any] = "" __magic_name__ : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_a ) + token __magic_name__ : List[Any] = True __magic_name__ : Optional[int] = [] else: current_sub_tokens.append(_a ) __magic_name__ : Optional[Any] = False out_string += self.sp_model.decode(_a ) return out_string.strip() def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : List[str] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def SCREAMING_SNAKE_CASE ( self , _a , _a = None , _a = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is not None: return [1] + ([0] * len(_a )) + [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): __magic_name__ : Optional[int] = [self.sep_token_id] __magic_name__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ : List[str] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , "wb" ) as fi: __magic_name__ : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
281
import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class _snake_case : @staticmethod def SCREAMING_SNAKE_CASE ( *_a , **_a ): pass def lowerCAmelCase_ ( _snake_case : Image ) -> str: '''simple docstring''' __magic_name__ : Optional[int] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def lowerCAmelCase_ ( _snake_case : Image ) -> Dict: '''simple docstring''' __magic_name__ : List[Any] = np.array(_snake_case ) __magic_name__ : Optional[int] = npimg.shape return {"hash": hashimage(_snake_case ), "shape": shape} @is_pipeline_test @require_vision @require_torch class _snake_case ( unittest.TestCase ): UpperCamelCase__ = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) UpperCamelCase__ = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): __magic_name__ : Dict = MaskGenerationPipeline(model=_a , image_processor=_a ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def SCREAMING_SNAKE_CASE ( self , _a , _a ): pass @require_tf @unittest.skip("Image segmentation not implemented in TF" ) def SCREAMING_SNAKE_CASE ( self ): pass @slow @require_torch def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = pipeline("mask-generation" , model="facebook/sam-vit-huge" ) __magic_name__ : str = image_segmenter("http://images.cocodataset.org/val2017/000000039769.jpg" , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Dict = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.0_21}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, {"mask": {"hash": "e2d0b7a0b7", "shape": (480, 640)}, "scores": 0.99_67}, {"mask": {"hash": "453c7844bd", "shape": (480, 640)}, "scores": 0.9_93}, {"mask": {"hash": "3d44f2926d", "shape": (480, 640)}, "scores": 0.99_09}, {"mask": {"hash": "64033ddc3f", "shape": (480, 640)}, "scores": 0.98_79}, {"mask": {"hash": "801064ff79", "shape": (480, 640)}, "scores": 0.98_34}, {"mask": {"hash": "6172f276ef", "shape": (480, 640)}, "scores": 0.97_16}, {"mask": {"hash": "b49e60e084", "shape": (480, 640)}, "scores": 0.96_12}, {"mask": {"hash": "a811e775fd", "shape": (480, 640)}, "scores": 0.95_99}, {"mask": {"hash": "a6a8ebcf4b", "shape": (480, 640)}, "scores": 0.95_52}, {"mask": {"hash": "9d8257e080", "shape": (480, 640)}, "scores": 0.95_32}, {"mask": {"hash": "32de6454a8", "shape": (480, 640)}, "scores": 0.95_16}, {"mask": {"hash": "af3d4af2c8", "shape": (480, 640)}, "scores": 0.94_99}, {"mask": {"hash": "3c6db475fb", "shape": (480, 640)}, "scores": 0.94_83}, {"mask": {"hash": "c290813fb9", "shape": (480, 640)}, "scores": 0.94_64}, {"mask": {"hash": "b6f0b8f606", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "92ce16bfdf", "shape": (480, 640)}, "scores": 0.9_43}, {"mask": {"hash": "c749b25868", "shape": (480, 640)}, "scores": 0.94_08}, {"mask": {"hash": "efb6cab859", "shape": (480, 640)}, "scores": 0.93_35}, {"mask": {"hash": "1ff2eafb30", "shape": (480, 640)}, "scores": 0.93_26}, {"mask": {"hash": "788b798e24", "shape": (480, 640)}, "scores": 0.92_62}, {"mask": {"hash": "abea804f0e", "shape": (480, 640)}, "scores": 0.89_99}, {"mask": {"hash": "7b9e8ddb73", "shape": (480, 640)}, "scores": 0.89_86}, {"mask": {"hash": "cd24047c8a", "shape": (480, 640)}, "scores": 0.89_84}, {"mask": {"hash": "6943e6bcbd", "shape": (480, 640)}, "scores": 0.88_73}, {"mask": {"hash": "b5f47c9191", "shape": (480, 640)}, "scores": 0.88_71} ] , ) # fmt: on @require_torch @slow def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : str = "facebook/sam-vit-huge" __magic_name__ : str = pipeline("mask-generation" , model=_a ) __magic_name__ : Tuple = image_segmenter( "http://images.cocodataset.org/val2017/000000039769.jpg" , pred_iou_thresh=1 , points_per_batch=256 ) # Shortening by hashing __magic_name__ : Any = [] for i, o in enumerate(outputs["masks"] ): new_outupt += [{"mask": mask_to_test_readable(_a ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(_a , decimals=4 ) , [ {"mask": {"hash": "115ad19f5f", "shape": (480, 640)}, "scores": 1.04_44}, {"mask": {"hash": "6affa964c6", "shape": (480, 640)}, "scores": 1.02_10}, {"mask": {"hash": "dfe28a0388", "shape": (480, 640)}, "scores": 1.01_67}, {"mask": {"hash": "c0a5f4a318", "shape": (480, 640)}, "scores": 1.01_32}, {"mask": {"hash": "fe8065c197", "shape": (480, 640)}, "scores": 1.00_53}, ] , )
281
1
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Tuple = 0 def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Tuple = Path(_a ) / "preprocessor_config.json" __magic_name__ : str = Path(_a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(_a , "w" ) , ) json.dump({"model_type": "clip"} , open(_a , "w" ) ) __magic_name__ : List[str] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Dict = Path(_a ) / "preprocessor_config.json" __magic_name__ : List[str] = Path(_a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(_a , "w" ) , ) json.dump({"model_type": "clip"} , open(_a , "w" ) ) __magic_name__ : List[Any] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : List[str] = CLIPConfig() # Create a dummy config file with image_proceesor_type __magic_name__ : Tuple = Path(_a ) / "preprocessor_config.json" __magic_name__ : int = Path(_a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(_a , "w" ) , ) json.dump({"model_type": "clip"} , open(_a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __magic_name__ : Tuple = AutoImageProcessor.from_pretrained(_a ).to_dict() config_dict.pop("image_processor_type" ) __magic_name__ : List[Any] = CLIPImageProcessor(**_a ) # save in new folder model_config.save_pretrained(_a ) config.save_pretrained(_a ) __magic_name__ : Tuple = AutoImageProcessor.from_pretrained(_a ) # make sure private variable is not incorrectly saved __magic_name__ : int = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Optional[int] = Path(_a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(_a , "w" ) , ) __magic_name__ : Optional[int] = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) def SCREAMING_SNAKE_CASE ( self ): with self.assertRaisesRegex( _a , "clip-base is not a local folder and is not a valid model identifier" ): __magic_name__ : Union[str, Any] = AutoImageProcessor.from_pretrained("clip-base" ) def SCREAMING_SNAKE_CASE ( self ): with self.assertRaisesRegex( _a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): __magic_name__ : List[Any] = AutoImageProcessor.from_pretrained(_a , revision="aaaaaa" ) def SCREAMING_SNAKE_CASE ( self ): with self.assertRaisesRegex( _a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): __magic_name__ : str = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def SCREAMING_SNAKE_CASE ( self ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_a ): __magic_name__ : List[str] = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(_a ): __magic_name__ : Union[str, Any] = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=_a ) __magic_name__ : Any = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) __magic_name__ : List[str] = AutoImageProcessor.from_pretrained(_a , trust_remote_code=_a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def SCREAMING_SNAKE_CASE ( self ): try: AutoConfig.register("custom" , _a ) AutoImageProcessor.register(_a , _a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_a ): AutoImageProcessor.register(_a , _a ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ : Dict = Path(_a ) / "preprocessor_config.json" __magic_name__ : Union[str, Any] = Path(_a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(_a , "w" ) , ) json.dump({"model_type": "clip"} , open(_a , "w" ) ) __magic_name__ : Dict = CustomImageProcessor.from_pretrained(_a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_a ) __magic_name__ : Any = AutoImageProcessor.from_pretrained(_a ) self.assertIsInstance(_a , _a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE ( self ): class _snake_case ( snake_case ): UpperCamelCase__ = True try: AutoConfig.register("custom" , _a ) AutoImageProcessor.register(_a , _a ) # If remote code is not set, the default is to use local __magic_name__ : Optional[int] = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __magic_name__ : Optional[int] = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __magic_name__ : List[Any] = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=_a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(_a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
281
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets snake_case : List[Any] = "\\n@inproceedings{lin-2004-rouge,\n title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",\n author = \"Lin, Chin-Yew\",\n booktitle = \"Text Summarization Branches Out\",\n month = jul,\n year = \"2004\",\n address = \"Barcelona, Spain\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W04-1013\",\n pages = \"74--81\",\n}\n" snake_case : Any = "\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n" snake_case : str = "\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n `\"rougeL\"`: Longest common subsequence based scoring.\n `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric('rouge')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n >>> print(results[\"rouge1\"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results[\"rouge1\"].mid.fmeasure)\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/google-research/google-research/tree/master/rouge"] , reference_urls=[ "https://en.wikipedia.org/wiki/ROUGE_(metric)", "https://github.com/google-research/google-research/tree/master/rouge", ] , ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a=None , _a=True , _a=False ): if rouge_types is None: __magic_name__ : str = ["rouge1", "rouge2", "rougeL", "rougeLsum"] __magic_name__ : List[str] = rouge_scorer.RougeScorer(rouge_types=_a , use_stemmer=_a ) if use_aggregator: __magic_name__ : Dict = scoring.BootstrapAggregator() else: __magic_name__ : str = [] for ref, pred in zip(_a , _a ): __magic_name__ : Union[str, Any] = scorer.score(_a , _a ) if use_aggregator: aggregator.add_scores(_a ) else: scores.append(_a ) if use_aggregator: __magic_name__ : Any = aggregator.aggregate() else: __magic_name__ : List[Any] = {} for key in scores[0]: __magic_name__ : str = [score[key] for score in scores] return result
281
1
import argparse import json import subprocess def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : Optional[int] ) -> Any: '''simple docstring''' __magic_name__ : Dict = [] __magic_name__ : int = ( F'''curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"''' " https://api.github.com/repos/huggingface/transformers/actions/runners" ) __magic_name__ : List[Any] = subprocess.run(_snake_case , shell=_snake_case , stdout=subprocess.PIPE ) __magic_name__ : Any = output.stdout.decode("utf-8" ) __magic_name__ : List[Any] = json.loads(_snake_case ) __magic_name__ : Any = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(_snake_case ) # save the result so we can report them on Slack with open("offline_runners.txt" , "w" ) as fp: fp.write(json.dumps(_snake_case ) ) if len(_snake_case ) > 0: __magic_name__ : int = "\n".join([x["name"] for x in offline_runners] ) raise ValueError(F'''The following runners are offline:\n{failed}''' ) if __name__ == "__main__": def lowerCAmelCase_ ( _snake_case : Optional[Any] ) -> Any: '''simple docstring''' return values.split("," ) snake_case : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--target_runners", default=None, type=list_str, required=True, help="Comma-separated list of runners to check status.", ) parser.add_argument( "--token", default=None, type=str, required=True, help="A token that has actions:read permission." ) snake_case : List[str] = parser.parse_args() get_runner_status(args.target_runners, args.token)
281
snake_case : Optional[int] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def lowerCAmelCase_ ( _snake_case : bytes ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ): __magic_name__ : Tuple = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_snake_case ) __magic_name__ : Optional[int] = "".join(bin(_snake_case )[2:].zfill(8 ) for byte in data ) __magic_name__ : List[Any] = len(_snake_case ) % 6 != 0 if padding_needed: # The padding that will be added later __magic_name__ : List[str] = B"=" * ((6 - len(_snake_case ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_snake_case ) % 6) else: __magic_name__ : List[str] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_snake_case ) , 6 ) ).encode() + padding ) def lowerCAmelCase_ ( _snake_case : str ) -> bytes: '''simple docstring''' if not isinstance(_snake_case , _snake_case ) and not isinstance(_snake_case , _snake_case ): __magic_name__ : List[str] = ( "argument should be a bytes-like object or ASCII string, " F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_snake_case ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_snake_case , _snake_case ): try: __magic_name__ : List[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) __magic_name__ : List[str] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_snake_case ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __magic_name__ : Optional[int] = encoded_data[:-padding] __magic_name__ : Dict = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __magic_name__ : Union[str, Any] = "".join( bin(B64_CHARSET.index(_snake_case ) )[2:].zfill(6 ) for char in encoded_data ) __magic_name__ : List[Any] = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_snake_case ) , 8 ) ] return bytes(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
281
1