code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {"""vocab_file""": """spiece.model"""} lowerCAmelCase__ = { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 lowerCAmelCase__ = { """t5-small""": 5_1_2, """t5-base""": 5_1_2, """t5-large""": 5_1_2, """t5-3b""": 5_1_2, """t5-11b""": 5_1_2, } lowerCAmelCase__ = """▁""" class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ['input_ids', 'attention_mask'] def __init__( self , lowercase , lowercase="</s>" , lowercase="<unk>" , lowercase="<pad>" , lowercase=100 , lowercase=None , lowercase = None , lowercase=True , **lowercase , ) -> None: '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: A__ = [F'<extra_id_{i}>' for i in range(lowercase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens A__ = len(set(filter(lambda lowercase : bool("extra_id" in str(lowercase ) ) , lowercase ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids" " tokens" ) if legacy: logger.warning_once( F'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to' " read the related pull request available at https://github.com/huggingface/transformers/pull/24565" ) A__ = legacy A__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=lowercase , unk_token=lowercase , pad_token=lowercase , extra_ids=lowercase , additional_special_tokens=lowercase , sp_model_kwargs=self.sp_model_kwargs , legacy=lowercase , **lowercase , ) A__ = vocab_file A__ = extra_ids A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowercase ) @staticmethod def UpperCamelCase ( lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: A__ = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( "This tokenizer was incorrectly instantiated with a model max length of" F' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this' " behavior is kept to avoid breaking backwards compatibility when padding/encoding with" " `truncation is True`.\n- Be aware that you SHOULD NOT rely on" F' {pretrained_model_name_or_path} automatically truncating your input to' F' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences' F' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with' " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please" " instantiate this tokenizer with `model_max_length` set to your preferred value." , lowercase , ) return max_model_length @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return self.sp_model.get_piece_size() + self._extra_ids def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = {self.convert_ids_to_tokens(lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowercase , token_ids_a=lowercase , already_has_special_tokens=lowercase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(lowercase )) + [1] return ([0] * len(lowercase )) + [1] + ([0] * len(lowercase )) + [1] def UpperCamelCase ( self ) -> int: '''simple docstring''' return list( set(filter(lambda lowercase : bool(re.search(R"<extra_id_\d+>" , lowercase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' return [self._convert_token_to_id(lowercase ) for token in self.get_sentinel_tokens()] def UpperCamelCase ( self , lowercase ) -> List[int]: '''simple docstring''' if len(lowercase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def UpperCamelCase ( self , lowercase , lowercase = None ) -> List[int]: '''simple docstring''' A__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase ( self , lowercase , lowercase = None ) -> List[int]: '''simple docstring''' A__ = self._add_eos_if_not_present(lowercase ) if token_ids_a is None: return token_ids_a else: A__ = self._add_eos_if_not_present(lowercase ) return token_ids_a + token_ids_a def __getstate__( self ) -> Dict: '''simple docstring''' A__ = self.__dict__.copy() A__ = None return state def __setstate__( self , lowercase ) -> str: '''simple docstring''' A__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): A__ = {} A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase ( self , lowercase , **lowercase ) -> List[str]: '''simple docstring''' if not self.legacy: A__ = SPIECE_UNDERLINE + text.replace(lowercase , " " ) return super().tokenize(lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , **lowercase ) -> Optional[int]: '''simple docstring''' if not self.legacy: A__ = text.startswith(lowercase ) if is_first: A__ = text[1:] A__ = self.sp_model.encode(lowercase , out_type=lowercase ) if not self.legacy and not is_first and not text.startswith(" " ) and tokens[0].startswith(lowercase ): A__ = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def UpperCamelCase ( self , lowercase ) -> Dict: '''simple docstring''' if token.startswith("<extra_id_" ): A__ = re.match(R"<extra_id_(\d+)>" , lowercase ) A__ = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(lowercase ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' if index < self.sp_model.get_piece_size(): A__ = self.sp_model.IdToPiece(lowercase ) else: A__ = F'<extra_id_{self.vocab_size - 1 - index}>' return token def UpperCamelCase ( self , lowercase ) -> List[Any]: '''simple docstring''' A__ = [] A__ = "" A__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(lowercase ) + token A__ = True A__ = [] else: current_sub_tokens.append(lowercase ) A__ = False out_string += self.sp_model.decode(lowercase ) return out_string.strip() def UpperCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(lowercase ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ = os.path.join( lowercase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , lowercase ) elif not os.path.isfile(self.vocab_file ): with open(lowercase , "wb" ) as fi: A__ = self.sp_model.serialized_model_proto() fi.write(lowercase ) return (out_vocab_file,)
68
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Tuple: '''simple docstring''' if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A__ = [[w, v]] if not self.graph.get(lowercase ): A__ = [] def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Any: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self , lowercase=-2 ) -> str: '''simple docstring''' A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s A__ = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> int: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin class a__ : """simple docstring""" def __init__( self ) -> int: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A__ = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A__ = [[w, u]] def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> str: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Dict: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> List[Any]: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin
68
1
import os import numpy import onnx def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: int ) -> Optional[int]: '''simple docstring''' A__ = a.name A__ = b.name A__ = "" A__ = "" A__ = a == b A__ = name_a A__ = name_b return res def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[Any] ) -> Tuple: '''simple docstring''' for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) _graph_replace_input_with(node_proto.attribute[1].g , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> List[Any]: '''simple docstring''' for n in graph_proto.node: _node_replace_input_with(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = list(model.graph.initializer ) A__ = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i A__ = inits[i].name A__ = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Any: '''simple docstring''' A__ = os.path.dirname(SCREAMING_SNAKE_CASE_ ) A__ = os.path.basename(SCREAMING_SNAKE_CASE_ ) A__ = onnx.load(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) A__ = list(model.graph.initializer ) A__ = set() A__ = {} A__ = [] A__ = 0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): if i in dup_set: continue for j in range(i + 1 , len(SCREAMING_SNAKE_CASE_ ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(SCREAMING_SNAKE_CASE_ ) dup_set.add(SCREAMING_SNAKE_CASE_ ) A__ = inits[j].data_type A__ = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 1_1: mem_size *= 8 else: print("unexpected data type: " , SCREAMING_SNAKE_CASE_ ) total_reduced_size += mem_size A__ = inits[i].name A__ = inits[j].name if name_i in dup_map: dup_map[name_i].append(SCREAMING_SNAKE_CASE_ ) else: A__ = [name_j] ind_to_replace.append((j, i) ) print("total reduced size: " , total_reduced_size / 1_0_2_4 / 1_0_2_4 / 1_0_2_4 , "GB" ) A__ = sorted(SCREAMING_SNAKE_CASE_ ) _remove_dup_initializers_from_model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ = "optimized_" + model_file_name A__ = os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) onnx.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return new_model
68
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { """configuration_instructblip""": [ """INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """InstructBlipConfig""", """InstructBlipQFormerConfig""", """InstructBlipVisionConfig""", ], """processing_instructblip""": ["""InstructBlipProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """InstructBlipQFormerModel""", """InstructBlipPreTrainedModel""", """InstructBlipForConditionalGeneration""", """InstructBlipVisionModel""", ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
1
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class a__ : """simple docstring""" __lowerCamelCase = 42 __lowerCamelCase = None # Automatically constructed __lowerCamelCase = "dict" __lowerCamelCase = None __lowerCamelCase = field(default='Translation' , init=snake_case , repr=snake_case ) def __call__( self ) -> int: '''simple docstring''' return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def UpperCamelCase ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Value return {k: Value("string" ) for k in sorted(self.languages )} @dataclass class a__ : """simple docstring""" __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None # Automatically constructed __lowerCamelCase = "dict" __lowerCamelCase = None __lowerCamelCase = field(default='TranslationVariableLanguages' , init=snake_case , repr=snake_case ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = sorted(set(self.languages ) ) if self.languages else None A__ = len(self.languages ) if self.languages else None def __call__( self ) -> Any: '''simple docstring''' return pa.struct({"language": pa.list_(pa.string() ), "translation": pa.list_(pa.string() )} ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = set(self.languages ) if self.languages and set(lowercase ) - lang_set: raise ValueError( F'Some languages in example ({", ".join(sorted(set(lowercase ) - lang_set ) )}) are not in valid set ({", ".join(lowercase )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. A__ = [] for lang, text in translation_dict.items(): if isinstance(lowercase , lowercase ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. A__ , A__ = zip(*sorted(lowercase ) ) return {"language": languages, "translation": translations} def UpperCamelCase ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: '''simple docstring''' from .features import Sequence, Value return { "language": Sequence(Value("string" ) ), "translation": Sequence(Value("string" ) ), }
68
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
1
import csv import tweepy # Twitter API credentials lowerCAmelCase__ = """""" lowerCAmelCase__ = """""" lowerCAmelCase__ = """""" lowerCAmelCase__ = """""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' A__ = tweepy.OAuthHandler(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) auth.set_access_token(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) A__ = tweepy.API(SCREAMING_SNAKE_CASE_ ) # initialize a list to hold all the tweepy Tweets A__ = [] # make initial request for most recent tweets (200 is the maximum allowed count) A__ = api.user_timeline(screen_name=SCREAMING_SNAKE_CASE_ , count=2_0_0 ) # save most recent tweets alltweets.extend(SCREAMING_SNAKE_CASE_ ) # save the id of the oldest tweet less one A__ = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(SCREAMING_SNAKE_CASE_ ) > 0: print(F'getting tweets before {oldest}' ) # all subsequent requests use the max_id param to prevent duplicates A__ = api.user_timeline( screen_name=SCREAMING_SNAKE_CASE_ , count=2_0_0 , max_id=SCREAMING_SNAKE_CASE_ ) # save most recent tweets alltweets.extend(SCREAMING_SNAKE_CASE_ ) # update the id of the oldest tweet less one A__ = alltweets[-1].id - 1 print(F'...{len(SCREAMING_SNAKE_CASE_ )} tweets downloaded so far' ) # transform the tweepy tweets into a 2D array that will populate the csv A__ = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F'new_{screen_name}_tweets.csv' , "w" ) as f: A__ = csv.writer(SCREAMING_SNAKE_CASE_ ) writer.writerow(["id", "created_at", "text"] ) writer.writerows(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
68
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: A__ = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE_ ) A__ = num - key if num < 0: A__ = num + len(string.ascii_uppercase ) A__ = translated + string.ascii_uppercase[num] else: A__ = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = input("Encrypted message: " ) A__ = message.upper() decrypt(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int = 1_0_0 ) -> int: '''simple docstring''' A__ = (n * (n + 1) // 2) ** 2 A__ = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f"""{solution() = }""")
68
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = SpeechTaTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(lowercase ) A__ = AddedToken("<mask>" , lstrip=lowercase , rstrip=lowercase ) A__ = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = "this is a test" A__ = "this is a test" return input_text, output_text def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=20 , lowercase=5 ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.get_input_output_texts(lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) return text, ids def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = "<pad>" A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(lowercase ) , 81 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] A__ = tokenizer.add_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size + len(lowercase ) ) A__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) A__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A__ = tokenizer.add_special_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size_a + len(lowercase ) ) A__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(lowercase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) A__ = tokenizer.convert_tokens_to_ids(lowercase ) # fmt: off self.assertListEqual(lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off A__ = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=lowercase , )
68
1
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = CanineTokenizer __lowerCamelCase = False def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' super().setUp() A__ = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return CanineTokenizer.from_pretrained("google/canine-s" ) def UpperCamelCase ( self , **lowercase ) -> CanineTokenizer: '''simple docstring''' A__ = self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase ) A__ = 1024 return tokenizer @require_torch def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = ["Life is like a box of chocolates.", "You never know what you're gonna get."] # fmt: off A__ = [57344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 57345, 0, 0, 0, 0] # fmt: on A__ = tokenizer(lowercase , padding=lowercase , return_tensors="pt" ) self.assertIsInstance(lowercase , lowercase ) A__ = list(batch.input_ids.numpy()[0] ) self.assertListEqual(lowercase , lowercase ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."] A__ = tokenizer(lowercase , padding=lowercase , return_tensors="pt" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("input_ids" , lowercase ) self.assertIn("attention_mask" , lowercase ) self.assertIn("token_type_ids" , lowercase ) @require_torch def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = [ "What's the weater?", "It's about 25 degrees.", ] A__ = tokenizer( text_target=lowercase , max_length=32 , padding="max_length" , truncation=lowercase , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc A__ = tempfile.mkdtemp() A__ = " He is very happy, UNwant\u00E9d,running" A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) A__ = tokenizer.__class__.from_pretrained(lowercase ) A__ = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) shutil.rmtree(lowercase ) A__ = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc A__ = tempfile.mkdtemp() A__ = " He is very happy, UNwant\u00E9d,running" A__ = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: A__ = chr(0XE_0_0_7 ) additional_special_tokens.append(lowercase ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) A__ = tokenizer.__class__.from_pretrained(lowercase ) A__ = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) self.assertIn(lowercase , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) A__ = tokenizer.__class__.from_pretrained(lowercase , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(lowercase ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ , A__ = self.get_clean_sequence(lowercase ) # a special token for Canine can be defined as follows: A__ = 0XE_0_0_5 A__ = chr(lowercase ) tokenizer.add_special_tokens({"cls_token": special_token} ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertEqual(len(lowercase ) , 1 ) A__ = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertEqual(lowercase , input_encoded + special_token_id ) A__ = tokenizer.decode(lowercase , skip_special_tokens=lowercase ) self.assertTrue(special_token not in decoded ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = chr(0XE_0_0_5 ) A__ = chr(0XE_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=lowercase ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]} ) A__ = tokenizer.tokenize(lowercase ) A__ = tokenizer.tokenize(lowercase ) self.assertEqual(len(lowercase ) , 1 ) self.assertEqual(len(lowercase ) , 1 ) self.assertEqual(token_a[0] , lowercase ) self.assertEqual(token_a[0] , lowercase ) @require_tokenizers def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: A__ = 0XE_0_0_6 A__ = chr(lowercase ) A__ = AddedToken(lowercase , lstrip=lowercase ) tokenizer.add_special_tokens({"additional_special_tokens": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(lowercase ) tokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowercase ) with open(os.path.join(lowercase , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: A__ = json.load(lowercase ) with open(os.path.join(lowercase , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: A__ = json.load(lowercase ) # a special token for Canine can be defined as follows: A__ = 0XE_0_0_6 A__ = chr(lowercase ) A__ = [new_token_a] A__ = [new_token_a] with open(os.path.join(lowercase , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase , lowercase ) with open(os.path.join(lowercase , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase , lowercase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files A__ = tokenizer_class.from_pretrained(lowercase , extra_ids=0 ) self.assertIn(lowercase , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) A__ = 0XE_0_0_7 A__ = chr(lowercase ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained A__ = [AddedToken(lowercase , lstrip=lowercase )] A__ = tokenizer_class.from_pretrained( lowercase , additional_special_tokens=lowercase , extra_ids=0 ) self.assertIn(lowercase , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = "hello world" if self.space_between_special_tokens: A__ = "[CLS] hello world [SEP]" else: A__ = input A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(lowercase , [output, output.lower()] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] A__ = "a" A__ = ord(lowercase ) for attr in attributes_list: setattr(lowercase , attr + "_id" , lowercase ) self.assertEqual(getattr(lowercase , lowercase ) , lowercase ) self.assertEqual(getattr(lowercase , attr + "_id" ) , lowercase ) setattr(lowercase , attr + "_id" , lowercase ) self.assertEqual(getattr(lowercase , lowercase ) , lowercase ) self.assertEqual(getattr(lowercase , attr + "_id" ) , lowercase ) setattr(lowercase , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens_ids" ) , [] ) A__ = 0XE_0_0_6 A__ = chr(lowercase ) setattr(lowercase , "additional_special_tokens_ids" , [additional_special_token_id] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens" ) , [additional_special_token] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens_ids" ) , [additional_special_token_id] ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' pass
68
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> List[str]: '''simple docstring''' A__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } A__ = F'{src_lang}-{tgt_lang}' A__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) # make sure we are under the root of the project lowerCAmelCase__ = Path(__file__).resolve().parent.parent.parent lowerCAmelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = model_name.split("""-""") lowerCAmelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: int ) -> list[str]: '''simple docstring''' return [sentence[i : i + ngram_size] for i in range(len(SCREAMING_SNAKE_CASE_ ) - ngram_size + 1 )] if __name__ == "__main__": from doctest import testmod testmod()
68
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = feature_size A__ = sampling_rate A__ = padding_value A__ = kwargs.pop("padding_side" , "right" ) A__ = kwargs.pop("return_attention_mask" , lowercase ) super().__init__(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = None , lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys() )}' ) A__ = processed_features[self.model_input_names[0]] A__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase ) == 0: if return_attention_mask: A__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A__ = required_input[0] if isinstance(lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase ): A__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase ): A__ = "tf" elif is_torch_tensor(lowercase ): A__ = "pt" elif isinstance(lowercase , (int, float, list, tuple, np.ndarray) ): A__ = "np" else: raise ValueError( F'type of {first_element} unknown: {type(lowercase )}. ' "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A__ = to_numpy(lowercase ) else: A__ = [to_numpy(lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy A__ = self._get_padding_strategies(padding=lowercase , max_length=lowercase ) A__ = processed_features[self.model_input_names[0]] A__ = len(lowercase ) if not all(len(lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) A__ = [] for i in range(lowercase ): A__ = {k: v[i] for k, v in processed_features.items()} # truncation A__ = self._truncate( lowercase , max_length=lowercase , pad_to_multiple_of=lowercase , truncation=lowercase , ) truncated_inputs.append(lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A__ = PaddingStrategy.MAX_LENGTH A__ = {} for i in range(lowercase ): # padding A__ = self._pad( truncated_inputs[i] , max_length=lowercase , padding_strategy=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: A__ = [] if value.dtype is np.dtype(np.floataa ): A__ = value.astype(np.floataa ) batch_outputs[key].append(lowercase ) return BatchFeature(lowercase , tensor_type=lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = PaddingStrategy.DO_NOT_PAD , lowercase = None , lowercase = None , ) -> dict: '''simple docstring''' A__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A__ = len(lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A__ = np.ones(len(lowercase ) , dtype=np.intaa ) if needs_to_be_padded: A__ = max_length - len(lowercase ) if self.padding_side == "right": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (0, difference) ) A__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (difference, 0) ) A__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , ) -> Union[str, Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) A__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = len(lowercase ) > max_length if needs_to_be_truncated: A__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A__ = processed_features["attention_mask"][:max_length] return processed_features def UpperCamelCase ( self , lowercase=False , lowercase=None ) -> Any: '''simple docstring''' if padding is not False: if padding is True: A__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase , lowercase ): A__ = PaddingStrategy(lowercase ) elif isinstance(lowercase , lowercase ): A__ = padding else: A__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
68
1
import gc import random import unittest import numpy as np import torch from transformers import XLMRobertaTokenizer from diffusers import ( AltDiffusionImgaImgPipeline, AutoencoderKL, PNDMScheduler, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) 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 enable_full_determinism() class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = 1 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(lowercase ) return image @property def UpperCamelCase ( self ) -> str: '''simple docstring''' torch.manual_seed(0 ) A__ = 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 , ) return model @property def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' torch.manual_seed(0 ) A__ = 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 , ) return model @property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' torch.manual_seed(0 ) A__ = RobertaSeriesConfig( hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5006 , ) return RobertaSeriesModelWithTransformation(lowercase ) @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' def extract(*lowercase , **lowercase ): class a__ : """simple docstring""" def __init__( self ) -> List[Any]: '''simple docstring''' A__ = torch.ones([0] ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' self.pixel_values.to(lowercase ) return self return Out() return extract def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = "cpu" # ensure determinism for the device-dependent torch.Generator A__ = self.dummy_cond_unet A__ = PNDMScheduler(skip_prk_steps=lowercase ) A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) A__ = 77 A__ = self.dummy_image.to(lowercase ) A__ = init_image / 2 + 0.5 # make sure here that pndm scheduler skips prk A__ = AltDiffusionImgaImgPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) A__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowercase ) A__ = alt_pipe.to(lowercase ) alt_pipe.set_progress_bar_config(disable=lowercase ) A__ = "A painting of a squirrel eating a burger" A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = alt_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowercase , ) A__ = output.images A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = alt_pipe( [prompt] , generator=lowercase , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , image=lowercase , return_dict=lowercase , )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ = np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.dummy_cond_unet A__ = PNDMScheduler(skip_prk_steps=lowercase ) A__ = self.dummy_vae A__ = self.dummy_text_encoder A__ = XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta" ) A__ = 77 A__ = self.dummy_image.to(lowercase ) # put models in fp16 A__ = unet.half() A__ = vae.half() A__ = bert.half() # make sure here that pndm scheduler skips prk A__ = AltDiffusionImgaImgPipeline( unet=lowercase , scheduler=lowercase , vae=lowercase , text_encoder=lowercase , tokenizer=lowercase , safety_checker=lowercase , feature_extractor=self.dummy_extractor , ) A__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=lowercase ) A__ = alt_pipe.to(lowercase ) alt_pipe.set_progress_bar_config(disable=lowercase ) A__ = "A painting of a squirrel eating a burger" A__ = torch.manual_seed(0 ) A__ = alt_pipe( [prompt] , generator=lowercase , num_inference_steps=2 , output_type="np" , image=lowercase , ).images assert image.shape == (1, 32, 32, 3) @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 A__ = init_image.resize((760, 504) ) A__ = "BAAI/AltDiffusion" A__ = AltDiffusionImgaImgPipeline.from_pretrained( lowercase , safety_checker=lowercase , ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing() A__ = "A fantasy landscape, trending on artstation" A__ = torch.manual_seed(0 ) A__ = pipe( prompt=lowercase , image=lowercase , strength=0.75 , guidance_scale=7.5 , generator=lowercase , output_type="np" , ) A__ = output.images[0] A__ = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) A__ = np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> int: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) A__ = init_image.resize((768, 512) ) A__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy" ) A__ = "BAAI/AltDiffusion" A__ = AltDiffusionImgaImgPipeline.from_pretrained( lowercase , safety_checker=lowercase , ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) pipe.enable_attention_slicing() A__ = "A fantasy landscape, trending on artstation" A__ = torch.manual_seed(0 ) A__ = pipe( prompt=lowercase , image=lowercase , strength=0.75 , guidance_scale=7.5 , generator=lowercase , output_type="np" , ) A__ = output.images[0] assert image.shape == (512, 768, 3) # img2img is flaky across GPUs even in fp32, so using MAE here assert np.abs(expected_image - image ).max() < 1e-2
68
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCAmelCase__ ( ) -> Optional[Any]: '''simple docstring''' raise RuntimeError("CUDA out of memory." ) class a__ ( nn.Module ): """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' super().__init__() A__ = nn.Linear(3 , 4 ) A__ = nn.BatchNormad(4 ) A__ = nn.Linear(4 , 5 ) def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return self.lineara(self.batchnorm(self.lineara(lowercase ) ) ) class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowercase ): nonlocal batch_sizes batch_sizes.append(lowercase ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(lowercase , [128, 64, 32, 16, 8] ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowercase , lowercase ): nonlocal batch_sizes batch_sizes.append(lowercase ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga A__ , A__ = mock_training_loop_function("hello" ) self.assertListEqual(lowercase , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, "hello"] ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(lowercase ): pass with self.assertRaises(lowercase ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(lowercase ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(lowercase ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(lowercase , lowercase , lowercase ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(lowercase ) as cm: mock_training_loop_function(128 , "hello" , "world" ) self.assertIn("Batch size was passed into `f`" , cm.exception.args[0] ) self.assertIn("`f(arg1='hello', arg2='world')" , cm.exception.args[0] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(lowercase ): raise ValueError("Oops, we had an error!" ) with self.assertRaises(lowercase ) as cm: mock_training_loop_function() self.assertIn("Oops, we had an error!" , cm.exception.args[0] ) @require_cuda def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = torch.cuda.memory_allocated() A__ = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , lowercase ) A__ = release_memory(lowercase ) self.assertEqual(torch.cuda.memory_allocated() , lowercase )
68
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'gpt_neox_japanese' def __init__( self , lowercase=32000 , lowercase=2560 , lowercase=32 , lowercase=32 , lowercase=4 , lowercase="gelu" , lowercase=1.00 , lowercase=10000 , lowercase=2048 , lowercase=0.02 , lowercase=1e-5 , lowercase=True , lowercase=31996 , lowercase=31999 , lowercase=0.1 , lowercase=0.0 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_multiple_size A__ = hidden_act A__ = rotary_pct A__ = rotary_emb_base A__ = initializer_range A__ = layer_norm_eps A__ = use_cache A__ = attention_dropout A__ = hidden_dropout
68
1
class a__ : """simple docstring""" def __init__( self , lowercase , lowercase , lowercase ) -> str: '''simple docstring''' A__ = None A__ = None A__ = graph self._normalize_graph(lowercase , lowercase ) A__ = len(lowercase ) A__ = None def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' if sources is int: A__ = [sources] if sinks is int: A__ = [sinks] if len(lowercase ) == 0 or len(lowercase ) == 0: return A__ = sources[0] A__ = sinks[0] # make fake vertex if there are more # than one source or sink if len(lowercase ) > 1 or len(lowercase ) > 1: A__ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) A__ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: A__ = max_input_flow A__ = 0 A__ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: A__ = max_input_flow A__ = size - 1 def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before." ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = algorithm(self ) class a__ : """simple docstring""" def __init__( self , lowercase ) -> List[Any]: '''simple docstring''' A__ = flow_network A__ = flow_network.verticesCount A__ = flow_network.sourceIndex A__ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that A__ = flow_network.graph A__ = False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' if not self.executed: self._algorithm() A__ = True def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' pass class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase ) -> List[Any]: '''simple docstring''' super().__init__(lowercase ) # use this to save your result A__ = -1 def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' if not self.executed: raise Exception("You should execute algorithm before using its result!" ) return self.maximum_flow class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase ) -> Dict: '''simple docstring''' super().__init__(lowercase ) A__ = [[0] * self.verticies_count for i in range(self.verticies_count )] A__ = [0] * self.verticies_count A__ = [0] * self.verticies_count def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule A__ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list A__ = 0 while i < len(lowercase ): A__ = vertices_list[i] A__ = self.heights[vertex_index] self.process_vertex(lowercase ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(lowercase ) ) A__ = 0 else: i += 1 A__ = sum(self.preflow[self.source_index] ) def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(lowercase , lowercase ) self.relabel(lowercase ) def UpperCamelCase ( self , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def UpperCamelCase ( self , lowercase ) -> Dict: '''simple docstring''' A__ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): A__ = self.heights[to_index] if min_height is not None: A__ = min_height + 1 if __name__ == "__main__": lowerCAmelCase__ = [0] lowerCAmelCase__ = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] lowerCAmelCase__ = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network lowerCAmelCase__ = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate lowerCAmelCase__ = flow_network.find_maximum_flow() print(f"""maximum flow is {maximum_flow}""")
68
import warnings from functools import wraps from typing import Callable def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Callable ) -> Callable: '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_: int , **SCREAMING_SNAKE_CASE_: Union[str, Any] ): warnings.warn( (F'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
68
1
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> str: '''simple docstring''' A__ = "" for i in sequence: A__ = ord(SCREAMING_SNAKE_CASE_ ) if 6_5 <= extract <= 9_0: output += chr(1_5_5 - extract ) elif 9_7 <= extract <= 1_2_2: output += chr(2_1_9 - extract ) else: output += i return output def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> str: '''simple docstring''' A__ = string.ascii_letters A__ = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(SCREAMING_SNAKE_CASE_ )] if c in letters else c for c in sequence ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' from timeit import timeit print("Running performance benchmarks..." ) A__ = "from string import printable ; from __main__ import atbash, atbash_slow" print(F'> atbash_slow(): {timeit("atbash_slow(printable)" , setup=SCREAMING_SNAKE_CASE_ )} seconds' ) print(F'> atbash(): {timeit("atbash(printable)" , setup=SCREAMING_SNAKE_CASE_ )} seconds' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"""{example} encrypted in atbash: {atbash(example)}""") benchmark()
68
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
1
import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> int: '''simple docstring''' A__ = np.max(_outputs , axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) A__ = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'sigmoid' __lowerCamelCase = 'softmax' __lowerCamelCase = 'none' @add_end_docstrings( snake_case , r'\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `"default"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `"sigmoid"`: Applies the sigmoid function on the output.\n - `"softmax"`: Applies the softmax function on the output.\n - `"none"`: Does not apply any function on the output.\n ' , ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = False __lowerCamelCase = ClassificationFunction.NONE def __init__( self , **lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(**lowercase ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def UpperCamelCase ( self , lowercase=None , lowercase=None , lowercase="" , **lowercase ) -> Optional[int]: '''simple docstring''' A__ = tokenizer_kwargs A__ = {} if hasattr(self.model.config , "return_all_scores" ) and return_all_scores is None: A__ = self.model.config.return_all_scores if isinstance(lowercase , lowercase ) or top_k is None: A__ = top_k A__ = False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`." , lowercase , ) if return_all_scores: A__ = None else: A__ = 1 if isinstance(lowercase , lowercase ): A__ = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: A__ = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self , *lowercase , **lowercase ) -> Any: '''simple docstring''' A__ = super().__call__(*lowercase , **lowercase ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. A__ = "top_k" not in kwargs if isinstance(args[0] , lowercase ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def UpperCamelCase ( self , lowercase , **lowercase ) -> Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework if isinstance(lowercase , lowercase ): return self.tokenizer(**lowercase , return_tensors=lowercase , **lowercase ) elif isinstance(lowercase , lowercase ) and len(lowercase ) == 1 and isinstance(inputs[0] , lowercase ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=lowercase , **lowercase ) elif isinstance(lowercase , lowercase ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair." ) return self.tokenizer(lowercase , return_tensors=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase ) -> Dict: '''simple docstring''' return self.model(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase=None , lowercase=1 , lowercase=True ) -> Tuple: '''simple docstring''' if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: A__ = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: A__ = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , "function_to_apply" ) and function_to_apply is None: A__ = self.model.config.function_to_apply else: A__ = ClassificationFunction.NONE A__ = model_outputs["logits"][0] A__ = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: A__ = sigmoid(lowercase ) elif function_to_apply == ClassificationFunction.SOFTMAX: A__ = softmax(lowercase ) elif function_to_apply == ClassificationFunction.NONE: A__ = outputs else: raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}' ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} A__ = [ {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(lowercase ) ] if not _legacy: dict_scores.sort(key=lambda lowercase : x["score"] , reverse=lowercase ) if top_k is not None: A__ = dict_scores[:top_k] return dict_scores
68
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class a__ : """simple docstring""" __lowerCamelCase = BlenderbotSmallConfig __lowerCamelCase = {} __lowerCamelCase = 'gelu' def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=False , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase=0.1 , lowercase=0.1 , lowercase=20 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) A__ = prepare_blenderbot_small_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = TFBlenderbotSmallModel(config=lowercase ).get_decoder() A__ = inputs_dict["input_ids"] A__ = input_ids[:1, :] A__ = inputs_dict["attention_mask"][:1, :] A__ = inputs_dict["head_mask"] A__ = 1 # first forward pass A__ = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(lowercase , attention_mask=lowercase )[0] A__ = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1e-3 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Optional[Any]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Dict=None , SCREAMING_SNAKE_CASE_: List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: A__ = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_tokenizers @require_tf class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __lowerCamelCase = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.tokenizer(self.src_text , return_tensors="tf" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
68
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """microsoft/swin-tiny-patch4-window7-224""": ( """https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json""" ), # See all Swin models at https://huggingface.co/models?filter=swin } class a__ ( snake_case , snake_case ): """simple docstring""" __lowerCamelCase = 'swin' __lowerCamelCase = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , lowercase=224 , lowercase=4 , lowercase=3 , lowercase=96 , lowercase=[2, 2, 6, 2] , lowercase=[3, 6, 12, 24] , lowercase=7 , lowercase=4.0 , lowercase=True , lowercase=0.0 , lowercase=0.0 , lowercase=0.1 , lowercase="gelu" , lowercase=False , lowercase=0.02 , lowercase=1e-5 , lowercase=32 , lowercase=None , lowercase=None , **lowercase , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**lowercase ) A__ = image_size A__ = patch_size A__ = num_channels A__ = embed_dim A__ = depths A__ = len(lowercase ) A__ = num_heads A__ = window_size A__ = mlp_ratio A__ = qkv_bias A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = drop_path_rate A__ = hidden_act A__ = use_absolute_embeddings A__ = layer_norm_eps A__ = initializer_range A__ = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model A__ = int(embed_dim * 2 ** (len(lowercase ) - 1) ) A__ = ["stem"] + [F'stage{idx}' for idx in range(1 , len(lowercase ) + 1 )] A__ , A__ = get_aligned_output_features_output_indices( out_features=lowercase , out_indices=lowercase , stage_names=self.stage_names ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = version.parse('1.11' ) @property def UpperCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase ( self ) -> float: '''simple docstring''' return 1e-4
68
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 convert_to_rgb, 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 if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = 1 / 255 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 384, "width": 384} A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = do_resize A__ = size A__ = resample A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ = image_std if image_std is not None else OPENAI_CLIP_STD A__ = do_convert_rgb def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase , default_to_square=lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) A__ = (size["height"], size["width"]) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = resample if resample is not None else self.resample A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = size if size is not None else self.size A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_rescale: A__ = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase ) return encoded_outputs
68
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") lowerCAmelCase__ = {"""target_lang""": """fi""", """source_lang""": """en"""} lowerCAmelCase__ = """>>zh<<""" lowerCAmelCase__ = """Helsinki-NLP/""" if is_torch_available(): lowerCAmelCase__ = """pt""" elif is_tf_available(): lowerCAmelCase__ = """tf""" else: lowerCAmelCase__ = """jax""" @require_sentencepiece class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = MarianTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> int: '''simple docstring''' super().setUp() A__ = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] A__ = dict(zip(lowercase , range(len(lowercase ) ) ) ) A__ = Path(self.tmpdirname ) save_json(lowercase , save_dir / VOCAB_FILES_NAMES["vocab"] ) save_json(lowercase , save_dir / VOCAB_FILES_NAMES["tokenizer_config_file"] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(lowercase , save_dir / VOCAB_FILES_NAMES["source_spm"] ) copyfile(lowercase , save_dir / VOCAB_FILES_NAMES["target_spm"] ) A__ = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , **lowercase ) -> MarianTokenizer: '''simple docstring''' return MarianTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' return ( "This is a test", "This is a test", ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = "</s>" A__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<pad>" ) self.assertEqual(len(lowercase ) , 9 ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = MarianTokenizer.from_pretrained(F'{ORG_NAME}opus-mt-en-de' ) A__ = en_de_tokenizer(["I am a small frog"] , return_tensors=lowercase ) self.assertIsInstance(lowercase , lowercase ) A__ = [38, 121, 14, 697, 38848, 0] self.assertListEqual(lowercase , batch.input_ids[0] ) A__ = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(lowercase ) A__ = [x.name for x in Path(lowercase ).glob("*" )] self.assertIn("source.spm" , lowercase ) MarianTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tok( ["I am a small frog" * 1000, "I am a small frog"] , padding=lowercase , truncation=lowercase , return_tensors=lowercase ) self.assertIsInstance(lowercase , lowercase ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tok(["I am a tiny frog", "I am a small frog"] , padding=lowercase , return_tensors=lowercase ) self.assertIsInstance(lowercase , lowercase ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = {"input_ids": [[43495, 462, 20, 42164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 38999, 6, 8, 464, 132, 1703, 492, 13, 4669, 37867, 13, 7525, 27, 1593, 988, 13, 33972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 12338, 2, 13958, 387, 2, 3629, 6953, 188, 2900, 2, 13958, 8011, 11501, 23, 8460, 4073, 34009, 20, 435, 11439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 37867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 26453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 10767, 6, 316, 304, 4239, 3, 0], [148, 15722, 19, 1839, 12, 1350, 13, 22327, 5082, 5418, 47567, 35938, 59, 318, 19552, 108, 2183, 54, 14976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 19088, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100], [36, 6395, 12570, 39147, 11597, 6, 266, 4, 45405, 7296, 3, 0, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100, 58100]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="Helsinki-NLP/opus-mt-en-de" , revision="1a8c2263da11e68e50938f97e10cd57820bd504c" , decode_kwargs={"use_source_tokenizer": True} , ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs" ) A__ = "Tämä on testi" A__ = "This is a test" A__ = [76, 7, 2047, 2] A__ = [69, 12, 11, 940, 2] A__ = tokenizer(lowercase ).input_ids self.assertListEqual(lowercase , lowercase ) A__ = tokenizer(text_target=lowercase ).input_ids self.assertListEqual(lowercase , lowercase ) A__ = tokenizer.decode(lowercase , skip_special_tokens=lowercase ) self.assertEqual(lowercase , lowercase )
68
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = """hf-internal-testing/tiny-random-bert""" lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""") lowerCAmelCase__ = """9b8c223d42b2188cb49d29af482996f9d0f3e5a6""" class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = cached_file(lowercase , lowercase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(lowercase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(lowercase , lowercase ) ) ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) self.assertTrue(os.path.isfile(lowercase ) ) # File is cached at the same place the second time. A__ = cached_file(lowercase , lowercase ) self.assertEqual(lowercase , lowercase ) # Using a specific revision to test the full commit hash. A__ = cached_file(lowercase , lowercase , revision="9b8c223" ) self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): A__ = cached_file("tiny-random-bert" , lowercase ) with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): A__ = cached_file(lowercase , lowercase , revision="aaaa" ) with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertTrue(os.path.isfile(os.path.join(lowercase , ".no_exist" , lowercase , "conf" ) ) ) A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = cached_file(lowercase , "conf" , local_files_only=lowercase , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = mock.Mock() A__ = 500 A__ = {} A__ = HTTPError A__ = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=lowercase ) as mock_head: A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_connection_errors=lowercase ) self.assertIsNone(lowercase ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) def UpperCamelCase ( self ) -> str: '''simple docstring''' self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): get_file_from_repo("bert-base-case" , lowercase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): get_file_from_repo("bert-base-cased" , lowercase , revision="ahaha" ) A__ = get_file_from_repo("bert-base-cased" , lowercase ) # The name is the cached name which is not very easy to test, so instead we load the content. A__ = json.loads(open(lowercase , "r" ).read() ) self.assertEqual(config["hidden_size"] , 768 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A__ = Path(lowercase ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(lowercase , "a.txt" ) , str(lowercase ) ) self.assertIsNone(get_file_from_repo(lowercase , "b.txt" ) )
68
1
from jiwer import compute_measures import datasets lowerCAmelCase__ = """\ @inproceedings{inproceedings, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } """ lowerCAmelCase__ = """\ Word error rate (WER) is a common metric of the performance of an automatic speech recognition system. The general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate. Word error rate can then be computed as: WER = (S + D + I) / N = (S + D + I) / (S + D + C) where S is the number of substitutions, D is the number of deletions, I is the number of insertions, C is the number of correct words, N is the number of words in the reference (N=S+D+C). This value indicates the average number of errors per reference word. The lower the value, the better the performance of the ASR system with a WER of 0 being a perfect score. """ lowerCAmelCase__ = """ Compute WER score of transcribed segments against references. Args: references: List of references for each speech input. predictions: List of transcriptions to score. concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively. Returns: (float): the word error rate Examples: >>> predictions = [\"this is the prediction\", \"there is an other sample\"] >>> references = [\"this is the reference\", \"there is another one\"] >>> wer = datasets.load_metric(\"wer\") >>> wer_score = wer.compute(predictions=predictions, references=references) >>> print(wer_score) 0.5 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> str: '''simple docstring''' 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/jitsi/jiwer/"] , reference_urls=[ "https://en.wikipedia.org/wiki/Word_error_rate", ] , ) def UpperCamelCase ( self , lowercase=None , lowercase=None , lowercase=False ) -> Tuple: '''simple docstring''' if concatenate_texts: return compute_measures(lowercase , lowercase )["wer"] else: A__ = 0 A__ = 0 for prediction, reference in zip(lowercase , lowercase ): A__ = compute_measures(lowercase , lowercase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
68
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = AutoencoderKL __lowerCamelCase = 'sample' __lowerCamelCase = 1e-2 @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = 4 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase ) return {"sample": image} @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } A__ = self.dummy_input return init_dict, inputs_dict def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ , A__ = self.prepare_init_args_and_inputs_for_common() A__ = self.model_class(**lowercase ) model.to(lowercase ) assert not model.is_gradient_checkpointing and model.training A__ = model(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() A__ = torch.randn_like(lowercase ) A__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing A__ = self.model_class(**lowercase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowercase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training A__ = model_a(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() A__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) A__ = dict(model.named_parameters() ) A__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ , A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowercase ) self.assertIsNotNone(lowercase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase ) A__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) A__ = model.to(lowercase ) model.eval() if torch_device == "mps": A__ = torch.manual_seed(0 ) else: A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) A__ = image.to(lowercase ) with torch.no_grad(): A__ = model(lowercase , sample_posterior=lowercase , generator=lowercase ).sample A__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": A__ = torch.tensor( [ -4.00_78e-01, -3.83_23e-04, -1.26_81e-01, -1.14_62e-01, 2.00_95e-01, 1.08_93e-01, -8.82_47e-02, -3.03_61e-01, -9.86_44e-03, ] ) elif torch_device == "cpu": A__ = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: A__ = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowercase , lowercase , rtol=1e-2 ) ) @slow class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' return F'gaussian_noise_s={seed}_shape={"_".join([str(lowercase ) for s in shape] )}.npy' def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self , lowercase=0 , lowercase=(4, 3, 512, 512) , lowercase=False ) -> Optional[int]: '''simple docstring''' A__ = torch.floataa if fpaa else torch.floataa A__ = torch.from_numpy(load_hf_numpy(self.get_file_format(lowercase , lowercase ) ) ).to(lowercase ).to(lowercase ) return image def UpperCamelCase ( self , lowercase="CompVis/stable-diffusion-v1-4" , lowercase=False ) -> Any: '''simple docstring''' A__ = "fp16" if fpaa else None A__ = torch.floataa if fpaa else torch.floataa A__ = AutoencoderKL.from_pretrained( lowercase , subfolder="vae" , torch_dtype=lowercase , revision=lowercase , ) model.to(lowercase ).eval() return model def UpperCamelCase ( self , lowercase=0 ) -> List[str]: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(lowercase ) return torch.Generator(device=lowercase ).manual_seed(lowercase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , fpaa=lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) with torch.no_grad(): A__ = model(lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Tuple: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model.encode(lowercase ).latent_dist A__ = dist.sample(generator=lowercase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] A__ = sample[0, -1, -3:, -3:].flatten().cpu() A__ = torch.tensor(lowercase ) A__ = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(lowercase , lowercase , atol=lowercase )
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: str = " " ) -> list: '''simple docstring''' A__ = [] A__ = 0 for index, char in enumerate(SCREAMING_SNAKE_CASE_ ): if char == separator: split_words.append(string[last_index:index] ) A__ = index + 1 elif index + 1 == len(SCREAMING_SNAKE_CASE_ ): split_words.append(string[last_index : index + 1] ) return split_words if __name__ == "__main__": from doctest import testmod testmod()
68
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCAmelCase__ = logging.getLogger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = label_idx def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: A__ = [] A__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 A__ = [] A__ = [] else: A__ = line.split(" " ) words.append(splits[0] ) if len(lowercase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(lowercase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: A__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(lowercase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a__ ( snake_case ): """simple docstring""" def __init__( self ) -> Union[str, Any]: '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a__ ( snake_case ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: for sentence in parse_incr(lowercase ): A__ = [] A__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(lowercase ) == len(lowercase ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = 0 for sentence in parse_incr(lowercase ): A__ = preds_list[example_id] A__ = "" for token in sentence: out += F'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(lowercase ) example_id += 1 def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
68
1
import re import string import numpy as np import datasets lowerCAmelCase__ = """ Returns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list. """ lowerCAmelCase__ = """ Args: predictions: List of predicted texts. references: List of reference texts. regexes_to_ignore: List, defaults to None. Regex expressions of characters to ignore when calculating the exact matches. Note: these regexes are removed from the input data before the changes based on the options below (e.g. ignore_case, ignore_punctuation, ignore_numbers) are applied. ignore_case: Boolean, defaults to False. If true, turns everything to lowercase so that capitalization differences are ignored. ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before comparing predictions and references. Returns: exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive. Examples: >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results[\"exact_match\"], 1)) 25.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True) >>> print(round(results[\"exact_match\"], 1)) 50.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True) >>> print(round(results[\"exact_match\"], 1)) 75.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"] >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"] >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True) >>> print(round(results[\"exact_match\"], 1)) 100.0 >>> exact_match = datasets.load_metric(\"exact_match\") >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"] >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"] >>> results = exact_match.compute(references=refs, predictions=preds) >>> print(round(results[\"exact_match\"], 1)) 33.3 """ lowerCAmelCase__ = """ """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' 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" ), } ) , reference_urls=[] , ) def UpperCamelCase ( self , lowercase , lowercase , lowercase=None , lowercase=False , lowercase=False , lowercase=False , ) -> List[str]: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: A__ = np.array([re.sub(lowercase , "" , lowercase ) for x in predictions] ) A__ = np.array([re.sub(lowercase , "" , lowercase ) for x in references] ) else: A__ = np.asarray(lowercase ) A__ = np.asarray(lowercase ) if ignore_case: A__ = np.char.lower(lowercase ) A__ = np.char.lower(lowercase ) if ignore_punctuation: A__ = string.punctuation.maketrans("" , "" , string.punctuation ) A__ = np.char.translate(lowercase , table=lowercase ) A__ = np.char.translate(lowercase , table=lowercase ) if ignore_numbers: A__ = string.digits.maketrans("" , "" , string.digits ) A__ = np.char.translate(lowercase , table=lowercase ) A__ = np.char.translate(lowercase , table=lowercase ) A__ = predictions == references return {"exact_match": np.mean(lowercase ) * 100}
68
import random class a__ : """simple docstring""" @staticmethod def UpperCamelCase ( lowercase ) -> tuple[list[int], list[int]]: '''simple docstring''' A__ = [ord(lowercase ) for i in text] A__ = [] A__ = [] for i in plain: A__ = random.randint(1 , 300 ) A__ = (i + k) * k cipher.append(lowercase ) key.append(lowercase ) return cipher, key @staticmethod def UpperCamelCase ( lowercase , lowercase ) -> str: '''simple docstring''' A__ = [] for i in range(len(lowercase ) ): A__ = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowercase ) ) return "".join(lowercase ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
68
1
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ = logging.getLogger(__name__) def lowerCAmelCase__ ( ) -> int: '''simple docstring''' A__ = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=SCREAMING_SNAKE_CASE_ , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=SCREAMING_SNAKE_CASE_ , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=SCREAMING_SNAKE_CASE_ , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=SCREAMING_SNAKE_CASE_ , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=SCREAMING_SNAKE_CASE_ , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=SCREAMING_SNAKE_CASE_ , type=SCREAMING_SNAKE_CASE_ , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=SCREAMING_SNAKE_CASE_ , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=SCREAMING_SNAKE_CASE_ , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) A__ = parser.parse_args() return args def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> Optional[Any]: '''simple docstring''' def fn(SCREAMING_SNAKE_CASE_: str ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> List[str]: '''simple docstring''' A__ = [] for i in range(len(tokenized_data["input_ids"] ) ): A__ = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } A__ = tf.train.Features(feature=SCREAMING_SNAKE_CASE_ ) A__ = tf.train.Example(features=SCREAMING_SNAKE_CASE_ ) A__ = example.SerializeToString() records.append(SCREAMING_SNAKE_CASE_ ) return records def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> Union[str, Any]: '''simple docstring''' A__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: A__ = min(len(SCREAMING_SNAKE_CASE_ ) , args.limit ) A__ = dataset.select(range(SCREAMING_SNAKE_CASE_ ) ) print(F'Limiting the dataset to {args.limit} entries.' ) A__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) A__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(SCREAMING_SNAKE_CASE_ ): os.makedirs(SCREAMING_SNAKE_CASE_ ) else: A__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. A__ = tokenize_function(SCREAMING_SNAKE_CASE_ ) A__ = dataset.map(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(SCREAMING_SNAKE_CASE_: int ): # Concatenate all texts. A__ = {k: sum(examples[k] , [] ) for k in examples.keys()} A__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 A__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. A__ = { k: [t[i : i + args.max_length] for i in range(0 , SCREAMING_SNAKE_CASE_ , args.max_length )] for k, t in concatenated_examples.items() } return result A__ = dataset_tokenized.map(SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , batch_size=1_0_0_0 , num_proc=4 ) A__ = 0 A__ = 0 for shard in range(0 , len(SCREAMING_SNAKE_CASE_ ) , args.shard_size ): A__ = grouped_dataset[shard : shard + args.shard_size] A__ = len(dataset_snapshot["input_ids"] ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , F'dataset-{shard_count}-{records_containing}.tfrecord' ) A__ = get_serialized_examples(SCREAMING_SNAKE_CASE_ ) with tf.io.TFRecordWriter(SCREAMING_SNAKE_CASE_ ) as out_file: for i in range(len(SCREAMING_SNAKE_CASE_ ) ): A__ = serialized_examples[i] out_file.write(SCREAMING_SNAKE_CASE_ ) print("Wrote file {} containing {} records".format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": lowerCAmelCase__ = parse_args() main(args)
68
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ = 2 while i * i <= n: A__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
68
1
from typing import List, Optional, Union import torch 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, ) lowerCAmelCase__ = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase__ = """ Examples: ```py >>> import torch >>> import numpy as np >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline >>> from transformers import pipeline >>> from diffusers.utils import load_image >>> def make_hint(image, depth_estimator): ... image = depth_estimator(image)[\"depth\"] ... image = np.array(image) ... image = image[:, :, None] ... image = np.concatenate([image, image, image], axis=2) ... detected_map = torch.from_numpy(image).float() / 255.0 ... hint = detected_map.permute(2, 0, 1) ... return hint >>> depth_estimator = pipeline(\"depth-estimation\") >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16 ... ) >>> pipe_prior = pipe_prior.to(\"cuda\") >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained( ... \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16 ... ) >>> pipe = pipe.to(\"cuda\") >>> img = load_image( ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\" ... \"/kandinsky/cat.png\" ... ).resize((768, 768)) >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\") >>> prompt = \"A robot, 4k photo\" >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\" >>> generator = torch.Generator(device=\"cuda\").manual_seed(43) >>> image_emb, zero_image_emb = pipe_prior( ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator ... ).to_tuple() >>> images = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... hint=hint, ... num_inference_steps=50, ... generator=generator, ... height=768, ... width=768, ... ).images >>> images[0].save(\"robot_cat.png\") ``` """ def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Dict=8 ) -> List[str]: '''simple docstring''' A__ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 A__ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , ) -> Optional[int]: '''simple docstring''' super().__init__() self.register_modules( unet=lowercase , scheduler=lowercase , movq=lowercase , ) A__ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' if latents is None: A__ = randn_tensor(lowercase , generator=lowercase , device=lowercase , dtype=lowercase ) else: if latents.shape != shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}' ) A__ = latents.to(lowercase ) A__ = latents * scheduler.init_noise_sigma return latents def UpperCamelCase ( self , lowercase=0 ) -> Union[str, Any]: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) A__ = torch.device(F'cuda:{gpu_id}' ) A__ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowercase , lowercase ) def UpperCamelCase ( self , lowercase=0 ) -> Dict: '''simple docstring''' 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__ = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=lowercase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) A__ = None for cpu_offloaded_model in [self.unet, self.movq]: A__ , A__ = cpu_offload_with_hook(lowercase , lowercase , prev_module_hook=lowercase ) # We'll offload the last model manually. A__ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowercase , "_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(lowercase ) def __call__( self , lowercase , lowercase , lowercase , lowercase = 512 , lowercase = 512 , lowercase = 100 , lowercase = 4.0 , lowercase = 1 , lowercase = None , lowercase = None , lowercase = "pil" , lowercase = True , ) -> int: '''simple docstring''' A__ = self._execution_device A__ = guidance_scale > 1.0 if isinstance(lowercase , lowercase ): A__ = torch.cat(lowercase , dim=0 ) if isinstance(lowercase , lowercase ): A__ = torch.cat(lowercase , dim=0 ) if isinstance(lowercase , lowercase ): A__ = torch.cat(lowercase , dim=0 ) A__ = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: A__ = image_embeds.repeat_interleave(lowercase , dim=0 ) A__ = negative_image_embeds.repeat_interleave(lowercase , dim=0 ) A__ = hint.repeat_interleave(lowercase , dim=0 ) A__ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=lowercase ) A__ = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=lowercase ) self.scheduler.set_timesteps(lowercase , device=lowercase ) A__ = self.scheduler.timesteps A__ = self.movq.config.latent_channels A__ , A__ = downscale_height_and_width(lowercase , lowercase , self.movq_scale_factor ) # create initial latent A__ = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , lowercase , lowercase , lowercase , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowercase ) ): # expand the latents if we are doing classifier free guidance A__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A__ = {"image_embeds": image_embeds, "hint": hint} A__ = self.unet( sample=lowercase , timestep=lowercase , encoder_hidden_states=lowercase , added_cond_kwargs=lowercase , return_dict=lowercase , )[0] if do_classifier_free_guidance: A__ , A__ = noise_pred.split(latents.shape[1] , dim=1 ) A__ , A__ = noise_pred.chunk(2 ) A__ , A__ = variance_pred.chunk(2 ) A__ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) A__ = 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__ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 A__ = self.scheduler.step( lowercase , lowercase , lowercase , generator=lowercase , )[0] # post-processing A__ = self.movq.decode(lowercase , force_not_quantize=lowercase )["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__ = image * 0.5 + 0.5 A__ = image.clamp(0 , 1 ) A__ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": A__ = self.numpy_to_pil(lowercase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowercase )
68
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: lowerCAmelCase__ = json.load(f) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return FSMTTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = F'facebook/wmt19-{pair}' A__ = self.get_tokenizer(lowercase ) A__ = self.get_model(lowercase ) A__ = bleu_data[pair]["src"] A__ = bleu_data[pair]["tgt"] A__ = tokenizer(lowercase , return_tensors="pt" , truncation=lowercase , padding="longest" ).to(lowercase ) A__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) A__ = tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) A__ = calculate_bleu(lowercase , lowercase ) print(lowercase ) self.assertGreaterEqual(scores["bleu"] , lowercase )
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[int] ) -> list[int]: '''simple docstring''' A__ = len(SCREAMING_SNAKE_CASE_ ) for i in range(SCREAMING_SNAKE_CASE_ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE_ ): if numbers[j] < numbers[i]: A__ , A__ = numbers[j], numbers[i] return numbers if __name__ == "__main__": lowerCAmelCase__ = input("""Enter numbers separated by a comma:\n""").strip() lowerCAmelCase__ = [int(item) for item in user_input.split(""",""")] print(exchange_sort(unsorted))
68
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> list: '''simple docstring''' A__ = int(SCREAMING_SNAKE_CASE_ ) if n_element < 1: A__ = ValueError("a should be a positive number" ) raise my_error A__ = [1] A__ , A__ , A__ = (0, 0, 0) A__ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowerCAmelCase__ = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") lowerCAmelCase__ = hamming(int(n)) print("""-----------------------------------------------------""") print(f"""The list with nth numbers is: {hamming_numbers}""") print("""-----------------------------------------------------""")
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int = 6_0_0_8_5_1_4_7_5_1_4_3 ) -> int: '''simple docstring''' try: A__ = int(SCREAMING_SNAKE_CASE_ ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) A__ = 2 A__ = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 A__ = i while n % i == 0: A__ = n // i i += 1 return int(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": print(f"""{solution() = }""")
68
import copy import random from transformers import CLIPTokenizer class a__ ( snake_case ): """simple docstring""" def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' super().__init__(*lowercase , **lowercase ) A__ = {} def UpperCamelCase ( self , lowercase , *lowercase , **lowercase ) -> str: '''simple docstring''' A__ = super().add_tokens(lowercase , *lowercase , **lowercase ) if num_added_tokens == 0: raise ValueError( F'The tokenizer already contains the token {placeholder_token}. Please pass a different' " `placeholder_token` that is not already in the tokenizer." ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=1 , **lowercase ) -> Any: '''simple docstring''' A__ = [] if num_vec_per_token == 1: self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) else: A__ = [] for i in range(lowercase ): A__ = placeholder_token + F'_{i}' self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'The tokenizer already has placeholder token {token} that can get confused with' F' {placeholder_token}keep placeholder tokens independent' ) A__ = output def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=1.0 ) -> List[Any]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = [] for i in range(len(lowercase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=lowercase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: A__ = self.token_map[placeholder_token] A__ = tokens[: 1 + int(len(lowercase ) * prop_tokens_to_load )] if vector_shuffle: A__ = copy.copy(lowercase ) random.shuffle(lowercase ) A__ = text.replace(lowercase , " ".join(lowercase ) ) return text def __call__( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> str: '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> List[str]: '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , )
68
1
class a__ : """simple docstring""" def __init__( self ) -> None: '''simple docstring''' A__ = {} # Mapping from char to TrieNode A__ = False def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' for word in words: self.insert(lowercase ) def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' A__ = self for char in word: if char not in curr.nodes: A__ = TrieNode() A__ = curr.nodes[char] A__ = True def UpperCamelCase ( self , lowercase ) -> bool: '''simple docstring''' A__ = self for char in word: if char not in curr.nodes: return False A__ = curr.nodes[char] return curr.is_leaf def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' def _delete(lowercase , lowercase , lowercase ) -> bool: if index == len(lowercase ): # If word does not exist if not curr.is_leaf: return False A__ = False return len(curr.nodes ) == 0 A__ = word[index] A__ = curr.nodes.get(lowercase ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted A__ = _delete(lowercase , lowercase , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , lowercase , 0 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: TrieNode , SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' if node.is_leaf: print(SCREAMING_SNAKE_CASE_ , end=" " ) for key, value in node.nodes.items(): print_words(SCREAMING_SNAKE_CASE_ , word + key ) def lowerCAmelCase__ ( ) -> bool: '''simple docstring''' A__ = "banana bananas bandana band apple all beast".split() A__ = TrieNode() root.insert_many(SCREAMING_SNAKE_CASE_ ) # print_words(root, "") assert all(root.find(SCREAMING_SNAKE_CASE_ ) for word in words ) assert root.find("banana" ) assert not root.find("bandanas" ) assert not root.find("apps" ) assert root.find("apple" ) assert root.find("all" ) root.delete("all" ) assert not root.find("all" ) root.delete("banana" ) assert not root.find("banana" ) assert root.find("bananas" ) return True def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: bool ) -> None: '''simple docstring''' print(str(SCREAMING_SNAKE_CASE_ ) , "works!" if passes else "doesn't work :(" ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' assert test_trie() def lowerCAmelCase__ ( ) -> None: '''simple docstring''' print_results("Testing trie functionality" , test_trie() ) if __name__ == "__main__": main()
68
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Tuple: '''simple docstring''' if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A__ = [[w, v]] if not self.graph.get(lowercase ): A__ = [] def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Any: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self , lowercase=-2 ) -> str: '''simple docstring''' A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s A__ = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> int: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin class a__ : """simple docstring""" def __init__( self ) -> int: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A__ = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A__ = [[w, u]] def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> str: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Dict: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> List[Any]: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin
68
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """facebook/s2t-wav2vec2-large-en-de""": ( """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'speech_to_text_2' __lowerCamelCase = ['past_key_values'] __lowerCamelCase = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , lowercase=10000 , lowercase=6 , lowercase=2048 , lowercase=4 , lowercase=0.0 , lowercase=True , lowercase="relu" , lowercase=256 , lowercase=0.1 , lowercase=0.0 , lowercase=0.0 , lowercase=0.02 , lowercase=2 , lowercase=True , lowercase=1 , lowercase=0 , lowercase=2 , lowercase=1024 , **lowercase , ) -> Optional[int]: '''simple docstring''' A__ = vocab_size A__ = d_model A__ = decoder_ffn_dim A__ = decoder_layers A__ = decoder_attention_heads A__ = dropout A__ = attention_dropout A__ = activation_dropout A__ = activation_function A__ = init_std A__ = decoder_layerdrop A__ = use_cache A__ = decoder_layers A__ = scale_embedding # scale factor will be sqrt(d_model) if True A__ = max_target_positions super().__init__( pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , decoder_start_token_id=lowercase , **lowercase , )
68
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
1
lowerCAmelCase__ = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ lowerCAmelCase__ = [{"""type""": """code""", """content""": INSTALL_CONTENT}] lowerCAmelCase__ = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
68
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
1
import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=True , lowercase=False , lowercase=True , lowercase=99 , lowercase=32 , lowercase=5 , lowercase=4 , lowercase=37 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=512 , lowercase=16 , lowercase=2 , lowercase=0.02 , lowercase=3 , lowercase=4 , lowercase=None , ) -> Optional[Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_input_mask A__ = use_token_type_ids A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_act A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = type_vocab_size A__ = type_sequence_label_size A__ = initializer_range A__ = num_labels A__ = num_choices A__ = scope def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = None if self.use_input_mask: A__ = random_attention_mask([self.batch_size, self.seq_length] ) A__ = None A__ = None A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) A__ = ids_tensor([self.batch_size] , self.num_choices ) A__ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = DistilBertModel(config=lowercase ) model.to(lowercase ) model.eval() A__ = model(lowercase , lowercase ) A__ = model(lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> str: '''simple docstring''' A__ = DistilBertForMaskedLM(config=lowercase ) model.to(lowercase ) model.eval() A__ = model(lowercase , attention_mask=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = DistilBertForQuestionAnswering(config=lowercase ) model.to(lowercase ) model.eval() A__ = model( lowercase , attention_mask=lowercase , start_positions=lowercase , end_positions=lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> str: '''simple docstring''' A__ = self.num_labels A__ = DistilBertForSequenceClassification(lowercase ) model.to(lowercase ) model.eval() A__ = model(lowercase , attention_mask=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = self.num_labels A__ = DistilBertForTokenClassification(config=lowercase ) model.to(lowercase ) model.eval() A__ = model(lowercase , attention_mask=lowercase , labels=lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = self.num_choices A__ = DistilBertForMultipleChoice(config=lowercase ) model.to(lowercase ) model.eval() A__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() A__ = model( lowercase , attention_mask=lowercase , labels=lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.prepare_config_and_inputs() ((A__) , (A__) , (A__) , (A__) , (A__) , (A__)) = config_and_inputs A__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) __lowerCamelCase = ( { 'feature-extraction': DistilBertModel, 'fill-mask': DistilBertForMaskedLM, 'question-answering': DistilBertForQuestionAnswering, 'text-classification': DistilBertForSequenceClassification, 'token-classification': DistilBertForTokenClassification, 'zero-shot': DistilBertForSequenceClassification, } if is_torch_available() else {} ) __lowerCamelCase = True __lowerCamelCase = True __lowerCamelCase = True __lowerCamelCase = True def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = DistilBertModelTester(self ) A__ = ConfigTester(self , config_class=lowercase , dim=37 ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase ) @slow def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = DistilBertModel.from_pretrained(lowercase ) self.assertIsNotNone(lowercase ) @slow @require_torch_gpu def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return A__ = True A__ = model_class(config=lowercase ) A__ = self._prepare_for_class(lowercase , lowercase ) A__ = torch.jit.trace( lowercase , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(lowercase , os.path.join(lowercase , "traced_model.pt" ) ) A__ = torch.jit.load(os.path.join(lowercase , "traced_model.pt" ) , map_location=lowercase ) loaded(inputs_dict["input_ids"].to(lowercase ) , inputs_dict["attention_mask"].to(lowercase ) ) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = DistilBertModel.from_pretrained("distilbert-base-uncased" ) A__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) A__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): A__ = model(lowercase , attention_mask=lowercase )[0] A__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , lowercase ) A__ = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , lowercase , atol=1e-4 ) )
68
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
1
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Tuple ) -> List[Any]: '''simple docstring''' A__ = WavaVecaForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) A__ = downstream_dict["projector.weight"] A__ = downstream_dict["projector.bias"] A__ = downstream_dict["model.post_net.linear.weight"] A__ = downstream_dict["model.post_net.linear.bias"] return model def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: Optional[Any] ) -> str: '''simple docstring''' A__ = WavaVecaForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) A__ = downstream_dict["model.linear.weight"] A__ = downstream_dict["model.linear.bias"] return model def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Any ) -> Union[str, Any]: '''simple docstring''' A__ = WavaVecaForXVector.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) A__ = downstream_dict["connector.weight"] A__ = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): A__ = downstream_dict[ F'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] A__ = downstream_dict[F'model.framelevel_feature_extractor.module.{i}.kernel.bias'] A__ = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] A__ = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] A__ = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] A__ = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] A__ = downstream_dict["objective.W"] return model @torch.no_grad() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: List[str] ) -> Any: '''simple docstring''' A__ = torch.load(SCREAMING_SNAKE_CASE_ , map_location="cpu" ) A__ = checkpoint["Downstream"] A__ = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) A__ = WavaVecaFeatureExtractor.from_pretrained( SCREAMING_SNAKE_CASE_ , return_attention_mask=SCREAMING_SNAKE_CASE_ , do_normalize=SCREAMING_SNAKE_CASE_ ) A__ = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): A__ = convert_classification(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForAudioFrameClassification" ): A__ = convert_diarization(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) elif arch.endswith("ForXVector" ): A__ = convert_xvector(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else: raise NotImplementedError(F'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: A__ = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( """--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model.""" ) parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""") parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""") lowerCAmelCase__ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
68
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: A__ = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE_ ) A__ = num - key if num < 0: A__ = num + len(string.ascii_uppercase ) A__ = translated + string.ascii_uppercase[num] else: A__ = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = input("Encrypted message: " ) A__ = message.upper() decrypt(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tensorflow_text_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ = { """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""], """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ["""BertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """BertForMaskedLM""", """BertForMultipleChoice""", """BertForNextSentencePrediction""", """BertForPreTraining""", """BertForQuestionAnswering""", """BertForSequenceClassification""", """BertForTokenClassification""", """BertLayer""", """BertLMHeadModel""", """BertModel""", """BertPreTrainedModel""", """load_tf_weights_in_bert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFBertEmbeddings""", """TFBertForMaskedLM""", """TFBertForMultipleChoice""", """TFBertForNextSentencePrediction""", """TFBertForPreTraining""", """TFBertForQuestionAnswering""", """TFBertForSequenceClassification""", """TFBertForTokenClassification""", """TFBertLMHeadModel""", """TFBertMainLayer""", """TFBertModel""", """TFBertPreTrainedModel""", ] try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ["""TFBertTokenizer"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """FlaxBertForCausalLM""", """FlaxBertForMaskedLM""", """FlaxBertForMultipleChoice""", """FlaxBertForNextSentencePrediction""", """FlaxBertForPreTraining""", """FlaxBertForQuestionAnswering""", """FlaxBertForSequenceClassification""", """FlaxBertForTokenClassification""", """FlaxBertModel""", """FlaxBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_fast import BertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bert import ( BERT_PRETRAINED_MODEL_ARCHIVE_LIST, BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLayer, BertLMHeadModel, BertModel, BertPreTrainedModel, load_tf_weights_in_bert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_bert import ( TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFBertEmbeddings, TFBertForMaskedLM, TFBertForMultipleChoice, TFBertForNextSentencePrediction, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertForTokenClassification, TFBertLMHeadModel, TFBertMainLayer, TFBertModel, TFBertPreTrainedModel, ) try: if not is_tensorflow_text_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bert_tf import TFBertTokenizer try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_bert import ( FlaxBertForCausalLM, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, FlaxBertPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = SpeechTaTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(lowercase ) A__ = AddedToken("<mask>" , lstrip=lowercase , rstrip=lowercase ) A__ = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = "this is a test" A__ = "this is a test" return input_text, output_text def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=20 , lowercase=5 ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.get_input_output_texts(lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) return text, ids def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = "<pad>" A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(lowercase ) , 81 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] A__ = tokenizer.add_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size + len(lowercase ) ) A__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) A__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A__ = tokenizer.add_special_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size_a + len(lowercase ) ) A__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(lowercase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) A__ = tokenizer.convert_tokens_to_ids(lowercase ) # fmt: off self.assertListEqual(lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off A__ = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=lowercase , )
68
1
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def lowerCAmelCase__ ( ) -> tuple[list[int], int]: '''simple docstring''' A__ = [randint(-1_0_0_0 , 1_0_0_0 ) for i in range(1_0 )] A__ = randint(-5_0_0_0 , 5_0_0_0 ) return (arr, r) lowerCAmelCase__ = make_dataset() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: int ) -> tuple[int, ...]: '''simple docstring''' for triplet in permutations(SCREAMING_SNAKE_CASE_ , 3 ): if sum(SCREAMING_SNAKE_CASE_ ) == target: return tuple(sorted(SCREAMING_SNAKE_CASE_ ) ) return (0, 0, 0) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[int] , SCREAMING_SNAKE_CASE_: int ) -> tuple[int, int, int]: '''simple docstring''' arr.sort() A__ = len(SCREAMING_SNAKE_CASE_ ) for i in range(n - 1 ): A__ , A__ = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def lowerCAmelCase__ ( ) -> tuple[float, float]: '''simple docstring''' A__ = "\nfrom __main__ import dataset, triplet_sum1, triplet_sum2\n" A__ = "\ntriplet_sum1(*dataset)\n" A__ = "\ntriplet_sum2(*dataset)\n" A__ = repeat(setup=SCREAMING_SNAKE_CASE_ , stmt=SCREAMING_SNAKE_CASE_ , repeat=5 , number=1_0_0_0_0 ) A__ = repeat(setup=SCREAMING_SNAKE_CASE_ , stmt=SCREAMING_SNAKE_CASE_ , repeat=5 , number=1_0_0_0_0 ) return (min(SCREAMING_SNAKE_CASE_ ), min(SCREAMING_SNAKE_CASE_ )) if __name__ == "__main__": from doctest import testmod testmod() lowerCAmelCase__ = solution_times() print(f"""The time for naive implementation is {times[0]}.""") print(f"""The time for optimized implementation is {times[1]}.""")
68
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> List[str]: '''simple docstring''' A__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } A__ = F'{src_lang}-{tgt_lang}' A__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) # make sure we are under the root of the project lowerCAmelCase__ = Path(__file__).resolve().parent.parent.parent lowerCAmelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = model_name.split("""-""") lowerCAmelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list ) -> list: '''simple docstring''' if len(SCREAMING_SNAKE_CASE_ ) <= 1: return [tuple(SCREAMING_SNAKE_CASE_ )] A__ = [] def generate(SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: list ): A__ = [0] * n res.append(tuple(SCREAMING_SNAKE_CASE_ ) ) A__ = 0 while i < n: if c[i] < i: if i % 2 == 0: A__ , A__ = arr[i], arr[0] else: A__ , A__ = arr[i], arr[c[i]] res.append(tuple(SCREAMING_SNAKE_CASE_ ) ) c[i] += 1 A__ = 0 else: A__ = 0 i += 1 generate(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) return res if __name__ == "__main__": lowerCAmelCase__ = input("""Enter numbers separated by a comma:\n""").strip() lowerCAmelCase__ = [int(item) for item in user_input.split(""",""")] print(heaps(arr))
68
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = feature_size A__ = sampling_rate A__ = padding_value A__ = kwargs.pop("padding_side" , "right" ) A__ = kwargs.pop("return_attention_mask" , lowercase ) super().__init__(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = None , lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys() )}' ) A__ = processed_features[self.model_input_names[0]] A__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase ) == 0: if return_attention_mask: A__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A__ = required_input[0] if isinstance(lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase ): A__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase ): A__ = "tf" elif is_torch_tensor(lowercase ): A__ = "pt" elif isinstance(lowercase , (int, float, list, tuple, np.ndarray) ): A__ = "np" else: raise ValueError( F'type of {first_element} unknown: {type(lowercase )}. ' "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A__ = to_numpy(lowercase ) else: A__ = [to_numpy(lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy A__ = self._get_padding_strategies(padding=lowercase , max_length=lowercase ) A__ = processed_features[self.model_input_names[0]] A__ = len(lowercase ) if not all(len(lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) A__ = [] for i in range(lowercase ): A__ = {k: v[i] for k, v in processed_features.items()} # truncation A__ = self._truncate( lowercase , max_length=lowercase , pad_to_multiple_of=lowercase , truncation=lowercase , ) truncated_inputs.append(lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A__ = PaddingStrategy.MAX_LENGTH A__ = {} for i in range(lowercase ): # padding A__ = self._pad( truncated_inputs[i] , max_length=lowercase , padding_strategy=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: A__ = [] if value.dtype is np.dtype(np.floataa ): A__ = value.astype(np.floataa ) batch_outputs[key].append(lowercase ) return BatchFeature(lowercase , tensor_type=lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = PaddingStrategy.DO_NOT_PAD , lowercase = None , lowercase = None , ) -> dict: '''simple docstring''' A__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A__ = len(lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A__ = np.ones(len(lowercase ) , dtype=np.intaa ) if needs_to_be_padded: A__ = max_length - len(lowercase ) if self.padding_side == "right": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (0, difference) ) A__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (difference, 0) ) A__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , ) -> Union[str, Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) A__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = len(lowercase ) > max_length if needs_to_be_truncated: A__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A__ = processed_features["attention_mask"][:max_length] return processed_features def UpperCamelCase ( self , lowercase=False , lowercase=None ) -> Any: '''simple docstring''' if padding is not False: if padding is True: A__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase , lowercase ): A__ = PaddingStrategy(lowercase ) elif isinstance(lowercase , lowercase ): A__ = padding else: A__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
68
1
import numpy as np from transformers import Pipeline def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[Any] ) -> Union[str, Any]: '''simple docstring''' A__ = np.max(SCREAMING_SNAKE_CASE_ , axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) A__ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=SCREAMING_SNAKE_CASE_ ) class a__ ( snake_case ): """simple docstring""" def UpperCamelCase ( self , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = {} if "second_text" in kwargs: A__ = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCamelCase ( self , lowercase , lowercase=None ) -> List[Any]: '''simple docstring''' return self.tokenizer(lowercase , text_pair=lowercase , return_tensors=self.framework ) def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' return self.model(**lowercase ) def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = model_outputs.logits[0].numpy() A__ = softmax(lowercase ) A__ = np.argmax(lowercase ) A__ = self.model.config.idalabel[best_class] A__ = probabilities[best_class].item() A__ = logits.tolist() return {"label": label, "score": score, "logits": logits}
68
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
1
from __future__ import annotations from typing import Any def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[Any] ) -> None: '''simple docstring''' create_state_space_tree(SCREAMING_SNAKE_CASE_ , [] , 0 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[Any] , SCREAMING_SNAKE_CASE_: list[Any] , SCREAMING_SNAKE_CASE_: int ) -> None: '''simple docstring''' if index == len(SCREAMING_SNAKE_CASE_ ): print(SCREAMING_SNAKE_CASE_ ) return create_state_space_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": lowerCAmelCase__ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["""A""", """B""", """C"""]) generate_all_subsequences(seq)
68
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'gpt_neox_japanese' def __init__( self , lowercase=32000 , lowercase=2560 , lowercase=32 , lowercase=32 , lowercase=4 , lowercase="gelu" , lowercase=1.00 , lowercase=10000 , lowercase=2048 , lowercase=0.02 , lowercase=1e-5 , lowercase=True , lowercase=31996 , lowercase=31999 , lowercase=0.1 , lowercase=0.0 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_multiple_size A__ = hidden_act A__ = rotary_pct A__ = rotary_emb_base A__ = initializer_range A__ = layer_norm_eps A__ = use_cache A__ = attention_dropout A__ = hidden_dropout
68
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowerCAmelCase__ = 2_5_0_0_0_4 lowerCAmelCase__ = 2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = MBartaaTokenizer __lowerCamelCase = MBartaaTokenizerFast __lowerCamelCase = True __lowerCamelCase = True def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = MBartaaTokenizer(lowercase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=lowercase ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = "<s>" A__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(lowercase ) , 1054 ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1054 ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = MBartaaTokenizer(lowercase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=lowercase ) A__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowercase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [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__ = tokenizer.convert_tokens_to_ids(lowercase ) self.assertListEqual( lowercase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [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>", "."] , ) @slow def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = {"input_ids": [[250004, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 5428, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 12399, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 122009, 115774, 23, 805, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [250004, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [250004, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowercase , model_name="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def UpperCamelCase ( self ) -> str: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A__ = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): A__ = self.rust_tokenizer_class.from_pretrained(lowercase , **lowercase ) A__ = self.tokenizer_class.from_pretrained(lowercase , **lowercase ) A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase ) A__ = tokenizer_p.save_pretrained(lowercase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) A__ = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(lowercase , lowercase ) # Checks everything loads correctly in the same way A__ = tokenizer_r.from_pretrained(lowercase ) A__ = tokenizer_p.from_pretrained(lowercase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase ) # Save tokenizer rust, legacy_format=True A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase , legacy_format=lowercase ) A__ = tokenizer_p.save_pretrained(lowercase ) # Checks it save with the same files self.assertSequenceEqual(lowercase , lowercase ) # Checks everything loads correctly in the same way A__ = tokenizer_r.from_pretrained(lowercase ) A__ = tokenizer_p.from_pretrained(lowercase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase ) ) shutil.rmtree(lowercase ) # Save tokenizer rust, legacy_format=False A__ = tempfile.mkdtemp() A__ = tokenizer_r.save_pretrained(lowercase , legacy_format=lowercase ) A__ = tokenizer_p.save_pretrained(lowercase ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A__ = tokenizer_r.from_pretrained(lowercase ) A__ = tokenizer_p.from_pretrained(lowercase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase , lowercase ) ) shutil.rmtree(lowercase ) @require_torch @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = 'facebook/mbart-large-50-one-to-many-mmt' __lowerCamelCase = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] __lowerCamelCase = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] __lowerCamelCase = [EN_CODE, 8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2] @classmethod def UpperCamelCase ( cls ) -> Tuple: '''simple docstring''' A__ = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) A__ = 1 return cls def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 250001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 250004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 250020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 250038 ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' self.assertIn(lowercase , self.tokenizer.all_special_ids ) A__ = [RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2] A__ = self.tokenizer.decode(lowercase , skip_special_tokens=lowercase ) A__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowercase ) self.assertEqual(lowercase , lowercase ) self.assertNotIn(self.tokenizer.eos_token , lowercase ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , lowercase ) A__ = 10 A__ = self.tokenizer(lowercase , max_length=lowercase , truncation=lowercase ).input_ids[0] self.assertEqual(ids[0] , lowercase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [250053, 250001] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = tempfile.mkdtemp() A__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase ) A__ = MBartaaTokenizer.from_pretrained(lowercase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowercase ) @require_torch def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowercase , return_tensors="pt" ) A__ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowercase , truncation=lowercase , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) A__ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowercase , lowercase ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) A__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowercase ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.tokenizer(self.src_text , padding=lowercase , truncation=lowercase , max_length=3 , return_tensors="pt" ) A__ = self.tokenizer( text_target=self.tgt_text , padding=lowercase , truncation=lowercase , max_length=10 , return_tensors="pt" ) A__ = targets["input_ids"] A__ = shift_tokens_right(lowercase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(lowercase ) , { # en_XX, A, test, EOS "input_ids": [[250004, 62, 3034, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 250001, } , )
68
import warnings from functools import wraps from typing import Callable def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Callable ) -> Callable: '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_: int , **SCREAMING_SNAKE_CASE_: Union[str, Any] ): warnings.warn( (F'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
68
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 convert_to_rgb, 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 if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = 1 / 255 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 384, "width": 384} A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = do_resize A__ = size A__ = resample A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ = image_std if image_std is not None else OPENAI_CLIP_STD A__ = do_convert_rgb def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase , default_to_square=lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) A__ = (size["height"], size["width"]) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = resample if resample is not None else self.resample A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = size if size is not None else self.size A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_rescale: A__ = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase ) return encoded_outputs
68
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
1
import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask lowerCAmelCase__ = logging.getLogger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'token-classification' def __init__( self , lowercase ) -> List[str]: '''simple docstring''' if type(lowercase ) == dict: A__ = Namespace(**lowercase ) A__ = import_module("tasks" ) try: A__ = getattr(lowercase , hparams.task_type ) A__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) A__ = self.token_classification_task.get_labels(hparams.labels ) A__ = CrossEntropyLoss().ignore_index super().__init__(lowercase , len(self.labels ) , self.mode ) def UpperCamelCase ( self , **lowercase ) -> Any: '''simple docstring''' return self.model(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' A__ = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": A__ = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids A__ = self(**lowercase ) A__ = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.hparams for mode in ["train", "dev", "test"]: A__ = self._feature_file(lowercase ) if os.path.exists(lowercase ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , lowercase ) A__ = torch.load(lowercase ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) A__ = self.token_classification_task.read_examples_from_file(args.data_dir , lowercase ) A__ = self.token_classification_task.convert_examples_to_features( lowercase , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["xlnet"] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["xlnet"] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=lowercase , pad_on_left=bool(self.config.model_type in ["xlnet"] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("Saving features into cached file %s" , lowercase ) torch.save(lowercase , lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = False ) -> DataLoader: '''simple docstring''' A__ = self._feature_file(lowercase ) logger.info("Loading features from cached file %s" , lowercase ) A__ = torch.load(lowercase ) A__ = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) A__ = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: A__ = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: A__ = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) A__ = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(lowercase , lowercase , lowercase , lowercase ) , batch_size=lowercase ) def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' """Compute validation""" "" A__ = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type != "distilbert": A__ = ( batch[2] if self.config.model_type in ["bert", "xlnet"] else None ) # XLM and RoBERTa don"t use token_type_ids A__ = self(**lowercase ) A__ , A__ = outputs[:2] A__ = logits.detach().cpu().numpy() A__ = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = torch.stack([x["val_loss"] for x in outputs] ).mean() A__ = np.concatenate([x["pred"] for x in outputs] , axis=0 ) A__ = np.argmax(lowercase , axis=2 ) A__ = np.concatenate([x["target"] for x in outputs] , axis=0 ) A__ = dict(enumerate(self.labels ) ) A__ = [[] for _ in range(out_label_ids.shape[0] )] A__ = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) A__ = { "val_loss": val_loss_mean, "accuracy_score": accuracy_score(lowercase , lowercase ), "precision": precision_score(lowercase , lowercase ), "recall": recall_score(lowercase , lowercase ), "f1": fa_score(lowercase , lowercase ), } A__ = dict(results.items() ) A__ = results return ret, preds_list, out_label_list def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' A__ , A__ , A__ = self._eval_end(lowercase ) A__ = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def UpperCamelCase ( self , lowercase ) -> str: '''simple docstring''' A__ , A__ , A__ = self._eval_end(lowercase ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 A__ = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def UpperCamelCase ( lowercase , lowercase ) -> Optional[int]: '''simple docstring''' BaseTransformer.add_model_specific_args(lowercase , lowercase ) parser.add_argument( "--task_type" , default="NER" , type=lowercase , help="Task type to fine tune in training (e.g. NER, POS, etc)" ) parser.add_argument( "--max_seq_length" , default=128 , type=lowercase , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--labels" , default="" , type=lowercase , help="Path to a file containing all labels. If not specified, CoNLL-2003 labels are used." , ) parser.add_argument( "--gpus" , default=0 , type=lowercase , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) lowerCAmelCase__ = NERTransformer.add_model_specific_args(parser, os.getcwd()) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = NERTransformer(args) lowerCAmelCase__ = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 lowerCAmelCase__ = sorted(glob.glob(os.path.join(args.output_dir, """checkpoint-epoch=*.ckpt"""), recursive=True)) lowerCAmelCase__ = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
68
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class a__ : """simple docstring""" __lowerCamelCase = BlenderbotSmallConfig __lowerCamelCase = {} __lowerCamelCase = 'gelu' def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=False , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase=0.1 , lowercase=0.1 , lowercase=20 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) A__ = prepare_blenderbot_small_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = TFBlenderbotSmallModel(config=lowercase ).get_decoder() A__ = inputs_dict["input_ids"] A__ = input_ids[:1, :] A__ = inputs_dict["attention_mask"][:1, :] A__ = inputs_dict["head_mask"] A__ = 1 # first forward pass A__ = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(lowercase , attention_mask=lowercase )[0] A__ = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1e-3 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Optional[Any]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Dict=None , SCREAMING_SNAKE_CASE_: List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: A__ = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_tokenizers @require_tf class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __lowerCamelCase = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.tokenizer(self.src_text , return_tensors="tf" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
68
1
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class a__ ( unittest.TestCase ): """simple docstring""" def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=18 , lowercase=30 , lowercase=400 , lowercase=True , lowercase=None , lowercase=True , ) -> List[str]: '''simple docstring''' A__ = size if size is not None else {"height": 18, "width": 18} A__ = parent A__ = batch_size A__ = num_channels A__ = image_size A__ = min_resolution A__ = max_resolution A__ = do_resize A__ = size A__ = apply_ocr def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = LayoutLMvaImageProcessingTester(self ) @property def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase , "do_resize" ) ) self.assertTrue(hasattr(lowercase , "size" ) ) self.assertTrue(hasattr(lowercase , "apply_ocr" ) ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) A__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , Image.Image ) # Test not batched input A__ = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , lowercase ) self.assertIsInstance(encoding.boxes , lowercase ) # Test batched A__ = image_processing(lowercase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , numpify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , np.ndarray ) # Test not batched input A__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched A__ = image_processing(lowercase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , torchify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , torch.Tensor ) # Test not batched input A__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched A__ = image_processing(lowercase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = LayoutLMvaImageProcessor() from datasets import load_dataset A__ = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) A__ = Image.open(ds[0]["file"] ).convert("RGB" ) A__ = image_processing(lowercase , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 A__ = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 A__ = [[[141, 57, 214, 69], [228, 58, 252, 69], [141, 75, 216, 88], [230, 79, 280, 88], [142, 260, 218, 273], [230, 261, 255, 273], [143, 279, 218, 290], [231, 282, 290, 291], [143, 342, 218, 354], [231, 345, 289, 355], [202, 362, 227, 373], [143, 379, 220, 392], [231, 382, 291, 394], [144, 714, 220, 726], [231, 715, 256, 726], [144, 732, 220, 745], [232, 736, 291, 747], [144, 769, 218, 782], [231, 770, 256, 782], [141, 788, 202, 801], [215, 791, 274, 804], [143, 826, 204, 838], [215, 826, 240, 838], [142, 844, 202, 857], [215, 847, 274, 859], [334, 57, 427, 69], [440, 57, 522, 69], [369, 75, 461, 88], [469, 75, 516, 88], [528, 76, 562, 88], [570, 76, 667, 88], [675, 75, 711, 87], [721, 79, 778, 88], [789, 75, 840, 88], [369, 97, 470, 107], [484, 94, 507, 106], [518, 94, 562, 107], [576, 94, 655, 110], [668, 94, 792, 109], [804, 95, 829, 107], [369, 113, 465, 125], [477, 116, 547, 125], [562, 113, 658, 125], [671, 116, 748, 125], [761, 113, 811, 125], [369, 131, 465, 143], [477, 133, 548, 143], [563, 130, 698, 145], [710, 130, 802, 146], [336, 171, 412, 183], [423, 171, 572, 183], [582, 170, 716, 184], [728, 171, 817, 187], [829, 171, 844, 186], [338, 197, 482, 212], [507, 196, 557, 209], [569, 196, 595, 208], [610, 196, 702, 209], [505, 214, 583, 226], [595, 214, 656, 227], [670, 215, 807, 227], [335, 259, 543, 274], [556, 259, 708, 272], [372, 279, 422, 291], [435, 279, 460, 291], [474, 279, 574, 292], [587, 278, 664, 291], [676, 278, 738, 291], [751, 279, 834, 291], [372, 298, 434, 310], [335, 341, 483, 354], [497, 341, 655, 354], [667, 341, 728, 354], [740, 341, 825, 354], [335, 360, 430, 372], [442, 360, 534, 372], [545, 359, 687, 372], [697, 360, 754, 372], [765, 360, 823, 373], [334, 378, 428, 391], [440, 378, 577, 394], [590, 378, 705, 391], [720, 378, 801, 391], [334, 397, 400, 409], [370, 416, 529, 429], [544, 416, 576, 432], [587, 416, 665, 428], [677, 416, 814, 429], [372, 435, 452, 450], [465, 434, 495, 447], [511, 434, 600, 447], [611, 436, 637, 447], [649, 436, 694, 451], [705, 438, 824, 447], [369, 453, 452, 466], [464, 454, 509, 466], [522, 453, 611, 469], [625, 453, 792, 469], [370, 472, 556, 488], [570, 472, 684, 487], [697, 472, 718, 485], [732, 472, 835, 488], [369, 490, 411, 503], [425, 490, 484, 503], [496, 490, 635, 506], [645, 490, 707, 503], [718, 491, 761, 503], [771, 490, 840, 503], [336, 510, 374, 521], [388, 510, 447, 522], [460, 510, 489, 521], [503, 510, 580, 522], [592, 509, 736, 525], [745, 509, 770, 522], [781, 509, 840, 522], [338, 528, 434, 541], [448, 528, 596, 541], [609, 527, 687, 540], [700, 528, 792, 541], [336, 546, 397, 559], [407, 546, 431, 559], [443, 546, 525, 560], [537, 546, 680, 562], [688, 546, 714, 559], [722, 546, 837, 562], [336, 565, 449, 581], [461, 565, 485, 577], [497, 565, 665, 581], [681, 565, 718, 577], [732, 565, 837, 580], [337, 584, 438, 597], [452, 583, 521, 596], [535, 584, 677, 599], [690, 583, 787, 596], [801, 583, 825, 596], [338, 602, 478, 615], [492, 602, 530, 614], [543, 602, 638, 615], [650, 602, 676, 614], [688, 602, 788, 615], [802, 602, 843, 614], [337, 621, 502, 633], [516, 621, 615, 637], [629, 621, 774, 636], [789, 621, 827, 633], [337, 639, 418, 652], [432, 640, 571, 653], [587, 639, 731, 655], [743, 639, 769, 652], [780, 639, 841, 652], [338, 658, 440, 673], [455, 658, 491, 670], [508, 658, 602, 671], [616, 658, 638, 670], [654, 658, 835, 674], [337, 677, 429, 689], [337, 714, 482, 726], [495, 714, 548, 726], [561, 714, 683, 726], [338, 770, 461, 782], [474, 769, 554, 785], [489, 788, 562, 803], [576, 788, 643, 801], [656, 787, 751, 804], [764, 788, 844, 801], [334, 825, 421, 838], [430, 824, 574, 838], [584, 824, 723, 841], [335, 844, 450, 857], [464, 843, 583, 860], [628, 862, 755, 875], [769, 861, 848, 878]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , lowercase ) self.assertListEqual(encoding.boxes , lowercase ) # with apply_OCR = False A__ = LayoutLMvaImageProcessor(apply_ocr=lowercase ) A__ = image_processing(lowercase , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
68
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 convert_to_rgb, 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 if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = 1 / 255 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 384, "width": 384} A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = do_resize A__ = size A__ = resample A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ = image_std if image_std is not None else OPENAI_CLIP_STD A__ = do_convert_rgb def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase , default_to_square=lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) A__ = (size["height"], size["width"]) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = resample if resample is not None else self.resample A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = size if size is not None else self.size A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_rescale: A__ = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase ) return encoded_outputs
68
1
import torch from torch import nn class a__ ( nn.Module ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , lowercase , lowercase=1 , lowercase=False ) -> Union[str, Any]: '''simple docstring''' super().__init__() A__ = n_token A__ = d_embed A__ = d_proj A__ = cutoffs + [n_token] A__ = [0] + self.cutoffs A__ = div_val A__ = self.cutoffs[0] A__ = len(self.cutoffs ) - 1 A__ = self.shortlist_size + self.n_clusters if self.n_clusters > 0: A__ = nn.Parameter(torch.zeros(self.n_clusters , self.d_embed ) ) A__ = nn.Parameter(torch.zeros(self.n_clusters ) ) A__ = nn.ModuleList() A__ = nn.ParameterList() if div_val == 1: for i in range(len(self.cutoffs ) ): if d_proj != d_embed: self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase , lowercase ) ) ) else: self.out_projs.append(lowercase ) self.out_layers.append(nn.Linear(lowercase , lowercase ) ) else: for i in range(len(self.cutoffs ) ): A__ , A__ = self.cutoff_ends[i], self.cutoff_ends[i + 1] A__ = d_embed // (div_val**i) self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase , lowercase ) ) ) self.out_layers.append(nn.Linear(lowercase , r_idx - l_idx ) ) A__ = keep_order def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase ) -> List[Any]: '''simple docstring''' if proj is None: A__ = nn.functional.linear(lowercase , lowercase , bias=lowercase ) else: # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1: A__ = nn.functional.linear(lowercase , proj.t().contiguous() ) A__ = nn.functional.linear(lowercase , lowercase , bias=lowercase ) # else: # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t())) # if bias is not None: # logit = logit + bias return logit def UpperCamelCase ( self , lowercase , lowercase=None , lowercase=False ) -> Dict: '''simple docstring''' if labels is not None: # Shift so that tokens < n predict n A__ = hidden[..., :-1, :].contiguous() A__ = labels[..., 1:].contiguous() A__ = hidden.view(-1 , hidden.size(-1 ) ) A__ = labels.view(-1 ) if hidden.size(0 ) != labels.size(0 ): raise RuntimeError("Input and labels should have the same size in the batch dimension." ) else: A__ = hidden.view(-1 , hidden.size(-1 ) ) if self.n_clusters == 0: A__ = self._compute_logit(lowercase , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) if labels is not None: A__ = labels != -100 A__ = torch.zeros_like(lowercase , dtype=hidden.dtype , device=hidden.device ) A__ = ( -nn.functional.log_softmax(lowercase , dim=-1 )[mask].gather(1 , labels[mask].unsqueeze(1 ) ).squeeze(1 ) ) else: A__ = nn.functional.log_softmax(lowercase , dim=-1 ) else: # construct weights and biases A__ , A__ = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: A__ , A__ = self.cutoff_ends[i], self.cutoff_ends[i + 1] A__ = self.out_layers[0].weight[l_idx:r_idx] A__ = self.out_layers[0].bias[l_idx:r_idx] else: A__ = self.out_layers[i].weight A__ = self.out_layers[i].bias if i == 0: A__ = torch.cat([weight_i, self.cluster_weight] , dim=0 ) A__ = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(lowercase ) biases.append(lowercase ) A__ , A__ , A__ = weights[0], biases[0], self.out_projs[0] A__ = self._compute_logit(lowercase , lowercase , lowercase , lowercase ) A__ = nn.functional.log_softmax(lowercase , dim=1 ) if labels is None: A__ = hidden.new_empty((head_logit.size(0 ), self.n_token) ) else: A__ = torch.zeros_like(lowercase , dtype=hidden.dtype , device=hidden.device ) A__ = 0 A__ = [0] + self.cutoffs for i in range(len(lowercase ) - 1 ): A__ , A__ = cutoff_values[i], cutoff_values[i + 1] if labels is not None: A__ = (labels >= l_idx) & (labels < r_idx) A__ = mask_i.nonzero().squeeze() if indices_i.numel() == 0: continue A__ = labels.index_select(0 , lowercase ) - l_idx A__ = head_logprob.index_select(0 , lowercase ) A__ = hidden.index_select(0 , lowercase ) else: A__ = hidden if i == 0: if labels is not None: A__ = head_logprob_i.gather(1 , target_i[:, None] ).squeeze(1 ) else: A__ = head_logprob[:, : self.cutoffs[0]] else: A__ , A__ , A__ = weights[i], biases[i], self.out_projs[i] A__ = self._compute_logit(lowercase , lowercase , lowercase , lowercase ) A__ = nn.functional.log_softmax(lowercase , dim=1 ) A__ = self.cutoffs[0] + i - 1 # No probability for the head cluster if labels is not None: A__ = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather( 1 , target_i[:, None] ).squeeze(1 ) else: A__ = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i A__ = logprob_i if labels is not None: if (hasattr(self , "keep_order" ) and self.keep_order) or keep_order: out.index_copy_(0 , lowercase , -logprob_i ) else: out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i ) offset += logprob_i.size(0 ) return out def UpperCamelCase ( self , lowercase ) -> Dict: '''simple docstring''' if self.n_clusters == 0: A__ = self._compute_logit(lowercase , self.out_layers[0].weight , self.out_layers[0].bias , self.out_projs[0] ) return nn.functional.log_softmax(lowercase , dim=-1 ) else: # construct weights and biases A__ , A__ = [], [] for i in range(len(self.cutoffs ) ): if self.div_val == 1: A__ , A__ = self.cutoff_ends[i], self.cutoff_ends[i + 1] A__ = self.out_layers[0].weight[l_idx:r_idx] A__ = self.out_layers[0].bias[l_idx:r_idx] else: A__ = self.out_layers[i].weight A__ = self.out_layers[i].bias if i == 0: A__ = torch.cat([weight_i, self.cluster_weight] , dim=0 ) A__ = torch.cat([bias_i, self.cluster_bias] , dim=0 ) weights.append(lowercase ) biases.append(lowercase ) A__ , A__ , A__ = weights[0], biases[0], self.out_projs[0] A__ = self._compute_logit(lowercase , lowercase , lowercase , lowercase ) A__ = hidden.new_empty((head_logit.size(0 ), self.n_token) ) A__ = nn.functional.log_softmax(lowercase , dim=1 ) A__ = [0] + self.cutoffs for i in range(len(lowercase ) - 1 ): A__ , A__ = cutoff_values[i], cutoff_values[i + 1] if i == 0: A__ = head_logprob[:, : self.cutoffs[0]] else: A__ , A__ , A__ = weights[i], biases[i], self.out_projs[i] A__ = self._compute_logit(lowercase , lowercase , lowercase , lowercase ) A__ = nn.functional.log_softmax(lowercase , dim=1 ) A__ = head_logprob[:, -i] + tail_logprob_i A__ = logprob_i return out
68
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = """hf-internal-testing/tiny-random-bert""" lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""") lowerCAmelCase__ = """9b8c223d42b2188cb49d29af482996f9d0f3e5a6""" class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = cached_file(lowercase , lowercase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(lowercase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(lowercase , lowercase ) ) ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) self.assertTrue(os.path.isfile(lowercase ) ) # File is cached at the same place the second time. A__ = cached_file(lowercase , lowercase ) self.assertEqual(lowercase , lowercase ) # Using a specific revision to test the full commit hash. A__ = cached_file(lowercase , lowercase , revision="9b8c223" ) self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): A__ = cached_file("tiny-random-bert" , lowercase ) with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): A__ = cached_file(lowercase , lowercase , revision="aaaa" ) with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertTrue(os.path.isfile(os.path.join(lowercase , ".no_exist" , lowercase , "conf" ) ) ) A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = cached_file(lowercase , "conf" , local_files_only=lowercase , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = mock.Mock() A__ = 500 A__ = {} A__ = HTTPError A__ = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=lowercase ) as mock_head: A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_connection_errors=lowercase ) self.assertIsNone(lowercase ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) def UpperCamelCase ( self ) -> str: '''simple docstring''' self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): get_file_from_repo("bert-base-case" , lowercase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): get_file_from_repo("bert-base-cased" , lowercase , revision="ahaha" ) A__ = get_file_from_repo("bert-base-cased" , lowercase ) # The name is the cached name which is not very easy to test, so instead we load the content. A__ = json.loads(open(lowercase , "r" ).read() ) self.assertEqual(config["hidden_size"] , 768 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A__ = Path(lowercase ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(lowercase , "a.txt" ) , str(lowercase ) ) self.assertIsNone(get_file_from_repo(lowercase , "b.txt" ) )
68
1
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int = 1 , SCREAMING_SNAKE_CASE_: int = 1_0_0_0 ) -> int: '''simple docstring''' A__ = 1 A__ = 0 for divide_by_number in range(SCREAMING_SNAKE_CASE_ , digit + 1 ): A__ = [] A__ = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(SCREAMING_SNAKE_CASE_ ): A__ = len(SCREAMING_SNAKE_CASE_ ) A__ = divide_by_number else: has_been_divided.append(SCREAMING_SNAKE_CASE_ ) A__ = now_divide * 1_0 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
68
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = AutoencoderKL __lowerCamelCase = 'sample' __lowerCamelCase = 1e-2 @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = 4 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase ) return {"sample": image} @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } A__ = self.dummy_input return init_dict, inputs_dict def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ , A__ = self.prepare_init_args_and_inputs_for_common() A__ = self.model_class(**lowercase ) model.to(lowercase ) assert not model.is_gradient_checkpointing and model.training A__ = model(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() A__ = torch.randn_like(lowercase ) A__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing A__ = self.model_class(**lowercase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowercase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training A__ = model_a(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() A__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) A__ = dict(model.named_parameters() ) A__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ , A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowercase ) self.assertIsNotNone(lowercase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase ) A__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) A__ = model.to(lowercase ) model.eval() if torch_device == "mps": A__ = torch.manual_seed(0 ) else: A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) A__ = image.to(lowercase ) with torch.no_grad(): A__ = model(lowercase , sample_posterior=lowercase , generator=lowercase ).sample A__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": A__ = torch.tensor( [ -4.00_78e-01, -3.83_23e-04, -1.26_81e-01, -1.14_62e-01, 2.00_95e-01, 1.08_93e-01, -8.82_47e-02, -3.03_61e-01, -9.86_44e-03, ] ) elif torch_device == "cpu": A__ = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: A__ = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowercase , lowercase , rtol=1e-2 ) ) @slow class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' return F'gaussian_noise_s={seed}_shape={"_".join([str(lowercase ) for s in shape] )}.npy' def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self , lowercase=0 , lowercase=(4, 3, 512, 512) , lowercase=False ) -> Optional[int]: '''simple docstring''' A__ = torch.floataa if fpaa else torch.floataa A__ = torch.from_numpy(load_hf_numpy(self.get_file_format(lowercase , lowercase ) ) ).to(lowercase ).to(lowercase ) return image def UpperCamelCase ( self , lowercase="CompVis/stable-diffusion-v1-4" , lowercase=False ) -> Any: '''simple docstring''' A__ = "fp16" if fpaa else None A__ = torch.floataa if fpaa else torch.floataa A__ = AutoencoderKL.from_pretrained( lowercase , subfolder="vae" , torch_dtype=lowercase , revision=lowercase , ) model.to(lowercase ).eval() return model def UpperCamelCase ( self , lowercase=0 ) -> List[str]: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(lowercase ) return torch.Generator(device=lowercase ).manual_seed(lowercase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , fpaa=lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) with torch.no_grad(): A__ = model(lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Tuple: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model.encode(lowercase ).latent_dist A__ = dist.sample(generator=lowercase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] A__ = sample[0, -1, -3:, -3:].flatten().cpu() A__ = torch.tensor(lowercase ) A__ = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(lowercase , lowercase , atol=lowercase )
68
1
from __future__ import annotations import time import numpy as np lowerCAmelCase__ = [8, 5, 9, 7] lowerCAmelCase__ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] lowerCAmelCase__ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class a__ : """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , ) -> None: '''simple docstring''' A__ = claim_vector A__ = allocated_resources_table A__ = maximum_claim_table def UpperCamelCase ( self ) -> list[int]: '''simple docstring''' return [ sum(p_item[i] for p_item in self.__allocated_resources_table ) for i in range(len(self.__allocated_resources_table[0] ) ) ] def UpperCamelCase ( self ) -> list[int]: '''simple docstring''' return np.array(self.__claim_vector ) - np.array( self.__processes_resource_summation() ) def UpperCamelCase ( self ) -> list[list[int]]: '''simple docstring''' return [ list(np.array(self.__maximum_claim_table[i] ) - np.array(lowercase ) ) for i, allocated_resource in enumerate(self.__allocated_resources_table ) ] def UpperCamelCase ( self ) -> dict[int, list[int]]: '''simple docstring''' return {self.__need().index(lowercase ): i for i in self.__need()} def UpperCamelCase ( self , **lowercase ) -> None: '''simple docstring''' A__ = self.__need() A__ = self.__allocated_resources_table A__ = self.__available_resources() A__ = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n" ) while need_list: A__ = False for each_need in need_list: A__ = True for index, need in enumerate(lowercase ): if need > available_resources[index]: A__ = False break if execution: A__ = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: A__ = original_need_index print(F'Process {process_number + 1} is executing.' ) # remove the process run from stack need_list.remove(lowercase ) # update available/freed resources stack A__ = np.array(lowercase ) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(lowercase ) for x in available_resources] ) ) break if safe: print("The process is in a safe state.\n" ) else: print("System in unsafe state. Aborting...\n" ) break def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' print(" " * 9 + "Allocated Resource Table" ) for item in self.__allocated_resources_table: print( F'P{self.__allocated_resources_table.index(lowercase ) + 1}' + " ".join(F'{it:>8}' for it in item ) + "\n" ) print(" " * 9 + "System Resource Table" ) for item in self.__maximum_claim_table: print( F'P{self.__maximum_claim_table.index(lowercase ) + 1}' + " ".join(F'{it:>8}' for it in item ) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(lowercase ) for x in self.__claim_vector ) ) print( "Initial Available Resources: " + " ".join(str(lowercase ) for x in self.__available_resources() ) ) time.sleep(1 ) if __name__ == "__main__": import doctest doctest.testmod()
68
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCAmelCase__ = logging.getLogger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = label_idx def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: A__ = [] A__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 A__ = [] A__ = [] else: A__ = line.split(" " ) words.append(splits[0] ) if len(lowercase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(lowercase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: A__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(lowercase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a__ ( snake_case ): """simple docstring""" def __init__( self ) -> Union[str, Any]: '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a__ ( snake_case ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: for sentence in parse_incr(lowercase ): A__ = [] A__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(lowercase ) == len(lowercase ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = 0 for sentence in parse_incr(lowercase ): A__ = preds_list[example_id] A__ = "" for token in sentence: out += F'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(lowercase ) example_id += 1 def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
68
1
import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowerCAmelCase__ = False lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = """ybelkada/fonts""" def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ' "Pix2StructImageProcessor. Please upgrade torch." ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Dict , SCREAMING_SNAKE_CASE_: int ) -> Tuple: '''simple docstring''' requires_backends(SCREAMING_SNAKE_CASE_ , ["torch"] ) _check_torch_version() A__ = image_tensor.unsqueeze(0 ) A__ = torch.nn.functional.unfold(SCREAMING_SNAKE_CASE_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) A__ = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , -1 ) A__ = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: int = 3_6 , SCREAMING_SNAKE_CASE_: str = "black" , SCREAMING_SNAKE_CASE_: str = "white" , SCREAMING_SNAKE_CASE_: int = 5 , SCREAMING_SNAKE_CASE_: int = 5 , SCREAMING_SNAKE_CASE_: int = 5 , SCREAMING_SNAKE_CASE_: int = 5 , SCREAMING_SNAKE_CASE_: Optional[bytes] = None , SCREAMING_SNAKE_CASE_: Optional[str] = None , ) -> Image.Image: '''simple docstring''' requires_backends(SCREAMING_SNAKE_CASE_ , "vision" ) # Add new lines so that each line is no more than 80 characters. A__ = textwrap.TextWrapper(width=8_0 ) A__ = wrapper.wrap(text=SCREAMING_SNAKE_CASE_ ) A__ = "\n".join(SCREAMING_SNAKE_CASE_ ) if font_bytes is not None and font_path is None: A__ = io.BytesIO(SCREAMING_SNAKE_CASE_ ) elif font_path is not None: A__ = font_path else: A__ = hf_hub_download(SCREAMING_SNAKE_CASE_ , "Arial.TTF" ) A__ = ImageFont.truetype(SCREAMING_SNAKE_CASE_ , encoding="UTF-8" , size=SCREAMING_SNAKE_CASE_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. A__ = ImageDraw.Draw(Image.new("RGB" , (1, 1) , SCREAMING_SNAKE_CASE_ ) ) A__ , A__ , A__ , A__ = temp_draw.textbbox((0, 0) , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Create the actual image with a bit of padding around the text. A__ = text_width + left_padding + right_padding A__ = text_height + top_padding + bottom_padding A__ = Image.new("RGB" , (image_width, image_height) , SCREAMING_SNAKE_CASE_ ) A__ = ImageDraw.Draw(SCREAMING_SNAKE_CASE_ ) draw.text(xy=(left_padding, top_padding) , text=SCREAMING_SNAKE_CASE_ , fill=SCREAMING_SNAKE_CASE_ , font=SCREAMING_SNAKE_CASE_ ) return image def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: np.ndarray , SCREAMING_SNAKE_CASE_: str , **SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> Dict: '''simple docstring''' requires_backends(SCREAMING_SNAKE_CASE_ , "vision" ) # Convert to PIL image if necessary A__ = to_pil_image(SCREAMING_SNAKE_CASE_ ) A__ = render_text(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) A__ = max(header_image.width , image.width ) A__ = int(image.height * (new_width / image.width) ) A__ = int(header_image.height * (new_width / header_image.width) ) A__ = Image.new("RGB" , (new_width, new_height + new_header_height) , "white" ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary A__ = to_numpy_array(SCREAMING_SNAKE_CASE_ ) if infer_channel_dimension_format(SCREAMING_SNAKE_CASE_ ) == ChannelDimension.LAST: A__ = to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , ChannelDimension.LAST ) return new_image class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['flattened_patches'] def __init__( self , lowercase = True , lowercase = True , lowercase = None , lowercase = 2048 , lowercase = False , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = patch_size if patch_size is not None else {"height": 16, "width": 16} A__ = do_normalize A__ = do_convert_rgb A__ = max_patches A__ = is_vqa def UpperCamelCase ( self , lowercase , lowercase , lowercase , **lowercase ) -> np.ndarray: '''simple docstring''' requires_backends(self.extract_flattened_patches , "torch" ) _check_torch_version() # convert to torch A__ = to_channel_dimension_format(lowercase , ChannelDimension.FIRST ) A__ = torch.from_numpy(lowercase ) A__ , A__ = patch_size["height"], patch_size["width"] A__ , A__ = get_image_size(lowercase ) # maximize scale s.t. A__ = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) A__ = max(min(math.floor(scale * image_height / patch_height ) , lowercase ) , 1 ) A__ = max(min(math.floor(scale * image_width / patch_width ) , lowercase ) , 1 ) A__ = max(num_feasible_rows * patch_height , 1 ) A__ = max(num_feasible_cols * patch_width , 1 ) A__ = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode="bilinear" , align_corners=lowercase , antialias=lowercase , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] A__ = torch_extract_patches(lowercase , lowercase , lowercase ) A__ = patches.shape A__ = patches_shape[1] A__ = patches_shape[2] A__ = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] A__ = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] A__ = torch.arange(lowercase ).reshape([rows, 1] ).repeat(1 , lowercase ).reshape([rows * columns, 1] ) A__ = torch.arange(lowercase ).reshape([1, columns] ).repeat(lowercase , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] A__ = row_ids.to(torch.floataa ) A__ = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] A__ = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] A__ = torch.nn.functional.pad(lowercase , [0, 0, 0, max_patches - (rows * columns)] ).float() A__ = to_numpy_array(lowercase ) return result def UpperCamelCase ( self , lowercase , lowercase = None , **lowercase ) -> np.ndarray: '''simple docstring''' if image.dtype == np.uinta: A__ = image.astype(np.floataa ) # take mean across the whole `image` A__ = np.mean(lowercase ) A__ = np.std(lowercase ) A__ = max(lowercase , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(lowercase , mean=lowercase , std=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> ImageInput: '''simple docstring''' A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = patch_size if patch_size is not None else self.patch_size A__ = max_patches if max_patches is not None else self.max_patches A__ = self.is_vqa if kwargs.get("data_format" , lowercase ) is not None: raise ValueError("data_format is not an accepted input as the outputs are " ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) # PIL RGBA images are converted to RGB if do_convert_rgb: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if is_vqa: if header_text is None: raise ValueError("A header text must be provided for VQA models." ) A__ = kwargs.pop("font_bytes" , lowercase ) A__ = kwargs.pop("font_path" , lowercase ) if isinstance(lowercase , lowercase ): A__ = [header_text] * len(lowercase ) A__ = [ render_header(lowercase , header_text[i] , font_bytes=lowercase , font_path=lowercase ) for i, image in enumerate(lowercase ) ] if do_normalize: A__ = [self.normalize(image=lowercase ) for image in images] # convert to torch tensor and permute A__ = [ self.extract_flattened_patches(image=lowercase , max_patches=lowercase , patch_size=lowercase ) for image in images ] # create attention mask in numpy A__ = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] A__ = BatchFeature( data={"flattened_patches": images, "attention_mask": attention_masks} , tensor_type=lowercase ) return encoded_outputs
68
import random class a__ : """simple docstring""" @staticmethod def UpperCamelCase ( lowercase ) -> tuple[list[int], list[int]]: '''simple docstring''' A__ = [ord(lowercase ) for i in text] A__ = [] A__ = [] for i in plain: A__ = random.randint(1 , 300 ) A__ = (i + k) * k cipher.append(lowercase ) key.append(lowercase ) return cipher, key @staticmethod def UpperCamelCase ( lowercase , lowercase ) -> str: '''simple docstring''' A__ = [] for i in range(len(lowercase ) ): A__ = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowercase ) ) return "".join(lowercase ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
68
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) UpperCAmelCase__ = pytest.mark.integration @pytest.mark.parametrize('''path''' , ['''paws''', '''csv'''] ) def _a ( a :Dict , a :Optional[int] ) -> List[str]: inspect_dataset(a , a ) a = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.filterwarnings('''ignore:inspect_metric is deprecated:FutureWarning''' ) @pytest.mark.filterwarnings('''ignore:metric_module_factory is deprecated:FutureWarning''' ) @pytest.mark.parametrize('''path''' , ['''accuracy'''] ) def _a ( a :Any , a :Optional[Any] ) -> Union[str, Any]: inspect_metric(a , a ) a = path + '''.py''' assert script_name in os.listdir(a ) assert "__pycache__" not in os.listdir(a ) @pytest.mark.parametrize( '''path, config_name, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :Union[str, Any] , a :List[Any] , a :Optional[Any] ) -> List[str]: a = get_dataset_config_info(a , config_name=a ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def _a ( a :str , a :Tuple , a :Any ) -> Tuple: with pytest.raises(a ): get_dataset_config_info(a , config_name=a ) @pytest.mark.parametrize( '''path, expected''' , [ ('''squad''', '''plain_text'''), ('''acronym_identification''', '''default'''), ('''lhoestq/squad''', '''plain_text'''), ('''lhoestq/test''', '''default'''), ('''lhoestq/demo1''', '''lhoestq--demo1'''), ('''dalle-mini/wit''', '''dalle-mini--wit'''), ] , ) def _a ( a :Any , a :Union[str, Any] ) -> Optional[Any]: a = get_dataset_config_names(a ) assert expected in config_names @pytest.mark.parametrize( '''path, expected_configs, expected_splits_in_first_config''' , [ ('''squad''', ['''plain_text'''], ['''train''', '''validation''']), ('''dalle-mini/wit''', ['''dalle-mini--wit'''], ['''train''']), ('''paws''', ['''labeled_final''', '''labeled_swap''', '''unlabeled_final'''], ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :Optional[int] , a :Optional[Any] , a :Optional[Any] ) -> List[Any]: a = get_dataset_infos(a ) assert list(infos.keys() ) == expected_configs a = expected_configs[0] assert expected_config in infos a = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( '''path, expected_config, expected_splits''' , [ ('''squad''', '''plain_text''', ['''train''', '''validation''']), ('''dalle-mini/wit''', '''dalle-mini--wit''', ['''train''']), ('''paws''', '''labeled_final''', ['''train''', '''test''', '''validation''']), ] , ) def _a ( a :str , a :Union[str, Any] , a :Union[str, Any] ) -> Any: a = get_dataset_infos(a ) assert expected_config in infos a = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( '''path, config_name, expected_exception''' , [ ('''paws''', None, ValueError), ] , ) def _a ( a :Dict , a :Any , a :Optional[int] ) -> Tuple: with pytest.raises(a ): get_dataset_split_names(a , config_name=a )
0
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ = 2 while i * i <= n: A__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
68
0
'''simple docstring''' import logging import os import threading import time try: import warnings except ImportError: SCREAMING_SNAKE_CASE_: Tuple =None try: import msvcrt except ImportError: SCREAMING_SNAKE_CASE_: Any =None try: import fcntl except ImportError: SCREAMING_SNAKE_CASE_: int =None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: SCREAMING_SNAKE_CASE_: Tuple =OSError # Data # ------------------------------------------------ SCREAMING_SNAKE_CASE_: int =[ 'Timeout', 'BaseFileLock', 'WindowsFileLock', 'UnixFileLock', 'SoftFileLock', 'FileLock', ] SCREAMING_SNAKE_CASE_: Union[str, Any] ='3.0.12' SCREAMING_SNAKE_CASE_: Any =None def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' global _logger UpperCAmelCase_ = _logger or logging.getLogger(__name__ ) return _logger class __A ( UpperCamelCase__ ): def __init__(self : Optional[Any] , __a : Optional[int] ): UpperCAmelCase_ = lock_file return None def __str__(self : Optional[int] ): UpperCAmelCase_ = f"""The file lock '{self.lock_file}' could not be acquired.""" return temp class __A : def __init__(self : Optional[int] , __a : Optional[Any] ): UpperCAmelCase_ = lock return None def __enter__(self : int ): return self.lock def __exit__(self : Dict , __a : int , __a : Any , __a : Union[str, Any] ): self.lock.release() return None class __A : def __init__(self : Optional[int] , __a : str , __a : Dict=-1 , __a : Tuple=None ): UpperCAmelCase_ = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long UpperCAmelCase_ = self.hash_filename_if_too_long(__a , __a ) # The path to the lock file. UpperCAmelCase_ = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. UpperCAmelCase_ = None # The default timeout value. UpperCAmelCase_ = timeout # We use this lock primarily for the lock counter. UpperCAmelCase_ = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. UpperCAmelCase_ = 0 return None @property def _lowercase (self : Optional[int] ): return self._lock_file @property def _lowercase (self : int ): return self._timeout @timeout.setter def _lowercase (self : Optional[Any] , __a : Optional[Any] ): UpperCAmelCase_ = float(__a ) return None def _lowercase (self : List[str] ): raise NotImplementedError() def _lowercase (self : Union[str, Any] ): raise NotImplementedError() @property def _lowercase (self : str ): return self._lock_file_fd is not None def _lowercase (self : Tuple , __a : Optional[Any]=None , __a : List[Any]=0.05 ): # Use the default timeout, if no timeout is provided. if timeout is None: UpperCAmelCase_ = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 UpperCAmelCase_ = id(self ) UpperCAmelCase_ = self._lock_file UpperCAmelCase_ = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f"""Attempting to acquire lock {lock_id} on {lock_filename}""" ) self._acquire() if self.is_locked: logger().debug(f"""Lock {lock_id} acquired on {lock_filename}""" ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f"""Timeout on acquiring lock {lock_id} on {lock_filename}""" ) raise Timeout(self._lock_file ) else: logger().debug( f"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" ) time.sleep(__a ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: UpperCAmelCase_ = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def _lowercase (self : Any , __a : Optional[Any]=False ): with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: UpperCAmelCase_ = id(self ) UpperCAmelCase_ = self._lock_file logger().debug(f"""Attempting to release lock {lock_id} on {lock_filename}""" ) self._release() UpperCAmelCase_ = 0 logger().debug(f"""Lock {lock_id} released on {lock_filename}""" ) return None def __enter__(self : Optional[int] ): self.acquire() return self def __exit__(self : int , __a : str , __a : List[str] , __a : Any ): self.release() return None def __del__(self : Tuple ): self.release(force=__a ) return None def _lowercase (self : str , __a : str , __a : int ): UpperCAmelCase_ = os.path.basename(__a ) if len(__a ) > max_length and max_length > 0: UpperCAmelCase_ = os.path.dirname(__a ) UpperCAmelCase_ = str(hash(__a ) ) UpperCAmelCase_ = filename[: max_length - len(__a ) - 8] + "..." + hashed_filename + ".lock" return os.path.join(__a , __a ) else: return path class __A ( UpperCamelCase__ ): def __init__(self : int , __a : Optional[int] , __a : Optional[Any]=-1 , __a : List[Any]=None ): from .file_utils import relative_to_absolute_path super().__init__(__a , timeout=__a , max_filename_length=__a ) UpperCAmelCase_ = "\\\\?\\" + relative_to_absolute_path(self.lock_file ) def _lowercase (self : str ): UpperCAmelCase_ = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: UpperCAmelCase_ = os.open(self._lock_file , __a ) except OSError: pass else: try: msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(__a ) else: UpperCAmelCase_ = fd return None def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self._lock_file_fd UpperCAmelCase_ = None msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 ) os.close(__a ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __A ( UpperCamelCase__ ): def __init__(self : Union[str, Any] , __a : List[Any] , __a : Any=-1 , __a : str=None ): UpperCAmelCase_ = os.statvfs(os.path.dirname(__a ) ).f_namemax super().__init__(__a , timeout=__a , max_filename_length=__a ) def _lowercase (self : str ): UpperCAmelCase_ = os.O_RDWR | os.O_CREAT | os.O_TRUNC UpperCAmelCase_ = os.open(self._lock_file , __a ) try: fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(__a ) else: UpperCAmelCase_ = fd return None def _lowercase (self : Union[str, Any] ): # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition UpperCAmelCase_ = self._lock_file_fd UpperCAmelCase_ = None fcntl.flock(__a , fcntl.LOCK_UN ) os.close(__a ) return None class __A ( UpperCamelCase__ ): def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: UpperCAmelCase_ = os.open(self._lock_file , __a ) except OSError: pass else: UpperCAmelCase_ = fd return None def _lowercase (self : str ): os.close(self._lock_file_fd ) UpperCAmelCase_ = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None SCREAMING_SNAKE_CASE_: Any =None if msvcrt: SCREAMING_SNAKE_CASE_: List[str] =WindowsFileLock elif fcntl: SCREAMING_SNAKE_CASE_: List[Any] =UnixFileLock else: SCREAMING_SNAKE_CASE_: Optional[Any] =SoftFileLock if warnings is not None: warnings.warn('only soft file lock is available')
1
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: lowerCAmelCase__ = json.load(f) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return FSMTTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = F'facebook/wmt19-{pair}' A__ = self.get_tokenizer(lowercase ) A__ = self.get_model(lowercase ) A__ = bleu_data[pair]["src"] A__ = bleu_data[pair]["tgt"] A__ = tokenizer(lowercase , return_tensors="pt" , truncation=lowercase , padding="longest" ).to(lowercase ) A__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) A__ = tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) A__ = calculate_bleu(lowercase , lowercase ) print(lowercase ) self.assertGreaterEqual(scores["bleu"] , lowercase )
68
0
'''simple docstring''' lowerCamelCase : List[str] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
2
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> list: '''simple docstring''' A__ = int(SCREAMING_SNAKE_CASE_ ) if n_element < 1: A__ = ValueError("a should be a positive number" ) raise my_error A__ = [1] A__ , A__ , A__ = (0, 0, 0) A__ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowerCAmelCase__ = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") lowerCAmelCase__ = hamming(int(n)) print("""-----------------------------------------------------""") print(f"""The list with nth numbers is: {hamming_numbers}""") print("""-----------------------------------------------------""")
68
0
'''simple docstring''' import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def lowerCAmelCase_ ( snake_case__ ): '''simple docstring''' return (data["data"], data["target"]) def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' A : int = XGBClassifier() classifier.fit(snake_case__ , snake_case__ ) return classifier def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[Any] = load_iris() A, A : List[str] = data_handling(snake_case__ ) A, A, A, A : Optional[Any] = train_test_split( snake_case__ , snake_case__ , test_size=0.25 ) A : Dict = iris['''target_names'''] # Create an XGBoost Classifier from the training data A : Tuple = xgboost(snake_case__ , snake_case__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( snake_case__ , snake_case__ , snake_case__ , display_labels=snake_case__ , cmap='''Blues''' , normalize='''true''' , ) plt.title('''Normalized Confusion Matrix - IRIS Dataset''' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
3
import copy import random from transformers import CLIPTokenizer class a__ ( snake_case ): """simple docstring""" def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' super().__init__(*lowercase , **lowercase ) A__ = {} def UpperCamelCase ( self , lowercase , *lowercase , **lowercase ) -> str: '''simple docstring''' A__ = super().add_tokens(lowercase , *lowercase , **lowercase ) if num_added_tokens == 0: raise ValueError( F'The tokenizer already contains the token {placeholder_token}. Please pass a different' " `placeholder_token` that is not already in the tokenizer." ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=1 , **lowercase ) -> Any: '''simple docstring''' A__ = [] if num_vec_per_token == 1: self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) else: A__ = [] for i in range(lowercase ): A__ = placeholder_token + F'_{i}' self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'The tokenizer already has placeholder token {token} that can get confused with' F' {placeholder_token}keep placeholder tokens independent' ) A__ = output def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=1.0 ) -> List[Any]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = [] for i in range(len(lowercase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=lowercase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: A__ = self.token_map[placeholder_token] A__ = tokens[: 1 + int(len(lowercase ) * prop_tokens_to_load )] if vector_shuffle: A__ = copy.copy(lowercase ) random.shuffle(lowercase ) A__ = text.replace(lowercase , " ".join(lowercase ) ) return text def __call__( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> str: '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> List[str]: '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , )
68
0
'''simple docstring''' from abc import ABC, abstractmethod from argparse import ArgumentParser class UpperCAmelCase_ ( __lowercase ): @staticmethod @abstractmethod def __UpperCAmelCase ( UpperCAmelCase__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __UpperCAmelCase ( self : List[Any] ) -> str: raise NotImplementedError()
4
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Tuple: '''simple docstring''' if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A__ = [[w, v]] if not self.graph.get(lowercase ): A__ = [] def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Any: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self , lowercase=-2 ) -> str: '''simple docstring''' A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s A__ = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> int: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin class a__ : """simple docstring""" def __init__( self ) -> int: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A__ = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A__ = [[w, u]] def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> str: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Dict: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> List[Any]: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin
68
0
# Copyright 2021 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 argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def UpperCAmelCase_ ( ) -> List[Any]: """simple docstring""" _lowercase =ArgumentParser('''Accelerate CLI tool''' , usage='''accelerate <command> [<args>]''' , allow_abbrev=__snake_case ) _lowercase =parser.add_subparsers(help='''accelerate command helpers''' ) # Register commands get_config_parser(subparsers=__snake_case ) env_command_parser(subparsers=__snake_case ) launch_command_parser(subparsers=__snake_case ) tpu_command_parser(subparsers=__snake_case ) test_command_parser(subparsers=__snake_case ) # Let's go _lowercase =parser.parse_args() if not hasattr(__snake_case , '''func''' ): parser.print_help() exit(1 ) # Run args.func(__snake_case ) if __name__ == "__main__": main()
5
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
0
from ...configuration_utils import PretrainedConfig from ...utils import logging A : str = logging.get_logger(__name__) A : Dict = { 'vinvino02/glpn-kitti': 'https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json', # See all GLPN models at https://huggingface.co/models?filter=glpn } class __A( a ): snake_case_ = '''glpn''' def __init__( self , _snake_case=3 , _snake_case=4 , _snake_case=[2, 2, 2, 2] , _snake_case=[8, 4, 2, 1] , _snake_case=[32, 64, 160, 256] , _snake_case=[7, 3, 3, 3] , _snake_case=[4, 2, 2, 2] , _snake_case=[1, 2, 5, 8] , _snake_case=[4, 4, 4, 4] , _snake_case="gelu" , _snake_case=0.0 , _snake_case=0.0 , _snake_case=0.02 , _snake_case=0.1 , _snake_case=1E-6 , _snake_case=64 , _snake_case=10 , _snake_case=-1 , **_snake_case , ) -> List[Any]: '''simple docstring''' super().__init__(**_snake_case ) __a = num_channels __a = num_encoder_blocks __a = depths __a = sr_ratios __a = hidden_sizes __a = patch_sizes __a = strides __a = mlp_ratios __a = num_attention_heads __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = drop_path_rate __a = layer_norm_eps __a = decoder_hidden_size __a = max_depth __a = head_in_index
6
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
0
from typing import Dict from .base import GenericTensor, Pipeline class A ( _UpperCAmelCase ): """simple docstring""" def snake_case__ ( self : int,lowercase_ : Dict=None,lowercase_ : Tuple=None,lowercase_ : List[Any]=None,**lowercase_ : Any )-> Optional[Any]: '''simple docstring''' if tokenize_kwargs is None: A__ = {} if truncation is not None: if "truncation" in tokenize_kwargs: raise ValueError( 'truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)' ) A__ = truncation A__ = tokenize_kwargs A__ = {} if return_tensors is not None: A__ = return_tensors return preprocess_params, {}, postprocess_params def snake_case__ ( self : Dict,lowercase_ : List[Any],**lowercase_ : Tuple )-> Dict[str, GenericTensor]: '''simple docstring''' A__ = self.framework A__ = self.tokenizer(lowercase_,return_tensors=lowercase_,**lowercase_ ) return model_inputs def snake_case__ ( self : Tuple,lowercase_ : int )-> Optional[Any]: '''simple docstring''' A__ = self.model(**lowercase_ ) return model_outputs def snake_case__ ( self : Tuple,lowercase_ : Tuple,lowercase_ : List[str]=False )-> Any: '''simple docstring''' if return_tensors: return model_outputs[0] if self.framework == "pt": return model_outputs[0].tolist() elif self.framework == "tf": return model_outputs[0].numpy().tolist() def __call__( self : List[Any],*lowercase_ : int,**lowercase_ : Optional[Any] )-> int: '''simple docstring''' return super().__call__(*lowercase_,**lowercase_ )
7
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''google/canine-s''': '''https://huggingface.co/google/canine-s/resolve/main/config.json''', # See all CANINE models at https://huggingface.co/models?filter=canine } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = "canine" def __init__( self : str , _UpperCamelCase : Optional[Any]=7_6_8 , _UpperCamelCase : Optional[int]=1_2 , _UpperCamelCase : int=1_2 , _UpperCamelCase : Tuple=3_0_7_2 , _UpperCamelCase : Tuple="gelu" , _UpperCamelCase : Optional[Any]=0.1 , _UpperCamelCase : Union[str, Any]=0.1 , _UpperCamelCase : Dict=1_6_3_8_4 , _UpperCamelCase : List[Any]=1_6 , _UpperCamelCase : Tuple=0.02 , _UpperCamelCase : Optional[Any]=1e-12 , _UpperCamelCase : Union[str, Any]=0 , _UpperCamelCase : Union[str, Any]=0xe_0_0_0 , _UpperCamelCase : Dict=0xe_0_0_1 , _UpperCamelCase : Any=4 , _UpperCamelCase : Tuple=4 , _UpperCamelCase : List[str]=8 , _UpperCamelCase : Any=1_6_3_8_4 , _UpperCamelCase : List[str]=1_2_8 , **_UpperCamelCase : str , ) ->List[Any]: super().__init__(pad_token_id=_UpperCamelCase , bos_token_id=_UpperCamelCase , eos_token_id=_UpperCamelCase , **_UpperCamelCase ) snake_case_ = max_position_embeddings snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = intermediate_size snake_case_ = hidden_act snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = initializer_range snake_case_ = type_vocab_size snake_case_ = layer_norm_eps # Character config: snake_case_ = downsampling_rate snake_case_ = upsampling_kernel_size snake_case_ = num_hash_functions snake_case_ = num_hash_buckets snake_case_ = local_transformer_stride
8
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: A__ = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE_ ) A__ = num - key if num < 0: A__ = num + len(string.ascii_uppercase ) A__ = translated + string.ascii_uppercase[num] else: A__ = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = input("Encrypted message: " ) A__ = message.upper() decrypt(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
0
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __lowerCAmelCase : Any =logging.get_logger(__name__) __lowerCAmelCase : List[str] ={'vocab_file': 'vocab.txt'} __lowerCAmelCase : Dict ={ 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __lowerCAmelCase : int ={ 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def _UpperCamelCase ( lowercase__ ): with open(lowercase__ , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = f.read().splitlines() return [l.strip() for l in lines] class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE__ : str = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES SCREAMING_SNAKE_CASE__ : Dict = ['''input_ids''', '''attention_mask'''] def __init__( self :Dict , lowerCAmelCase__ :int , lowerCAmelCase__ :int="<unk>" , lowerCAmelCase__ :List[Any]="<cls>" , lowerCAmelCase__ :Optional[Any]="<pad>" , lowerCAmelCase__ :List[str]="<mask>" , lowerCAmelCase__ :List[Any]="<eos>" , **lowerCAmelCase__ :Optional[int] , ) -> Optional[int]: super().__init__(**lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : List[str] = load_vocab_file(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = dict(enumerate(self.all_tokens ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {tok: ind for ind, tok in enumerate(self.all_tokens )} __SCREAMING_SNAKE_CASE : Tuple = unk_token __SCREAMING_SNAKE_CASE : Tuple = cls_token __SCREAMING_SNAKE_CASE : Dict = pad_token __SCREAMING_SNAKE_CASE : Dict = mask_token __SCREAMING_SNAKE_CASE : Union[str, Any] = eos_token __SCREAMING_SNAKE_CASE : Dict = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __magic_name__( self :str , lowerCAmelCase__ :int ) -> str: return self._id_to_token.get(lowerCAmelCase__ , self.unk_token ) def __magic_name__( self :List[str] , lowerCAmelCase__ :str ) -> int: return self._token_to_id.get(lowerCAmelCase__ , self._token_to_id.get(self.unk_token ) ) def __magic_name__( self :Tuple , lowerCAmelCase__ :List[str] , **lowerCAmelCase__ :Tuple ) -> Tuple: return text.split() def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :Optional[int]=False ) -> Optional[int]: return len(self._id_to_token ) def __magic_name__( self :Tuple ) -> Any: return {token: i for i, token in enumerate(self.all_tokens )} def __magic_name__( self :str , lowerCAmelCase__ :str ) -> int: return self._token_to_id.get(lowerCAmelCase__ , self._token_to_id.get(self.unk_token ) ) def __magic_name__( self :Optional[int] , lowerCAmelCase__ :int ) -> str: return self._id_to_token.get(lowerCAmelCase__ , self.unk_token ) def __magic_name__( self :Tuple , lowerCAmelCase__ :List[int] , lowerCAmelCase__ :Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE : str = [self.cls_token_id] __SCREAMING_SNAKE_CASE : Optional[Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __magic_name__( self :Union[str, Any] , lowerCAmelCase__ :List , lowerCAmelCase__ :Optional[List] = None , lowerCAmelCase__ :bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] __SCREAMING_SNAKE_CASE : Any = [1] + ([0] * len(lowerCAmelCase__ )) + [1] if token_ids_a is not None: mask += [0] * len(lowerCAmelCase__ ) + [1] return mask def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE : str = os.path.join(lowerCAmelCase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(lowerCAmelCase__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __magic_name__( self :int ) -> int: return self.get_vocab_size(with_added_tokens=lowerCAmelCase__ ) def __magic_name__( self :Optional[int] , lowerCAmelCase__ :Union[List[str], List[AddedToken]] , lowerCAmelCase__ :bool = False ) -> int: return super()._add_tokens(lowerCAmelCase__ , special_tokens=lowerCAmelCase__ )
9
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = SpeechTaTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(lowercase ) A__ = AddedToken("<mask>" , lstrip=lowercase , rstrip=lowercase ) A__ = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = "this is a test" A__ = "this is a test" return input_text, output_text def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=20 , lowercase=5 ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.get_input_output_texts(lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) return text, ids def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = "<pad>" A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(lowercase ) , 81 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] A__ = tokenizer.add_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size + len(lowercase ) ) A__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) A__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A__ = tokenizer.add_special_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size_a + len(lowercase ) ) A__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(lowercase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) A__ = tokenizer.convert_tokens_to_ids(lowercase ) # fmt: off self.assertListEqual(lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off A__ = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=lowercase , )
68
0
import string import numpy def lowerCAmelCase_ ( __a , __a ) -> int: """simple docstring""" return b if a == 0 else greatest_common_divisor(b % a , __a ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' lowercase_ = string.ascii_uppercase + string.digits # This cipher takes alphanumerics into account # i.e. a total of 36 characters # take x and return x % len(key_string) lowercase_ = numpy.vectorize(lambda __SCREAMING_SNAKE_CASE : x % 36 ) lowercase_ = numpy.vectorize(__SCREAMING_SNAKE_CASE ) def __init__(self : Union[str, Any] , UpperCAmelCase_ : numpy.ndarray) ->None: '''simple docstring''' lowerCamelCase__: int =self.modulus(UpperCAmelCase_) # mod36 calc's on the encrypt key self.check_determinant() # validate the determinant of the encryption key lowerCamelCase__: Dict =encrypt_key.shape[0] def SCREAMING_SNAKE_CASE_ (self : str , UpperCAmelCase_ : str) ->int: '''simple docstring''' return self.key_string.index(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Any , UpperCAmelCase_ : int) ->str: '''simple docstring''' return self.key_string[round(UpperCAmelCase_)] def SCREAMING_SNAKE_CASE_ (self : int) ->None: '''simple docstring''' lowerCamelCase__: str =round(numpy.linalg.det(self.encrypt_key)) if det < 0: lowerCamelCase__: str =det % len(self.key_string) lowerCamelCase__: Optional[int] =len(self.key_string) if greatest_common_divisor(UpperCAmelCase_ , len(self.key_string)) != 1: lowerCamelCase__: Tuple =( F"""determinant modular {req_l} of encryption key({det}) """ F"""is not co prime w.r.t {req_l}.\nTry another key.""" ) raise ValueError(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Optional[int] , UpperCAmelCase_ : str) ->str: '''simple docstring''' lowerCamelCase__: int =[char for char in text.upper() if char in self.key_string] lowerCamelCase__: List[str] =chars[-1] while len(UpperCAmelCase_) % self.break_key != 0: chars.append(UpperCAmelCase_) return "".join(UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : Tuple , UpperCAmelCase_ : str) ->str: '''simple docstring''' lowerCamelCase__: Any =self.process_text(text.upper()) lowerCamelCase__: List[str] ="" for i in range(0 , len(UpperCAmelCase_) - self.break_key + 1 , self.break_key): lowerCamelCase__: Union[str, Any] =text[i : i + self.break_key] lowerCamelCase__: Optional[int] =[self.replace_letters(UpperCAmelCase_) for char in batch] lowerCamelCase__: Any =numpy.array([vec]).T lowerCamelCase__: Union[str, Any] =self.modulus(self.encrypt_key.dot(UpperCAmelCase_)).T.tolist()[ 0 ] lowerCamelCase__: Dict ="".join( self.replace_digits(UpperCAmelCase_) for num in batch_encrypted) encrypted += encrypted_batch return encrypted def SCREAMING_SNAKE_CASE_ (self : List[str]) ->numpy.ndarray: '''simple docstring''' lowerCamelCase__: Tuple =round(numpy.linalg.det(self.encrypt_key)) if det < 0: lowerCamelCase__: str =det % len(self.key_string) lowerCamelCase__: Optional[int] =None for i in range(len(self.key_string)): if (det * i) % len(self.key_string) == 1: lowerCamelCase__: Optional[int] =i break lowerCamelCase__: str =( det_inv * numpy.linalg.det(self.encrypt_key) * numpy.linalg.inv(self.encrypt_key) ) return self.to_int(self.modulus(UpperCAmelCase_)) def SCREAMING_SNAKE_CASE_ (self : Optional[Any] , UpperCAmelCase_ : str) ->str: '''simple docstring''' lowerCamelCase__: Any =self.make_decrypt_key() lowerCamelCase__: Any =self.process_text(text.upper()) lowerCamelCase__: Dict ="" for i in range(0 , len(UpperCAmelCase_) - self.break_key + 1 , self.break_key): lowerCamelCase__: List[str] =text[i : i + self.break_key] lowerCamelCase__: List[str] =[self.replace_letters(UpperCAmelCase_) for char in batch] lowerCamelCase__: Dict =numpy.array([vec]).T lowerCamelCase__: Any =self.modulus(decrypt_key.dot(UpperCAmelCase_)).T.tolist()[0] lowerCamelCase__: int ="".join( self.replace_digits(UpperCAmelCase_) for num in batch_decrypted) decrypted += decrypted_batch return decrypted def lowerCAmelCase_ ( ) -> None: """simple docstring""" lowerCamelCase__: Optional[Any] =int(input("Enter the order of the encryption key: " ) ) lowerCamelCase__: str =[] print("Enter each row of the encryption key with space separated integers" ) for _ in range(__a ): lowerCamelCase__: List[Any] =[int(__a ) for x in input().split()] hill_matrix.append(__a ) lowerCamelCase__: Dict =HillCipher(numpy.array(__a ) ) print("Would you like to encrypt or decrypt some text? (1 or 2)" ) lowerCamelCase__: List[str] =input("\n1. Encrypt\n2. Decrypt\n" ) if option == "1": lowerCamelCase__: Union[str, Any] =input("What text would you like to encrypt?: " ) print("Your encrypted text is:" ) print(hc.encrypt(__a ) ) elif option == "2": lowerCamelCase__: Optional[int] =input("What text would you like to decrypt?: " ) print("Your decrypted text is:" ) print(hc.decrypt(__a ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
10
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> List[str]: '''simple docstring''' A__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } A__ = F'{src_lang}-{tgt_lang}' A__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) # make sure we are under the root of the project lowerCAmelCase__ = Path(__file__).resolve().parent.parent.parent lowerCAmelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = model_name.split("""-""") lowerCAmelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
68
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { 'facebook/timesformer': 'https://huggingface.co/facebook/timesformer/resolve/main/config.json', } class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = "timesformer" def __init__( self , __lowerCamelCase=2_2_4 , __lowerCamelCase=1_6 , __lowerCamelCase=3 , __lowerCamelCase=8 , __lowerCamelCase=7_6_8 , __lowerCamelCase=1_2 , __lowerCamelCase=1_2 , __lowerCamelCase=3_0_7_2 , __lowerCamelCase="gelu" , __lowerCamelCase=0.0 , __lowerCamelCase=0.0 , __lowerCamelCase=0.0_2 , __lowerCamelCase=1e-6 , __lowerCamelCase=True , __lowerCamelCase="divided_space_time" , __lowerCamelCase=0 , **__lowerCamelCase , ) -> Tuple: super().__init__(**__lowerCamelCase) _A : Any = image_size _A : Union[str, Any] = patch_size _A : Tuple = num_channels _A : Dict = num_frames _A : int = hidden_size _A : Union[str, Any] = num_hidden_layers _A : List[Any] = num_attention_heads _A : Optional[int] = intermediate_size _A : Union[str, Any] = hidden_act _A : List[Any] = hidden_dropout_prob _A : Any = attention_probs_dropout_prob _A : Tuple = initializer_range _A : Tuple = layer_norm_eps _A : str = qkv_bias _A : str = attention_type _A : Dict = drop_path_rate
11
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = feature_size A__ = sampling_rate A__ = padding_value A__ = kwargs.pop("padding_side" , "right" ) A__ = kwargs.pop("return_attention_mask" , lowercase ) super().__init__(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = None , lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys() )}' ) A__ = processed_features[self.model_input_names[0]] A__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase ) == 0: if return_attention_mask: A__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A__ = required_input[0] if isinstance(lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase ): A__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase ): A__ = "tf" elif is_torch_tensor(lowercase ): A__ = "pt" elif isinstance(lowercase , (int, float, list, tuple, np.ndarray) ): A__ = "np" else: raise ValueError( F'type of {first_element} unknown: {type(lowercase )}. ' "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A__ = to_numpy(lowercase ) else: A__ = [to_numpy(lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy A__ = self._get_padding_strategies(padding=lowercase , max_length=lowercase ) A__ = processed_features[self.model_input_names[0]] A__ = len(lowercase ) if not all(len(lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) A__ = [] for i in range(lowercase ): A__ = {k: v[i] for k, v in processed_features.items()} # truncation A__ = self._truncate( lowercase , max_length=lowercase , pad_to_multiple_of=lowercase , truncation=lowercase , ) truncated_inputs.append(lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A__ = PaddingStrategy.MAX_LENGTH A__ = {} for i in range(lowercase ): # padding A__ = self._pad( truncated_inputs[i] , max_length=lowercase , padding_strategy=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: A__ = [] if value.dtype is np.dtype(np.floataa ): A__ = value.astype(np.floataa ) batch_outputs[key].append(lowercase ) return BatchFeature(lowercase , tensor_type=lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = PaddingStrategy.DO_NOT_PAD , lowercase = None , lowercase = None , ) -> dict: '''simple docstring''' A__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A__ = len(lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A__ = np.ones(len(lowercase ) , dtype=np.intaa ) if needs_to_be_padded: A__ = max_length - len(lowercase ) if self.padding_side == "right": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (0, difference) ) A__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (difference, 0) ) A__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , ) -> Union[str, Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) A__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = len(lowercase ) > max_length if needs_to_be_truncated: A__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A__ = processed_features["attention_mask"][:max_length] return processed_features def UpperCamelCase ( self , lowercase=False , lowercase=None ) -> Any: '''simple docstring''' if padding is not False: if padding is True: A__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase , lowercase ): A__ = PaddingStrategy(lowercase ) elif isinstance(lowercase , lowercase ): A__ = padding else: A__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
68
0
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration UpperCAmelCase_ = 50_000 UpperCAmelCase_ = 5_000 UpperCAmelCase_ , UpperCAmelCase_ = os.path.split(__file__) UpperCAmelCase_ = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def lowerCamelCase__ ( A__ : datasets.Dataset , A__ : Optional[int] ): '''simple docstring''' for i in range(A__ ): __lowerCamelCase = dataset[i] @get_duration def lowerCamelCase__ ( A__ : datasets.Dataset , A__ : Union[str, Any] , A__ : str ): '''simple docstring''' for i in range(0 , len(A__ ) , A__ ): __lowerCamelCase = dataset[i : i + batch_size] @get_duration def lowerCamelCase__ ( A__ : datasets.Dataset , A__ : Optional[int] , A__ : Union[str, Any] ): '''simple docstring''' with dataset.formatted_as(type=A__ ): for i in range(A__ ): __lowerCamelCase = dataset[i] @get_duration def lowerCamelCase__ ( A__ : datasets.Dataset , A__ : int , A__ : Optional[int] , A__ : Any ): '''simple docstring''' with dataset.formatted_as(type=A__ ): for i in range(0 , A__ , A__ ): __lowerCamelCase = dataset[i : i + batch_size] def lowerCamelCase__ ( ): '''simple docstring''' __lowerCamelCase = {"""num examples""": SPEED_TEST_N_EXAMPLES} __lowerCamelCase = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """pandas""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """torch""", """length""": SMALL_TEST}), (read_formatted, {"""type""": """tensorflow""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}), ] __lowerCamelCase = [ (read, {"""length""": SMALL_TEST}), (read, {"""length""": SPEED_TEST_N_EXAMPLES}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 10}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 100}), (read_batch, {"""length""": SPEED_TEST_N_EXAMPLES, """batch_size""": 1000}), (read_formatted, {"""type""": """numpy""", """length""": SMALL_TEST}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 10}), (read_formatted_batch, {"""type""": """numpy""", """length""": SMALL_TEST, """batch_size""": 1000}), ] with tempfile.TemporaryDirectory() as tmp_dir: print("""generating dataset""" ) __lowerCamelCase = datasets.Features( {"""list""": datasets.Sequence(datasets.Value("""float32""" ) ), """numbers""": datasets.Value("""float32""" )} ) __lowerCamelCase = generate_example_dataset( os.path.join(A__ , """dataset.arrow""" ) , A__ , num_examples=A__ , seq_shapes={"""list""": (100,)} , ) print("""first set of iterations""" ) for func, kwargs in functions: print(func.__name__ , str(A__ ) ) __lowerCamelCase = func(A__ , **A__ ) print("""shuffling dataset""" ) __lowerCamelCase = dataset.shuffle() print("""Second set of iterations (after shuffling""" ) for func, kwargs in functions_shuffled: print("""shuffled """ , func.__name__ , str(A__ ) ) __lowerCamelCase = func( A__ , **A__ ) with open(A__ , """wb""" ) as f: f.write(json.dumps(A__ ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
12
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase : Union[str, Any] = {"""configuration_vit""": ["""VIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTConfig""", """ViTOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Tuple = ["""ViTFeatureExtractor"""] lowerCAmelCase : Any = ["""ViTImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Dict = [ """VIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTForImageClassification""", """ViTForMaskedImageModeling""", """ViTModel""", """ViTPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[Any] = [ """TFViTForImageClassification""", """TFViTModel""", """TFViTPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : int = [ """FlaxViTForImageClassification""", """FlaxViTModel""", """FlaxViTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys lowerCAmelCase : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
13
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'gpt_neox_japanese' def __init__( self , lowercase=32000 , lowercase=2560 , lowercase=32 , lowercase=32 , lowercase=4 , lowercase="gelu" , lowercase=1.00 , lowercase=10000 , lowercase=2048 , lowercase=0.02 , lowercase=1e-5 , lowercase=True , lowercase=31996 , lowercase=31999 , lowercase=0.1 , lowercase=0.0 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_multiple_size A__ = hidden_act A__ = rotary_pct A__ = rotary_emb_base A__ = initializer_range A__ = layer_norm_eps A__ = use_cache A__ = attention_dropout A__ = hidden_dropout
68
0
print((lambda quine: quine % quine)("""print((lambda quine: quine %% quine)(%r))"""))
14
import warnings from functools import wraps from typing import Callable def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Callable ) -> Callable: '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_: int , **SCREAMING_SNAKE_CASE_: Union[str, Any] ): warnings.warn( (F'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
68
0
# Copyright 2021 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 packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_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_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) SCREAMING_SNAKE_CASE :List[str] = 'pytorch_model.bin' SCREAMING_SNAKE_CASE :str = 'pytorch_model.bin.index.json' SCREAMING_SNAKE_CASE :Optional[int] = 'adapter_config.json' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.bin' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.safetensors' SCREAMING_SNAKE_CASE :str = 'tf_model.h5' SCREAMING_SNAKE_CASE :List[Any] = 'tf_model.h5.index.json' SCREAMING_SNAKE_CASE :str = 'model.ckpt' SCREAMING_SNAKE_CASE :List[Any] = 'flax_model.msgpack' SCREAMING_SNAKE_CASE :Optional[int] = 'flax_model.msgpack.index.json' SCREAMING_SNAKE_CASE :Tuple = 'model.safetensors' SCREAMING_SNAKE_CASE :List[Any] = 'model.safetensors.index.json' SCREAMING_SNAKE_CASE :str = 'config.json' SCREAMING_SNAKE_CASE :int = 'preprocessor_config.json' SCREAMING_SNAKE_CASE :Optional[Any] = FEATURE_EXTRACTOR_NAME SCREAMING_SNAKE_CASE :Optional[int] = 'generation_config.json' SCREAMING_SNAKE_CASE :List[str] = 'modelcard.json' SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :Optional[Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility SCREAMING_SNAKE_CASE :str = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. SCREAMING_SNAKE_CASE :Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] SCREAMING_SNAKE_CASE :List[Any] = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" if version.parse(a_ ) < version.parse(a_ ): if "dev" in min_version: __A = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: __A = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
15
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
0
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer lowerCAmelCase_ = ['bert-base-uncased', 'bert-base-cased'] lowerCAmelCase_ = 'hf-internal-testing/tiny-bert-tf-only' if is_tf_available(): class __A ( tf.keras.Model ): '''simple docstring''' def __init__( self : Optional[Any] ,_snake_case : Tuple ) -> List[str]: """simple docstring""" super().__init__() lowercase__ : str = tokenizer lowercase__ : Optional[int] = AutoConfig.from_pretrained(_snake_case ) lowercase__ : int = TFAutoModel.from_config(_snake_case ) def UpperCAmelCase ( self : Tuple ,_snake_case : List[str] ) -> Optional[Any]: """simple docstring""" lowercase__ : List[str] = self.tokenizer(_snake_case ) lowercase__ : Optional[int] = self.bert(**_snake_case ) return out["pooler_output"] @require_tf @require_tensorflow_text class __A ( unittest.TestCase ): '''simple docstring''' def UpperCAmelCase ( self : Tuple ) -> List[str]: """simple docstring""" super().setUp() lowercase__ : int = [ BertTokenizer.from_pretrained(_snake_case ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false lowercase__ : Dict = [TFBertTokenizer.from_pretrained(_snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(_snake_case ,use_fast_bert_tokenizer=_snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) lowercase__ : int = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] lowercase__ : Dict = list(zip(self.test_sentences ,self.test_sentences[::-1] ) ) def UpperCAmelCase ( self : Optional[int] ) -> Dict: """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers ,self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): lowercase__ : Optional[Any] = tokenizer(_snake_case ,return_tensors='''tf''' ,padding='''longest''' ) lowercase__ : Union[str, Any] = tf_tokenizer(_snake_case ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] ,tf.intaa ) == tf_outputs[key] ) ) @slow def UpperCAmelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase__ : Optional[int] = tf_tokenizer(self.paired_sentences ) lowercase__ : Optional[Any] = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] ,text_pair=[sentence[1] for sentence in self.paired_sentences] ,) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] ,tf.intaa ) == separated_outputs[key] ) ) @slow def UpperCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase__ : Tuple = tf.function(_snake_case ) for test_inputs in (self.test_sentences, self.paired_sentences): lowercase__ : int = tf.constant(_snake_case ) lowercase__ : List[Any] = compiled_tokenizer(_snake_case ) lowercase__ : Dict = tf_tokenizer(_snake_case ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def UpperCAmelCase ( self : Optional[Any] ) -> Any: """simple docstring""" for tf_tokenizer in self.tf_tokenizers: lowercase__ : Tuple = ModelToSave(tokenizer=_snake_case ) lowercase__ : str = tf.convert_to_tensor(self.test_sentences ) lowercase__ : Optional[Any] = model(_snake_case ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: lowercase__ : List[Any] = Path(_snake_case ) / '''saved.model''' model.save(_snake_case ) lowercase__ : Union[str, Any] = tf.keras.models.load_model(_snake_case ) lowercase__ : Dict = loaded_model(_snake_case ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) ,1e-5 )
16
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class a__ : """simple docstring""" __lowerCamelCase = BlenderbotSmallConfig __lowerCamelCase = {} __lowerCamelCase = 'gelu' def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=False , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase=0.1 , lowercase=0.1 , lowercase=20 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) A__ = prepare_blenderbot_small_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = TFBlenderbotSmallModel(config=lowercase ).get_decoder() A__ = inputs_dict["input_ids"] A__ = input_ids[:1, :] A__ = inputs_dict["attention_mask"][:1, :] A__ = inputs_dict["head_mask"] A__ = 1 # first forward pass A__ = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(lowercase , attention_mask=lowercase )[0] A__ = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1e-3 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Optional[Any]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Dict=None , SCREAMING_SNAKE_CASE_: List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: A__ = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_tokenizers @require_tf class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __lowerCamelCase = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.tokenizer(self.src_text , return_tensors="tf" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
68
0
"""simple docstring""" def _A ( UpperCamelCase_ : int = 10, UpperCamelCase_ : int = 1000, UpperCamelCase_ : bool = True) -> int: '''simple docstring''' assert ( isinstance(UpperCamelCase_, UpperCamelCase_) and isinstance(UpperCamelCase_, UpperCamelCase_) and isinstance(UpperCamelCase_, UpperCamelCase_) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)") return min_val if option else max_val def _A ( UpperCamelCase_ : int, UpperCamelCase_ : int) -> int: '''simple docstring''' return int((number_a + number_a) / 2) def _A ( UpperCamelCase_ : int, UpperCamelCase_ : int, UpperCamelCase_ : int) -> None: '''simple docstring''' assert ( isinstance(UpperCamelCase_, UpperCamelCase_) and isinstance(UpperCamelCase_, UpperCamelCase_) and isinstance(UpperCamelCase_, UpperCamelCase_) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)") if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value") def answer(UpperCamelCase_ : int) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started...") __lowercase = lower __lowercase = higher __lowercase = [] while True: __lowercase = get_avg(UpperCamelCase_, UpperCamelCase_) last_numbers.append(UpperCamelCase_) if answer(UpperCamelCase_) == "low": __lowercase = number elif answer(UpperCamelCase_) == "high": __lowercase = number else: break print(F"""guess the number : {last_numbers[-1]}""") print(F"""details : {last_numbers!s}""") def _A ( ) -> None: '''simple docstring''' __lowercase = int(input("Enter lower value : ").strip()) __lowercase = int(input("Enter high value : ").strip()) __lowercase = int(input("Enter value to guess : ").strip()) guess_the_number(UpperCamelCase_, UpperCamelCase_, UpperCamelCase_) if __name__ == "__main__": main()
17
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 convert_to_rgb, 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 if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = 1 / 255 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 384, "width": 384} A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = do_resize A__ = size A__ = resample A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ = image_std if image_std is not None else OPENAI_CLIP_STD A__ = do_convert_rgb def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase , default_to_square=lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) A__ = (size["height"], size["width"]) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = resample if resample is not None else self.resample A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = size if size is not None else self.size A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_rescale: A__ = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase ) return encoded_outputs
68
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase : str = { '''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: __lowerCamelCase : Any = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Dict = [ '''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 __lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
18
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = """hf-internal-testing/tiny-random-bert""" lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""") lowerCAmelCase__ = """9b8c223d42b2188cb49d29af482996f9d0f3e5a6""" class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = cached_file(lowercase , lowercase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(lowercase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(lowercase , lowercase ) ) ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) self.assertTrue(os.path.isfile(lowercase ) ) # File is cached at the same place the second time. A__ = cached_file(lowercase , lowercase ) self.assertEqual(lowercase , lowercase ) # Using a specific revision to test the full commit hash. A__ = cached_file(lowercase , lowercase , revision="9b8c223" ) self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): A__ = cached_file("tiny-random-bert" , lowercase ) with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): A__ = cached_file(lowercase , lowercase , revision="aaaa" ) with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertTrue(os.path.isfile(os.path.join(lowercase , ".no_exist" , lowercase , "conf" ) ) ) A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = cached_file(lowercase , "conf" , local_files_only=lowercase , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = mock.Mock() A__ = 500 A__ = {} A__ = HTTPError A__ = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=lowercase ) as mock_head: A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_connection_errors=lowercase ) self.assertIsNone(lowercase ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) def UpperCamelCase ( self ) -> str: '''simple docstring''' self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): get_file_from_repo("bert-base-case" , lowercase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): get_file_from_repo("bert-base-cased" , lowercase , revision="ahaha" ) A__ = get_file_from_repo("bert-base-cased" , lowercase ) # The name is the cached name which is not very easy to test, so instead we load the content. A__ = json.loads(open(lowercase , "r" ).read() ) self.assertEqual(config["hidden_size"] , 768 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A__ = Path(lowercase ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(lowercase , "a.txt" ) , str(lowercase ) ) self.assertIsNone(get_file_from_repo(lowercase , "b.txt" ) )
68
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('TEST_SAGEMAKER' , 'False' ) ) is not True , reason='Skipping test because should only be run when releasing minor transformers version' , ) @pytest.mark.usefixtures('sm_env' ) @parameterized_class( [ { 'framework': 'pytorch', 'script': 'run_glue.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_50, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'pytorch', 'script': 'run_ddp.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_00, 'eval_accuracy': 0.7, 'eval_loss': 0.6}, }, { 'framework': 'tensorflow', 'script': 'run_tf_dist.py', 'model_name_or_path': 'distilbert-base-cased', 'instance_type': 'ml.p3.16xlarge', 'results': {'train_runtime': 6_00, 'eval_accuracy': 0.6, 'eval_loss': 0.7}, }, ] ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> Any: if self.framework == "pytorch": subprocess.run( f'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding="utf-8" , check=lowercase , ) assert hasattr(self , "env" ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> Optional[Any]: lowerCamelCase_ = f'{self.env.base_job_name}-{instance_count}-{"ddp" if "ddp" in self.script else "smd"}' # distributed data settings lowerCamelCase_ = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=lowercase , instance_count=lowercase , instance_type=self.instance_type , debugger_hook_config=lowercase , hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , distribution=lowercase , py_version="py36" , ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: TrainingJobAnalytics(lowercase ).export_csv(f'{self.env.test_path}/{job_name}_metrics.csv' ) @parameterized.expand([(2,)] ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: # create estimator lowerCamelCase_ = self.create_estimator(lowercase ) # run training estimator.fit() # result dataframe lowerCamelCase_ = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis lowerCamelCase_ = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) lowerCamelCase_ = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping lowerCamelCase_ = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'{estimator.latest_training_job.name}.json' , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , lowercase )
19
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = AutoencoderKL __lowerCamelCase = 'sample' __lowerCamelCase = 1e-2 @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = 4 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase ) return {"sample": image} @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } A__ = self.dummy_input return init_dict, inputs_dict def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ , A__ = self.prepare_init_args_and_inputs_for_common() A__ = self.model_class(**lowercase ) model.to(lowercase ) assert not model.is_gradient_checkpointing and model.training A__ = model(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() A__ = torch.randn_like(lowercase ) A__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing A__ = self.model_class(**lowercase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowercase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training A__ = model_a(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() A__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) A__ = dict(model.named_parameters() ) A__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ , A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowercase ) self.assertIsNotNone(lowercase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase ) A__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) A__ = model.to(lowercase ) model.eval() if torch_device == "mps": A__ = torch.manual_seed(0 ) else: A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) A__ = image.to(lowercase ) with torch.no_grad(): A__ = model(lowercase , sample_posterior=lowercase , generator=lowercase ).sample A__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": A__ = torch.tensor( [ -4.00_78e-01, -3.83_23e-04, -1.26_81e-01, -1.14_62e-01, 2.00_95e-01, 1.08_93e-01, -8.82_47e-02, -3.03_61e-01, -9.86_44e-03, ] ) elif torch_device == "cpu": A__ = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: A__ = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowercase , lowercase , rtol=1e-2 ) ) @slow class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' return F'gaussian_noise_s={seed}_shape={"_".join([str(lowercase ) for s in shape] )}.npy' def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self , lowercase=0 , lowercase=(4, 3, 512, 512) , lowercase=False ) -> Optional[int]: '''simple docstring''' A__ = torch.floataa if fpaa else torch.floataa A__ = torch.from_numpy(load_hf_numpy(self.get_file_format(lowercase , lowercase ) ) ).to(lowercase ).to(lowercase ) return image def UpperCamelCase ( self , lowercase="CompVis/stable-diffusion-v1-4" , lowercase=False ) -> Any: '''simple docstring''' A__ = "fp16" if fpaa else None A__ = torch.floataa if fpaa else torch.floataa A__ = AutoencoderKL.from_pretrained( lowercase , subfolder="vae" , torch_dtype=lowercase , revision=lowercase , ) model.to(lowercase ).eval() return model def UpperCamelCase ( self , lowercase=0 ) -> List[str]: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(lowercase ) return torch.Generator(device=lowercase ).manual_seed(lowercase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , fpaa=lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) with torch.no_grad(): A__ = model(lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Tuple: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model.encode(lowercase ).latent_dist A__ = dist.sample(generator=lowercase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] A__ = sample[0, -1, -3:, -3:].flatten().cpu() A__ = torch.tensor(lowercase ) A__ = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(lowercase , lowercase , atol=lowercase )
68
0
from math import ceil def _snake_case( SCREAMING_SNAKE_CASE__ = 1_001 ) -> int: lowercase : List[Any] = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): lowercase : List[Any] = 2 * i + 1 lowercase : Tuple = 2 * i lowercase : List[str] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: lowercase : Any = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number""")
20
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCAmelCase__ = logging.getLogger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = label_idx def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: A__ = [] A__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 A__ = [] A__ = [] else: A__ = line.split(" " ) words.append(splits[0] ) if len(lowercase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(lowercase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: A__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(lowercase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a__ ( snake_case ): """simple docstring""" def __init__( self ) -> Union[str, Any]: '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a__ ( snake_case ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: for sentence in parse_incr(lowercase ): A__ = [] A__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(lowercase ) == len(lowercase ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = 0 for sentence in parse_incr(lowercase ): A__ = preds_list[example_id] A__ = "" for token in sentence: out += F'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(lowercase ) example_id += 1 def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
68
0
def UpperCamelCase_( lowerCamelCase_ = 100 ) -> int: _lowercase : int = set() _lowercase : str = 0 _lowercase : int = n + 1 # maximum limit for a in range(2 , lowerCamelCase_ ): for b in range(2 , lowerCamelCase_ ): _lowercase : Tuple = a**b # calculates the current power collect_powers.add(lowerCamelCase_ ) # adds the result to the set return len(lowerCamelCase_ ) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
21
import random class a__ : """simple docstring""" @staticmethod def UpperCamelCase ( lowercase ) -> tuple[list[int], list[int]]: '''simple docstring''' A__ = [ord(lowercase ) for i in text] A__ = [] A__ = [] for i in plain: A__ = random.randint(1 , 300 ) A__ = (i + k) * k cipher.append(lowercase ) key.append(lowercase ) return cipher, key @staticmethod def UpperCamelCase ( lowercase , lowercase ) -> str: '''simple docstring''' A__ = [] for i in range(len(lowercase ) ): A__ = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowercase ) ) return "".join(lowercase ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
68
0
'''simple docstring''' import warnings from ...utils import is_sklearn_available, requires_backends if is_sklearn_available(): from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef __SCREAMING_SNAKE_CASE :List[str] = ( '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate ''' '''library. You can have a look at this example script for pointers: ''' '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py''' ) def UpperCAmelCase_ ( __lowercase : Any , __lowercase : Tuple ) -> int: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) return (preds == labels).mean() def UpperCAmelCase_ ( __lowercase : int , __lowercase : str ) -> Optional[Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) _UpperCAmelCase = simple_accuracy(__lowercase , __lowercase ) _UpperCAmelCase = fa_score(y_true=__lowercase , y_pred=__lowercase ) return { "acc": acc, "f1": fa, "acc_and_f1": (acc + fa) / 2, } def UpperCAmelCase_ ( __lowercase : Optional[int] , __lowercase : List[str] ) -> List[Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) _UpperCAmelCase = pearsonr(__lowercase , __lowercase )[0] _UpperCAmelCase = spearmanr(__lowercase , __lowercase )[0] return { "pearson": pearson_corr, "spearmanr": spearman_corr, "corr": (pearson_corr + spearman_corr) / 2, } def UpperCAmelCase_ ( __lowercase : Optional[Any] , __lowercase : str , __lowercase : str ) -> Tuple: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) assert len(__lowercase ) == len(__lowercase ), f'Predictions and labels have mismatched lengths {len(__lowercase )} and {len(__lowercase )}' if task_name == "cola": return {"mcc": matthews_corrcoef(__lowercase , __lowercase )} elif task_name == "sst-2": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "mrpc": return acc_and_fa(__lowercase , __lowercase ) elif task_name == "sts-b": return pearson_and_spearman(__lowercase , __lowercase ) elif task_name == "qqp": return acc_and_fa(__lowercase , __lowercase ) elif task_name == "mnli": return {"mnli/acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "mnli-mm": return {"mnli-mm/acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "qnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "rte": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "wnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} elif task_name == "hans": return {"acc": simple_accuracy(__lowercase , __lowercase )} else: raise KeyError(__lowercase ) def UpperCAmelCase_ ( __lowercase : List[Any] , __lowercase : Dict , __lowercase : str ) -> Union[str, Any]: '''simple docstring''' warnings.warn(__lowercase , __lowercase ) requires_backends(__lowercase , "sklearn" ) if len(__lowercase ) != len(__lowercase ): raise ValueError(f'Predictions and labels have mismatched lengths {len(__lowercase )} and {len(__lowercase )}' ) if task_name == "xnli": return {"acc": simple_accuracy(__lowercase , __lowercase )} else: raise KeyError(__lowercase )
22
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ = 2 while i * i <= n: A__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
68
0
'''simple docstring''' import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class SCREAMING_SNAKE_CASE( A__ , unittest.TestCase ): """simple docstring""" lowerCamelCase__ = MobileBertTokenizer lowerCamelCase__ = MobileBertTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True lowerCamelCase__ = filter_non_english lowerCamelCase__ = """google/mobilebert-uncased""" def A ( self : Any ) -> int: super().setUp() UpperCAmelCase : str = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] UpperCAmelCase : Dict = 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] ) ) UpperCAmelCase : List[Any] = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def A ( self : Optional[Any] , __snake_case : Union[str, Any] ) -> Optional[Any]: UpperCAmelCase : Optional[Any] = '''UNwant\u00E9d,running''' UpperCAmelCase : int = '''unwanted, running''' return input_text, output_text def A ( self : Optional[Any] ) -> Dict: UpperCAmelCase : List[str] = self.tokenizer_class(self.vocab_file ) UpperCAmelCase : Dict = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(__snake_case , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [9, 6, 7, 12, 10, 11] ) def A ( self : Any ) -> int: if not self.test_rust_tokenizer: return UpperCAmelCase : Optional[int] = self.get_tokenizer() UpperCAmelCase : Any = self.get_rust_tokenizer() UpperCAmelCase : int = '''UNwant\u00E9d,running''' UpperCAmelCase : Dict = tokenizer.tokenize(__snake_case ) UpperCAmelCase : Optional[int] = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Optional[int] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : int = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : int = self.get_rust_tokenizer() UpperCAmelCase : int = tokenizer.encode(__snake_case ) UpperCAmelCase : str = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) # With lower casing UpperCAmelCase : Dict = self.get_tokenizer(do_lower_case=__snake_case ) UpperCAmelCase : int = self.get_rust_tokenizer(do_lower_case=__snake_case ) UpperCAmelCase : Dict = '''UNwant\u00E9d,running''' UpperCAmelCase : int = tokenizer.tokenize(__snake_case ) UpperCAmelCase : List[Any] = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : int = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : List[Any] = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Optional[Any] = self.get_rust_tokenizer() UpperCAmelCase : Union[str, Any] = tokenizer.encode(__snake_case ) UpperCAmelCase : Union[str, Any] = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) def A ( self : List[str] ) -> List[str]: UpperCAmelCase : str = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def A ( self : Optional[int] ) -> Any: UpperCAmelCase : Tuple = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : Optional[int] ) -> int: UpperCAmelCase : Optional[Any] = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def A ( self : Union[str, Any] ) -> Optional[Any]: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : str ) -> Optional[int]: UpperCAmelCase : Any = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def A ( self : Union[str, Any] ) -> Optional[int]: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Tuple ) -> Any: UpperCAmelCase : Dict = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Optional[int] ) -> Union[str, Any]: UpperCAmelCase : List[str] = BasicTokenizer(do_lower_case=__snake_case , strip_accents=__snake_case ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def A ( self : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase : Tuple = BasicTokenizer(do_lower_case=__snake_case , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def A ( self : List[Any] ) -> Dict: UpperCAmelCase : List[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] UpperCAmelCase : Tuple = {} for i, token in enumerate(__snake_case ): UpperCAmelCase : List[str] = i UpperCAmelCase : str = WordpieceTokenizer(vocab=__snake_case , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) def A ( self : Union[str, Any] ) -> Tuple: self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def A ( self : Union[str, Any] ) -> Any: self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def A ( self : Optional[int] ) -> Tuple: self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) def A ( self : Union[str, Any] ) -> List[str]: UpperCAmelCase : Dict = self.get_tokenizer() UpperCAmelCase : int = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__snake_case ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) self.assertListEqual( [rust_tokenizer.tokenize(__snake_case ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] ) @slow def A ( self : Union[str, Any] ) -> Optional[int]: UpperCAmelCase : Optional[Any] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' ) UpperCAmelCase : Dict = tokenizer.encode('''sequence builders''' , add_special_tokens=__snake_case ) UpperCAmelCase : List[str] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__snake_case ) UpperCAmelCase : Any = tokenizer.build_inputs_with_special_tokens(__snake_case ) UpperCAmelCase : Tuple = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) assert encoded_sentence == [101] + text + [102] assert encoded_pair == [101] + text + [102] + text_a + [102] def A ( self : Optional[Any] ) -> Any: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase : Dict = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : str = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" UpperCAmelCase : Optional[int] = tokenizer_r.encode_plus( __snake_case , return_attention_mask=__snake_case , return_token_type_ids=__snake_case , return_offsets_mapping=__snake_case , add_special_tokens=__snake_case , ) UpperCAmelCase : List[Any] = tokenizer_r.do_lower_case if hasattr(__snake_case , '''do_lower_case''' ) else False UpperCAmelCase : str = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''A'''), ((1, 2), ''','''), ((3, 5), '''na'''), ((5, 6), '''##ï'''), ((6, 8), '''##ve'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''Allen'''), ((21, 23), '''##NL'''), ((23, 24), '''##P'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), '''a'''), ((1, 2), ''','''), ((3, 8), '''naive'''), ((9, 15), tokenizer_r.mask_token), ((16, 21), '''allen'''), ((21, 23), '''##nl'''), ((23, 24), '''##p'''), ((25, 33), '''sentence'''), ((33, 34), '''.'''), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] ) def A ( self : Optional[int] ) -> str: UpperCAmelCase : str = ['''的''', '''人''', '''有'''] UpperCAmelCase : List[Any] = ''''''.join(__snake_case ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase : Union[str, Any] = True UpperCAmelCase : List[str] = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : int = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : List[Any] = tokenizer_p.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Tuple = tokenizer_r.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Any = tokenizer_r.convert_ids_to_tokens(__snake_case ) UpperCAmelCase : Optional[int] = tokenizer_p.convert_ids_to_tokens(__snake_case ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__snake_case , __snake_case ) self.assertListEqual(__snake_case , __snake_case ) UpperCAmelCase : Union[str, Any] = False UpperCAmelCase : int = self.rust_tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : int = self.tokenizer_class.from_pretrained(__snake_case , **__snake_case ) UpperCAmelCase : List[Any] = tokenizer_r.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : Tuple = tokenizer_p.encode(__snake_case , add_special_tokens=__snake_case ) UpperCAmelCase : List[str] = tokenizer_r.convert_ids_to_tokens(__snake_case ) UpperCAmelCase : Optional[int] = tokenizer_p.convert_ids_to_tokens(__snake_case ) # it is expected that only the first Chinese character is not preceded by "##". UpperCAmelCase : Optional[Any] = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(__snake_case ) ] self.assertListEqual(__snake_case , __snake_case ) self.assertListEqual(__snake_case , __snake_case )
23
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: lowerCAmelCase__ = json.load(f) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return FSMTTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = F'facebook/wmt19-{pair}' A__ = self.get_tokenizer(lowercase ) A__ = self.get_model(lowercase ) A__ = bleu_data[pair]["src"] A__ = bleu_data[pair]["tgt"] A__ = tokenizer(lowercase , return_tensors="pt" , truncation=lowercase , padding="longest" ).to(lowercase ) A__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) A__ = tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) A__ = calculate_bleu(lowercase , lowercase ) print(lowercase ) self.assertGreaterEqual(scores["bleu"] , lowercase )
68
0
import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() snake_case_ = logging.get_logger(__name__) snake_case_ = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'encoder.layer_norm_for_extract': 'layer_norm_for_extract', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'label_embs_concat': 'label_embeddings_concat', 'mask_emb': 'masked_spec_embed', 'spk_proj': 'speaker_proj', } snake_case_ = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'label_embeddings_concat', 'speaker_proj', 'layer_norm_for_extract', ] def lowerCamelCase__ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : List[Any] , snake_case_ : List[str] , snake_case_ : str ) -> List[str]: for attribute in key.split('''.''' ): __snake_case = getattr(snake_case_ , snake_case_ ) if weight_type is not None: __snake_case = getattr(snake_case_ , snake_case_ ).shape else: __snake_case = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": __snake_case = value elif weight_type == "weight_g": __snake_case = value elif weight_type == "weight_v": __snake_case = value elif weight_type == "bias": __snake_case = value else: __snake_case = value logger.info(f"""{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.""" ) def lowerCamelCase__ ( snake_case_ : Any , snake_case_ : List[str] ) -> List[str]: __snake_case = [] __snake_case = fairseq_model.state_dict() __snake_case = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __snake_case = False if "conv_layers" in name: load_conv_layer( snake_case_ , snake_case_ , snake_case_ , snake_case_ , hf_model.config.feat_extract_norm == '''group''' , ) __snake_case = True else: for key, mapped_key in MAPPING.items(): __snake_case = '''unispeech_sat.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('''.''' )[:-1] ) != key): # special case since naming is very similar continue __snake_case = True if "*" in mapped_key: __snake_case = name.split(snake_case_ )[0].split('''.''' )[-2] __snake_case = mapped_key.replace('''*''' , snake_case_ ) if "weight_g" in name: __snake_case = '''weight_g''' elif "weight_v" in name: __snake_case = '''weight_v''' elif "bias" in name: __snake_case = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __snake_case = '''weight''' else: __snake_case = None set_recursively(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) def lowerCamelCase__ ( snake_case_ : str , snake_case_ : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Tuple , snake_case_ : Optional[int] ) -> List[Any]: __snake_case = full_name.split('''conv_layers.''' )[-1] __snake_case = name.split('''.''' ) __snake_case = int(items[0] ) __snake_case = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) __snake_case = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) __snake_case = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) __snake_case = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) __snake_case = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) @torch.no_grad() def lowerCamelCase__ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] , snake_case_ : int=None , snake_case_ : str=None , snake_case_ : Optional[int]=True ) -> int: if config_path is not None: __snake_case = UniSpeechSatConfig.from_pretrained(snake_case_ ) else: __snake_case = UniSpeechSatConfig() __snake_case = '''''' if is_finetuned: __snake_case = UniSpeechSatForCTC(snake_case_ ) else: __snake_case = UniSpeechSatForPreTraining(snake_case_ ) __snake_case , __snake_case , __snake_case = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) __snake_case = model[0].eval() recursively_load_weights(snake_case_ , snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) if __name__ == "__main__": snake_case_ = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) snake_case_ = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
24
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> list: '''simple docstring''' A__ = int(SCREAMING_SNAKE_CASE_ ) if n_element < 1: A__ = ValueError("a should be a positive number" ) raise my_error A__ = [1] A__ , A__ , A__ = (0, 0, 0) A__ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowerCAmelCase__ = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") lowerCAmelCase__ = hamming(int(n)) print("""-----------------------------------------------------""") print(f"""The list with nth numbers is: {hamming_numbers}""") print("""-----------------------------------------------------""")
68
0
"""simple docstring""" from typing import List, Union import numpy as np from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING UpperCAmelCase__ : List[str] = logging.get_logger(__name__) @add_end_docstrings(a__ ) class lowerCAmelCase_ (a__ ): """simple docstring""" def __init__(self , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , """vision""" ) self.check_model_type(SCREAMING_SNAKE_CASE__ ) def __call__(self , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , **SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" return {}, {}, {} def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = load_image(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = image.size SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) return model_inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model(**SCREAMING_SNAKE_CASE__ ) return model_outputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = model_outputs.predicted_depth SCREAMING_SNAKE_CASE__ : Optional[int] = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode="""bicubic""" , align_corners=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = prediction.squeeze().cpu().numpy() SCREAMING_SNAKE_CASE__ : Any = (output * 2_55 / np.max(SCREAMING_SNAKE_CASE__ )).astype("""uint8""" ) SCREAMING_SNAKE_CASE__ : List[str] = Image.fromarray(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = {} SCREAMING_SNAKE_CASE__ : Any = predicted_depth SCREAMING_SNAKE_CASE__ : Dict = depth return output_dict
25
import copy import random from transformers import CLIPTokenizer class a__ ( snake_case ): """simple docstring""" def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' super().__init__(*lowercase , **lowercase ) A__ = {} def UpperCamelCase ( self , lowercase , *lowercase , **lowercase ) -> str: '''simple docstring''' A__ = super().add_tokens(lowercase , *lowercase , **lowercase ) if num_added_tokens == 0: raise ValueError( F'The tokenizer already contains the token {placeholder_token}. Please pass a different' " `placeholder_token` that is not already in the tokenizer." ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=1 , **lowercase ) -> Any: '''simple docstring''' A__ = [] if num_vec_per_token == 1: self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) else: A__ = [] for i in range(lowercase ): A__ = placeholder_token + F'_{i}' self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'The tokenizer already has placeholder token {token} that can get confused with' F' {placeholder_token}keep placeholder tokens independent' ) A__ = output def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=1.0 ) -> List[Any]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = [] for i in range(len(lowercase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=lowercase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: A__ = self.token_map[placeholder_token] A__ = tokens[: 1 + int(len(lowercase ) * prop_tokens_to_load )] if vector_shuffle: A__ = copy.copy(lowercase ) random.shuffle(lowercase ) A__ = text.replace(lowercase , " ".join(lowercase ) ) return text def __call__( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> str: '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> List[str]: '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , )
68
0
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( UpperCamelCase__ ): _a = ["image_processor", "tokenizer"] _a = "BlipImageProcessor" _a = ("BertTokenizer", "BertTokenizerFast") def __init__( self , _a , _a ) -> int: _A : Union[str, Any] = False super().__init__(_a , _a ) _A : int = self.image_processor def __call__( self , _a = None , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ) -> BatchEncoding: if images is None and text is None: raise ValueError("""You have to specify either images or text.""" ) # Get only text if images is None: _A : Dict = self.tokenizer _A : Optional[int] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) return text_encoding # add pixel_values _A : Any = self.image_processor(_a , return_tensors=_a ) if text is not None: _A : List[str] = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_token_type_ids=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) else: _A : Dict = None if text_encoding is not None: encoding_image_processor.update(_a ) return encoding_image_processor def a__ ( self , *_a , **_a ) -> int: return self.tokenizer.batch_decode(*_a , **_a ) def a__ ( self , *_a , **_a ) -> Optional[int]: return self.tokenizer.decode(*_a , **_a ) @property def a__ ( self ) -> int: _A : Dict = self.tokenizer.model_input_names _A : Tuple = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
26
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Tuple: '''simple docstring''' if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A__ = [[w, v]] if not self.graph.get(lowercase ): A__ = [] def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Any: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self , lowercase=-2 ) -> str: '''simple docstring''' A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s A__ = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> int: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin class a__ : """simple docstring""" def __init__( self ) -> int: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A__ = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A__ = [[w, u]] def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> str: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Dict: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> List[Any]: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin
68
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) __lowercase : Union[str, Any] = { 'configuration_swiftformer': [ 'SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwiftFormerConfig', 'SwiftFormerOnnxConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase : Tuple = [ 'SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwiftFormerForImageClassification', 'SwiftFormerModel', 'SwiftFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swiftformer import ( SWIFTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, SwiftFormerConfig, SwiftFormerOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swiftformer import ( SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, SwiftFormerForImageClassification, SwiftFormerModel, SwiftFormerPreTrainedModel, ) else: import sys __lowercase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
0
'''simple docstring''' def __lowerCamelCase ( A__ ) -> bool: """simple docstring""" if not isinstance(A__ , A__ ): UpperCamelCase = F"""Input value of [number={number}] must be an integer""" raise TypeError(A__ ) if number < 0: return False UpperCamelCase = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
28
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) __UpperCAmelCase = {'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ['ViTFeatureExtractor'] __UpperCAmelCase = ['ViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'VIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTForImageClassification', 'ViTForMaskedImageModeling', 'ViTModel', 'ViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'TFViTForImageClassification', 'TFViTModel', 'TFViTPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ 'FlaxViTForImageClassification', 'FlaxViTModel', 'FlaxViTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
29
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
0
import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() __a = logging.get_logger(__name__) def a ( snake_case__: Optional[Any] ): '''simple docstring''' lowercase_ = MobileNetVaConfig(layer_norm_eps=0.0_0_1 ) if "_quant" in model_name: raise ValueError('''Quantized models are not supported.''' ) lowercase_ = re.match(r'''^mobilenet_v1_([^_]*)_([^_]*)$''' , snake_case__ ) if matches: lowercase_ = float(matches[1] ) lowercase_ = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". lowercase_ = 1_001 lowercase_ = '''imagenet-1k-id2label.json''' lowercase_ = '''huggingface/label-files''' lowercase_ = json.load(open(hf_hub_download(snake_case__ , snake_case__ , repo_type='''dataset''' ) , '''r''' ) ) lowercase_ = {int(snake_case__ ) + 1: v for k, v in idalabel.items()} lowercase_ = '''background''' lowercase_ = idalabel lowercase_ = {v: k for k, v in idalabel.items()} return config def a ( ): '''simple docstring''' lowercase_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase_ = Image.open(requests.get(snake_case__ , stream=snake_case__ ).raw ) return im @torch.no_grad() def a ( snake_case__: Optional[int] , snake_case__: int , snake_case__: Dict , snake_case__: Optional[Any]=False ): '''simple docstring''' lowercase_ = get_mobilenet_va_config(snake_case__ ) # Load 🤗 model lowercase_ = MobileNetVaForImageClassification(snake_case__ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(snake_case__ , snake_case__ , snake_case__ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor lowercase_ = MobileNetVaImageProcessor( crop_size={'''width''': config.image_size, '''height''': config.image_size} , size={'''shortest_edge''': config.image_size + 32} , ) lowercase_ = image_processor(images=prepare_img() , return_tensors='''pt''' ) lowercase_ = model(**snake_case__ ) lowercase_ = outputs.logits assert logits.shape == (1, 1_001) if model_name == "mobilenet_v1_1.0_224": lowercase_ = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ) elif model_name == "mobilenet_v1_0.75_192": lowercase_ = torch.tensor([-3.9_4_4_0, -2.3_1_4_1, -0.3_3_3_3] ) else: lowercase_ = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , snake_case__ , atol=1e-4 ) Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(snake_case__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(snake_case__ ) if push_to_hub: print('''Pushing to the hub...''' ) lowercase_ = '''google/''' + model_name image_processor.push_to_hub(snake_case__ ) model.push_to_hub(snake_case__ ) if __name__ == "__main__": __a = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='mobilenet_v1_1.0_224', type=str, help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.', ) parser.add_argument( '--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).' ) parser.add_argument( '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) __a = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
30
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: A__ = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE_ ) A__ = num - key if num < 0: A__ = num + len(string.ascii_uppercase ) A__ = translated + string.ascii_uppercase[num] else: A__ = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = input("Encrypted message: " ) A__ = message.upper() decrypt(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
0
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) __SCREAMING_SNAKE_CASE : Optional[int] = logging.getLogger(__name__) if __name__ == "__main__": __SCREAMING_SNAKE_CASE : Tuple = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) __SCREAMING_SNAKE_CASE : List[Any] = parser.parse_args() logger.info(F'Loading data from {args.data_file}') with open(args.data_file, """rb""") as fp: __SCREAMING_SNAKE_CASE : Optional[Any] = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") __SCREAMING_SNAKE_CASE : int = Counter() for tk_ids in data: counter.update(tk_ids) __SCREAMING_SNAKE_CASE : Any = [0] * args.vocab_size for k, v in counter.items(): __SCREAMING_SNAKE_CASE : Tuple = v logger.info(F'Dump to {args.token_counts_dump}') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
31
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = SpeechTaTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(lowercase ) A__ = AddedToken("<mask>" , lstrip=lowercase , rstrip=lowercase ) A__ = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = "this is a test" A__ = "this is a test" return input_text, output_text def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=20 , lowercase=5 ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.get_input_output_texts(lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) return text, ids def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = "<pad>" A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(lowercase ) , 81 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] A__ = tokenizer.add_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size + len(lowercase ) ) A__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) A__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A__ = tokenizer.add_special_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size_a + len(lowercase ) ) A__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(lowercase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) A__ = tokenizer.convert_tokens_to_ids(lowercase ) # fmt: off self.assertListEqual(lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off A__ = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=lowercase , )
68
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( __A : Union[str, Any] , __A : Any , __A : Dict ) -> Optional[Any]: """simple docstring""" return params[F"""{prefix}/{prefix}/relpos_bias/rel_embedding"""][:, i, :] def SCREAMING_SNAKE_CASE_ ( __A : List[str] , __A : Dict , __A : Tuple , __A : Tuple="attention" ) -> str: """simple docstring""" a_ : List[Any] = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/key/kernel"""][:, i, :, :] ) a_ : int = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) a_ : Optional[int] = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/out/kernel"""][:, i, :, :] ) a_ : Dict = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) a_ : Any = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/query/kernel"""][:, i, :, :] ) a_ : Any = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) a_ : List[str] = np.ascontiguousarray(params[F"""{prefix}/{prefix}/{layer_name}/value/kernel"""][:, i, :, :] ) a_ : Optional[int] = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def SCREAMING_SNAKE_CASE_ ( __A : List[str] , __A : Optional[int] , __A : str , __A : List[Any]=False ) -> int: """simple docstring""" if split_mlp_wi: a_ : List[str] = params[F"""{prefix}/{prefix}/mlp/wi_0/kernel"""][:, i, :] a_ : Union[str, Any] = params[F"""{prefix}/{prefix}/mlp/wi_1/kernel"""][:, i, :] a_ : Any = (wi_a, wi_a) else: a_ : List[str] = params[F"""{prefix}/{prefix}/mlp/wi/kernel"""][:, i, :] a_ : Union[str, Any] = params[F"""{prefix}/{prefix}/mlp/wo/kernel"""][:, i, :] return wi, wo def SCREAMING_SNAKE_CASE_ ( __A : Dict , __A : List[Any] , __A : str , __A : int ) -> Tuple: """simple docstring""" return params[F"""{prefix}/{prefix}/{layer_name}/scale"""][:, i] def SCREAMING_SNAKE_CASE_ ( __A : dict , *, __A : int , __A : bool , __A : bool = False ) -> Union[str, Any]: """simple docstring""" a_ : Dict = traverse_util.flatten_dict(variables['target'] ) a_ : List[str] = {'/'.join(__A ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi a_ : Optional[int] = 'encoder/encoder/mlp/wi_0/kernel' in old print('Split MLP:' , __A ) a_ : List[str] = collections.OrderedDict() # Shared embeddings. a_ : List[str] = old['token_embedder/embedding'] # Encoder. for i in range(__A ): # Block i, layer 0 (Self Attention). a_ : Tuple = tax_layer_norm_lookup(__A , __A , 'encoder' , 'pre_attention_layer_norm' ) a_ , a_ , a_ , a_ : List[Any] = tax_attention_lookup(__A , __A , 'encoder' , 'attention' ) a_ : Optional[int] = layer_norm a_ : Tuple = k.T a_ : Tuple = o.T a_ : Optional[Any] = q.T a_ : List[str] = v.T # Block i, layer 1 (MLP). a_ : List[Any] = tax_layer_norm_lookup(__A , __A , 'encoder' , 'pre_mlp_layer_norm' ) a_ , a_ : Any = tax_mlp_lookup(__A , __A , 'encoder' , __A ) a_ : Union[str, Any] = layer_norm if split_mlp_wi: a_ : Union[str, Any] = wi[0].T a_ : int = wi[1].T else: a_ : Tuple = wi.T a_ : int = wo.T if scalable_attention: # convert the rel_embedding of each layer a_ : Dict = tax_relpos_bias_lookup( __A , __A , 'encoder' ).T a_ : Optional[Any] = old['encoder/encoder_norm/scale'] if not scalable_attention: a_ : int = tax_relpos_bias_lookup( __A , 0 , 'encoder' ).T a_ : str = tax_relpos_bias_lookup( __A , 0 , 'decoder' ).T if not is_encoder_only: # Decoder. for i in range(__A ): # Block i, layer 0 (Self Attention). a_ : str = tax_layer_norm_lookup(__A , __A , 'decoder' , 'pre_self_attention_layer_norm' ) a_ , a_ , a_ , a_ : Tuple = tax_attention_lookup(__A , __A , 'decoder' , 'self_attention' ) a_ : int = layer_norm a_ : Optional[int] = k.T a_ : List[str] = o.T a_ : Any = q.T a_ : int = v.T # Block i, layer 1 (Cross Attention). a_ : int = tax_layer_norm_lookup(__A , __A , 'decoder' , 'pre_cross_attention_layer_norm' ) a_ , a_ , a_ , a_ : str = tax_attention_lookup(__A , __A , 'decoder' , 'encoder_decoder_attention' ) a_ : List[str] = layer_norm a_ : str = k.T a_ : Optional[Any] = o.T a_ : Tuple = q.T a_ : int = v.T # Block i, layer 2 (MLP). a_ : Any = tax_layer_norm_lookup(__A , __A , 'decoder' , 'pre_mlp_layer_norm' ) a_ , a_ : int = tax_mlp_lookup(__A , __A , 'decoder' , __A ) a_ : int = layer_norm if split_mlp_wi: a_ : List[Any] = wi[0].T a_ : List[str] = wi[1].T else: a_ : int = wi.T a_ : List[str] = wo.T if scalable_attention: # convert the rel_embedding of each layer a_ : List[str] = tax_relpos_bias_lookup(__A , __A , 'decoder' ).T a_ : Dict = old['decoder/decoder_norm/scale'] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: a_ : Any = old['decoder/logits_dense/kernel'].T return new def SCREAMING_SNAKE_CASE_ ( __A : List[Any] , __A : bool ) -> List[Any]: """simple docstring""" a_ : Union[str, Any] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: a_ : Dict = state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: a_ : int = state_dict['shared.weight'] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('Using shared word embeddings as lm_head.' ) a_ : Any = state_dict['shared.weight'] return state_dict def SCREAMING_SNAKE_CASE_ ( __A : Dict , __A : int , __A : int , __A : List[str] , __A : int ) -> int: """simple docstring""" a_ : str = checkpoints.load_tax_checkpoint(__A ) a_ : Optional[Any] = convert_tax_to_pytorch( __A , num_layers=config.num_layers , is_encoder_only=__A , scalable_attention=__A ) a_ : Dict = make_state_dict(__A , __A ) model.load_state_dict(__A , strict=__A ) def SCREAMING_SNAKE_CASE_ ( __A : str , __A : Optional[Any] , __A : str , __A : bool = False , __A : bool = False , ) -> Optional[Any]: """simple docstring""" a_ : Dict = MTaConfig.from_json_file(__A ) print(F"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: a_ : Tuple = UMTaEncoderModel(__A ) else: a_ : Union[str, Any] = UMTaForConditionalGeneration(__A ) # Load weights from tf checkpoint load_tax_weights_in_ta(__A , __A , __A , __A , __A ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(__A ) # Verify that we can load the checkpoint. model.from_pretrained(__A ) print('Done' ) if __name__ == "__main__": UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.') # Required parameters parser.add_argument( '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False ) parser.add_argument( '--scalable_attention', action='store_true', help='Whether the model uses scaled attention (umt5 model)', default=False, ) UpperCAmelCase_ : List[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
32
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> List[str]: '''simple docstring''' A__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } A__ = F'{src_lang}-{tgt_lang}' A__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) # make sure we are under the root of the project lowerCAmelCase__ = Path(__file__).resolve().parent.parent.parent lowerCAmelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = model_name.split("""-""") lowerCAmelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
68
0
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import OPTConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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 GPTaTokenizer, TFOPTForCausalLM, TFOPTModel def lowercase ( __snake_case : Dict , __snake_case : str , __snake_case : Dict=None , __snake_case : Dict=None ): if attention_mask is None: lowercase_ : List[Any] = tf.cast(tf.math.not_equal(__snake_case , config.pad_token_id ) , tf.inta ) return {"input_ids": input_ids, "attention_mask": attention_mask} @require_tf class _UpperCAmelCase : SCREAMING_SNAKE_CASE_ : Optional[int] = OPTConfig SCREAMING_SNAKE_CASE_ : List[str] = {} SCREAMING_SNAKE_CASE_ : Dict = "gelu" def __init__( self : Any , A : List[str] , A : Dict=13 , A : Optional[Any]=7 , A : Dict=True , A : Union[str, Any]=False , A : List[Any]=99 , A : List[str]=16 , A : str=2 , A : List[Any]=4 , A : Union[str, Any]=4 , A : Optional[int]="gelu" , A : Optional[int]=0.1 , A : List[str]=0.1 , A : Optional[Any]=20 , A : Optional[Any]=2 , A : str=1 , A : Union[str, Any]=0 , A : Optional[Any]=16 , A : List[Any]=16 , ) -> Union[str, Any]: lowercase_ : Dict = parent lowercase_ : Dict = batch_size lowercase_ : str = seq_length lowercase_ : Union[str, Any] = is_training lowercase_ : Union[str, Any] = use_labels lowercase_ : List[str] = vocab_size lowercase_ : Union[str, Any] = hidden_size lowercase_ : Optional[int] = num_hidden_layers lowercase_ : List[str] = num_attention_heads lowercase_ : str = intermediate_size lowercase_ : Dict = hidden_act lowercase_ : str = hidden_dropout_prob lowercase_ : Dict = attention_probs_dropout_prob lowercase_ : Dict = max_position_embeddings lowercase_ : int = eos_token_id lowercase_ : Any = pad_token_id lowercase_ : Optional[Any] = bos_token_id lowercase_ : Tuple = embed_dim lowercase_ : Optional[Any] = word_embed_proj_dim lowercase_ : Tuple = False def A ( self : Any ) -> List[str]: lowercase_ : int = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase_ : Tuple = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase_ : int = tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase_ : int = self.config_cls( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , 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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , embed_dim=self.embed_dim , word_embed_proj_dim=self.word_embed_proj_dim , is_encoder_decoder=A , **self.config_updates , ) lowercase_ : Tuple = prepare_opt_inputs_dict(A , A ) return config, inputs_dict def A ( self : int , A : Union[str, Any] , A : Tuple ) -> Optional[Any]: lowercase_ : Optional[Any] = TFOPTModel(config=A ) lowercase_ : int = inputs_dict['''input_ids'''] lowercase_ : Dict = input_ids[:1, :] lowercase_ : Tuple = inputs_dict['''attention_mask'''][:1, :] lowercase_ : Optional[int] = 1 # first forward pass lowercase_ : Optional[Any] = model(A , attention_mask=A , use_cache=A ) lowercase_ , lowercase_ : Optional[int] = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowercase_ : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase_ : Union[str, Any] = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowercase_ : str = tf.concat([input_ids, next_tokens] , axis=-1 ) lowercase_ : Tuple = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowercase_ : List[str] = model(A , attention_mask=A )[0] lowercase_ : Any = 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 lowercase_ : Dict = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowercase_ : Optional[Any] = output_from_no_past[:, -3:, random_slice_idx] lowercase_ : Dict = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(A , A , rtol=1e-3 ) @require_tf class _UpperCAmelCase ( _A , _A , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : int = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else () SCREAMING_SNAKE_CASE_ : List[Any] = (TFOPTForCausalLM,) if is_tf_available() else () SCREAMING_SNAKE_CASE_ : Dict = ( {"feature-extraction": TFOPTModel, "text-generation": TFOPTForCausalLM} if is_tf_available() else {} ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = False SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : List[str] = False SCREAMING_SNAKE_CASE_ : Dict = 10 def A ( self : Union[str, Any] ) -> str: lowercase_ : Dict = TFOPTModelTester(self ) lowercase_ : Dict = ConfigTester(self , config_class=A ) def A ( self : List[str] ) -> str: self.config_tester.run_common_tests() def A ( self : Union[str, Any] ) -> str: lowercase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) def A ( self : str ) -> Optional[Any]: lowercase_ , lowercase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() def _get_word_embedding_weight(A : List[str] , A : Any ): if hasattr(A , '''weight''' ): return embedding_layer.weight else: # Here we build the word embeddings weights if not exists. # And then we retry to get the attribute once built. model.build() if hasattr(A , '''weight''' ): return embedding_layer.weight else: return None for model_class in self.all_model_classes: for size in [config.vocab_size - 10, config.vocab_size + 10]: # build the embeddings lowercase_ : str = model_class(config=A ) lowercase_ : Any = _get_word_embedding_weight(A , model.get_input_embeddings() ) lowercase_ : List[Any] = _get_word_embedding_weight(A , model.get_output_embeddings() ) # reshape the embeddings model.resize_token_embeddings(A ) lowercase_ : Optional[Any] = _get_word_embedding_weight(A , model.get_input_embeddings() ) lowercase_ : Optional[int] = _get_word_embedding_weight(A , model.get_output_embeddings() ) # check that the resized embeddings size matches the desired size. lowercase_ : List[Any] = size if size is not None else config.vocab_size self.assertEqual(new_input_embeddings.shape[0] , A ) # check that weights remain the same after resizing lowercase_ : Optional[int] = True for pa, pa in zip(old_input_embeddings.value() , new_input_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowercase_ : Any = False self.assertTrue(A ) if old_output_embeddings is not None and new_output_embeddings is not None: self.assertEqual(new_output_embeddings.shape[0] , A ) lowercase_ : Any = True for pa, pa in zip(old_output_embeddings.value() , new_output_embeddings.value() ): if tf.math.reduce_sum(tf.math.abs(pa - pa ) ) > 0: lowercase_ : Dict = False self.assertTrue(A ) def lowercase ( __snake_case : int ): return tf.constant(__snake_case , dtype=tf.intaa ) @require_tf class _UpperCAmelCase ( unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Optional[Any] = 99 def A ( self : Union[str, Any] ) -> str: lowercase_ : Union[str, Any] = tf.ones((4, 1) , dtype=tf.intaa ) * 2 lowercase_ : Optional[Any] = tf.concat([ids_tensor((4, 6) , self.vocab_size - 3 ) + 3, eos_column_vector] , axis=1 ) lowercase_ : Dict = input_ids.shape[0] lowercase_ : Optional[int] = OPTConfig( vocab_size=self.vocab_size , hidden_size=24 , num_hidden_layers=2 , num_attention_heads=2 , ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size @require_sentencepiece @require_tf class _UpperCAmelCase ( unittest.TestCase ): @slow def A ( self : Any ) -> Union[str, Any]: lowercase_ : int = TFOPTModel.from_pretrained('''facebook/opt-350m''' ) lowercase_ : List[str] = _long_tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] ) lowercase_ : Dict = tf.not_equal(A , model.config.pad_token_id ) with tf.GradientTape(): lowercase_ : str = model(input_ids=A , attention_mask=A ).last_hidden_state lowercase_ : Union[str, Any] = (1, 11, 5_12) self.assertEqual(output.shape , A ) lowercase_ : Union[str, Any] = tf.constant( [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]] ) self.assertTrue(np.allclose(output[:, :3, :3] , A , atol=4e-3 ) ) lowercase_ : Dict = tf.function(A , jit_compile=A ) lowercase_ : Union[str, Any] = xla_generate(A , A )[0] self.assertTrue(np.allclose(output[:, :3, :3] , A , atol=4e-2 ) ) @require_tf @slow class _UpperCAmelCase ( unittest.TestCase ): def A ( self : List[str] ) -> Any: super().setUp() lowercase_ : Tuple = '''facebook/opt-350m''' def A ( self : Any ) -> Union[str, Any]: lowercase_ : Optional[int] = TFOPTForCausalLM.from_pretrained(self.path_model ) lowercase_ : str = GPTaTokenizer.from_pretrained(self.path_model ) lowercase_ : Any = [ '''Today is a beautiful day and I want to''', '''In the city of''', '''Paris is the capital of France and''', '''Computers and mobile phones have taken''', ] # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False lowercase_ : str = tokenizer(A , return_tensors='''tf''' , padding=A , add_special_tokens=A ) lowercase_ : str = tf.math.reduce_mean(model(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) lowercase_ : Any = tf.constant( [ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670], [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822], [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703], [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477], ] ) self.assertTrue(np.allclose(A , A , atol=1e-4 ) ) lowercase_ : str = tf.function(A , jit_compile=A ) lowercase_ : Dict = tf.math.reduce_mean(xla_generate(inputs.input_ids , attention_mask=inputs.attention_mask )[0] , axis=-1 ) self.assertTrue(np.allclose(A , A , atol=1e-4 ) ) @require_tf @slow class _UpperCAmelCase ( unittest.TestCase ): @property def A ( self : Optional[int] ) -> Any: return [ "Today is a beautiful day and I want", "In the city of", "Paris is the capital of France and", "Computers and mobile phones have taken", ] def A ( self : Tuple ) -> Optional[Any]: lowercase_ : str = '''facebook/opt-125m''' lowercase_ : int = [ '''Today is a beautiful day and I want to''', '''In the city of New York, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] lowercase_ : Tuple = [] lowercase_ : Optional[int] = GPTaTokenizer.from_pretrained(A ) lowercase_ : Any = TFOPTForCausalLM.from_pretrained(A ) for prompt in self.prompts: lowercase_ : int = tokenizer(A , return_tensors='''tf''' ).input_ids lowercase_ : Any = model.generate(A , max_length=10 ) lowercase_ : List[Any] = tokenizer.batch_decode(A , skip_special_tokens=A ) predicted_outputs += generated_string self.assertListEqual(A , A ) def A ( self : Optional[Any] ) -> Union[str, Any]: lowercase_ : int = '''facebook/opt-350m''' lowercase_ : List[str] = GPTaTokenizer.from_pretrained(A ) lowercase_ : Tuple = TFOPTForCausalLM.from_pretrained(A ) lowercase_ : Any = '''left''' # use different length sentences to test batching lowercase_ : Union[str, Any] = [ '''Hello, my dog is a little''', '''Today, I''', ] lowercase_ : List[str] = tokenizer(A , return_tensors='''tf''' , padding=A ) lowercase_ : List[Any] = inputs['''input_ids'''] lowercase_ : List[Any] = model.generate(input_ids=A , attention_mask=inputs['''attention_mask'''] ) lowercase_ : str = tokenizer(sentences[0] , return_tensors='''tf''' ).input_ids lowercase_ : Dict = model.generate(input_ids=A ) lowercase_ : Any = inputs_non_padded.shape[-1] - tf.math.reduce_sum( tf.cast(inputs['''attention_mask'''][-1] , tf.intaa ) ) lowercase_ : Dict = tokenizer(sentences[1] , return_tensors='''tf''' ).input_ids lowercase_ : List[str] = model.generate(input_ids=A , max_length=model.config.max_length - num_paddings ) lowercase_ : Optional[int] = tokenizer.batch_decode(A , skip_special_tokens=A ) lowercase_ : List[Any] = tokenizer.decode(output_non_padded[0] , skip_special_tokens=A ) lowercase_ : Tuple = tokenizer.decode(output_padded[0] , skip_special_tokens=A ) lowercase_ : Tuple = [ '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''', '''Today, I was in the middle of a conversation with a friend about the''', ] self.assertListEqual(A , A ) self.assertListEqual(A , [non_padded_sentence, padded_sentence] ) def A ( self : List[str] ) -> Optional[Any]: lowercase_ : Any = '''facebook/opt-350m''' lowercase_ : Optional[Any] = [ '''Today is a beautiful day and I want to''', '''In the city of San Francisco, the city''', '''Paris is the capital of France and the capital''', '''Computers and mobile phones have taken over the''', ] lowercase_ : List[Any] = [] lowercase_ : Dict = GPTaTokenizer.from_pretrained(A ) lowercase_ : Tuple = TFOPTForCausalLM.from_pretrained(A ) for prompt in self.prompts: lowercase_ : Optional[Any] = tokenizer(A , return_tensors='''tf''' ).input_ids lowercase_ : Dict = model.generate(A , max_length=10 ) lowercase_ : Optional[Any] = tokenizer.batch_decode(A , skip_special_tokens=A ) predicted_outputs += generated_string self.assertListEqual(A , A )
33
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = feature_size A__ = sampling_rate A__ = padding_value A__ = kwargs.pop("padding_side" , "right" ) A__ = kwargs.pop("return_attention_mask" , lowercase ) super().__init__(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = None , lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys() )}' ) A__ = processed_features[self.model_input_names[0]] A__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase ) == 0: if return_attention_mask: A__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A__ = required_input[0] if isinstance(lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase ): A__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase ): A__ = "tf" elif is_torch_tensor(lowercase ): A__ = "pt" elif isinstance(lowercase , (int, float, list, tuple, np.ndarray) ): A__ = "np" else: raise ValueError( F'type of {first_element} unknown: {type(lowercase )}. ' "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A__ = to_numpy(lowercase ) else: A__ = [to_numpy(lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy A__ = self._get_padding_strategies(padding=lowercase , max_length=lowercase ) A__ = processed_features[self.model_input_names[0]] A__ = len(lowercase ) if not all(len(lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) A__ = [] for i in range(lowercase ): A__ = {k: v[i] for k, v in processed_features.items()} # truncation A__ = self._truncate( lowercase , max_length=lowercase , pad_to_multiple_of=lowercase , truncation=lowercase , ) truncated_inputs.append(lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A__ = PaddingStrategy.MAX_LENGTH A__ = {} for i in range(lowercase ): # padding A__ = self._pad( truncated_inputs[i] , max_length=lowercase , padding_strategy=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: A__ = [] if value.dtype is np.dtype(np.floataa ): A__ = value.astype(np.floataa ) batch_outputs[key].append(lowercase ) return BatchFeature(lowercase , tensor_type=lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = PaddingStrategy.DO_NOT_PAD , lowercase = None , lowercase = None , ) -> dict: '''simple docstring''' A__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A__ = len(lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A__ = np.ones(len(lowercase ) , dtype=np.intaa ) if needs_to_be_padded: A__ = max_length - len(lowercase ) if self.padding_side == "right": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (0, difference) ) A__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (difference, 0) ) A__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , ) -> Union[str, Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) A__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = len(lowercase ) > max_length if needs_to_be_truncated: A__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A__ = processed_features["attention_mask"][:max_length] return processed_features def UpperCamelCase ( self , lowercase=False , lowercase=None ) -> Any: '''simple docstring''' if padding is not False: if padding is True: A__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase , lowercase ): A__ = PaddingStrategy(lowercase ) elif isinstance(lowercase , lowercase ): A__ = padding else: A__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
68
0
'''simple docstring''' def snake_case_ (_a : str ): UpperCAmelCase = 0 for ch in input_str: UpperCAmelCase = ord(_a ) UpperCAmelCase = pow(2 , _a ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
34
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
0
'''simple docstring''' 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 SPIECE_UNDERLINE, logging __a = logging.get_logger(__name__) __a = {"vocab_file": "spiece.model"} __a = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } __a = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) __a = 0 __a = 1 __a = 2 __a = 3 __a = 4 class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = VOCAB_FILES_NAMES lowercase = PRETRAINED_VOCAB_FILES_MAP lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase = "left" def __init__( self : Tuple , snake_case_ : List[Any] , snake_case_ : List[Any]=False , snake_case_ : Union[str, Any]=True , snake_case_ : Optional[Any]=False , snake_case_ : str="<s>" , snake_case_ : Dict="</s>" , snake_case_ : Optional[int]="<unk>" , snake_case_ : str="<sep>" , snake_case_ : List[Any]="<pad>" , snake_case_ : Optional[int]="<cls>" , snake_case_ : int="<mask>" , snake_case_ : Optional[Any]=["<eop>", "<eod>"] , snake_case_ : Optional[Dict[str, Any]] = None , **snake_case_ : str , ): # Mask token behave like a normal word, i.e. include the space before it snake_case__ : Dict = AddedToken(snake_case_ , lstrip=snake_case_ , rstrip=snake_case_ ) if isinstance(snake_case_ , snake_case_ ) else mask_token snake_case__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=snake_case_ , remove_space=snake_case_ , keep_accents=snake_case_ , bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , sep_token=snake_case_ , pad_token=snake_case_ , cls_token=snake_case_ , mask_token=snake_case_ , additional_special_tokens=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) snake_case__ : List[str] = 3 snake_case__ : List[str] = do_lower_case snake_case__ : str = remove_space snake_case__ : Tuple = keep_accents snake_case__ : str = vocab_file snake_case__ : List[str] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @property def lowerCamelCase ( self : Union[str, Any] ): return len(self.sp_model ) def lowerCamelCase ( self : Union[str, Any] ): snake_case__ : Union[str, Any] = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ): snake_case__ : str = self.__dict__.copy() snake_case__ : Tuple = None return state def __setstate__( self : List[Any] , snake_case_ : Tuple ): snake_case__ : Optional[int] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): snake_case__ : List[Any] = {} snake_case__ : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Optional[Any] ): if self.remove_space: snake_case__ : Dict = """ """.join(inputs.strip().split() ) else: snake_case__ : Any = inputs snake_case__ : List[str] = outputs.replace("""``""" , """\"""" ).replace("""''""" , """\"""" ) if not self.keep_accents: snake_case__ : Union[str, Any] = unicodedata.normalize("""NFKD""" , snake_case_ ) snake_case__ : str = """""".join([c for c in outputs if not unicodedata.combining(snake_case_ )] ) if self.do_lower_case: snake_case__ : Optional[Any] = outputs.lower() return outputs def lowerCamelCase ( self : Tuple , snake_case_ : str ): snake_case__ : int = self.preprocess_text(snake_case_ ) snake_case__ : int = self.sp_model.encode(snake_case_ , out_type=snake_case_ ) snake_case__ : Optional[int] = [] for piece in pieces: if len(snake_case_ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): snake_case__ : Union[str, Any] = self.sp_model.EncodeAsPieces(piece[:-1].replace(snake_case_ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: snake_case__ : str = cur_pieces[1:] else: snake_case__ : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(snake_case_ ) else: new_pieces.append(snake_case_ ) return new_pieces def lowerCamelCase ( self : Optional[int] , snake_case_ : Optional[int] ): return self.sp_model.PieceToId(snake_case_ ) def lowerCamelCase ( self : List[str] , snake_case_ : List[Any] ): return self.sp_model.IdToPiece(snake_case_ ) def lowerCamelCase ( self : Optional[int] , snake_case_ : Union[str, Any] ): snake_case__ : str = """""".join(snake_case_ ).replace(snake_case_ , """ """ ).strip() return out_string def lowerCamelCase ( self : Union[str, Any] , snake_case_ : List[int] , snake_case_ : bool = False , snake_case_ : bool = None , snake_case_ : bool = True , **snake_case_ : List[Any] , ): snake_case__ : Optional[int] = kwargs.pop("""use_source_tokenizer""" , snake_case_ ) snake_case__ : Dict = self.convert_ids_to_tokens(snake_case_ , skip_special_tokens=snake_case_ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 snake_case__ : List[str] = [] snake_case__ : List[Any] = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case_ ) ) snake_case__ : List[Any] = [] sub_texts.append(snake_case_ ) else: current_sub_text.append(snake_case_ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(snake_case_ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens snake_case__ : Union[str, Any] = """""".join(snake_case_ ) snake_case__ : List[str] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: snake_case__ : Union[str, Any] = self.clean_up_tokenization(snake_case_ ) return clean_text else: return text def lowerCamelCase ( self : Optional[int] , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): snake_case__ : int = [self.sep_token_id] snake_case__ : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def lowerCamelCase ( self : int , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None , snake_case_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case_ , token_ids_a=snake_case_ , already_has_special_tokens=snake_case_ ) if token_ids_a is not None: return ([0] * len(snake_case_ )) + [1] + ([0] * len(snake_case_ )) + [1, 1] return ([0] * len(snake_case_ )) + [1, 1] def lowerCamelCase ( self : Any , snake_case_ : List[int] , snake_case_ : Optional[List[int]] = None ): snake_case__ : Dict = [self.sep_token_id] snake_case__ : Tuple = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def lowerCamelCase ( self : str , snake_case_ : str , snake_case_ : Optional[str] = None ): if not os.path.isdir(snake_case_ ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return snake_case__ : int = os.path.join( snake_case_ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , """wb""" ) as fi: snake_case__ : int = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
35
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'gpt_neox_japanese' def __init__( self , lowercase=32000 , lowercase=2560 , lowercase=32 , lowercase=32 , lowercase=4 , lowercase="gelu" , lowercase=1.00 , lowercase=10000 , lowercase=2048 , lowercase=0.02 , lowercase=1e-5 , lowercase=True , lowercase=31996 , lowercase=31999 , lowercase=0.1 , lowercase=0.0 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_multiple_size A__ = hidden_act A__ = rotary_pct A__ = rotary_emb_base A__ = initializer_range A__ = layer_norm_eps A__ = use_cache A__ = attention_dropout A__ = hidden_dropout
68
0
import datasets from .evaluate import evaluate _snake_case = "\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n" _snake_case = "\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n" _snake_case = "\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair as given in the references (see below)\n - 'prediction_text': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - 'id': id of the question-answer pair (see above),\n - 'answers': a Dict in the CUAD dataset format\n {\n 'text': list of possible texts for the answer, as a list of strings\n 'answer_start': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n 'exact_match': Exact match (the normalized answer exactly match the gold answer)\n 'f1': The F-score of predicted tokens versus the gold answer\n 'aupr': Area Under the Precision-Recall curve\n 'prec_at_80_recall': Precision at 80% recall\n 'prec_at_90_recall': Precision at 90% recall\nExamples:\n >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}]\n >>> cuad_metric = datasets.load_metric(\"cuad\")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCAmelCase_ ( datasets.Metric): def snake_case__ ( self): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": { "id": datasets.Value("string"), "prediction_text": datasets.features.Sequence(datasets.Value("string")), }, "references": { "id": datasets.Value("string"), "answers": datasets.features.Sequence( { "text": datasets.Value("string"), "answer_start": datasets.Value("int32"), }), }, }), codebase_urls=["https://www.atticusprojectai.org/cuad"], reference_urls=["https://www.atticusprojectai.org/cuad"], ) def snake_case__ ( self, __a, __a): '''simple docstring''' _lowerCAmelCase : Optional[Any] = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} _lowerCAmelCase : Optional[Any] = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] _lowerCAmelCase : int = evaluate(dataset=__a, predictions=__a) return score
36
import warnings from functools import wraps from typing import Callable def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Callable ) -> Callable: '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_: int , **SCREAMING_SNAKE_CASE_: Union[str, Any] ): warnings.warn( (F'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
68
0
'''simple docstring''' import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = {'''vocab_file''': '''spiece.model'''} _lowerCAmelCase = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } _lowerCAmelCase = { '''AI-Sweden/gpt-sw3-126m''': 2048, '''AI-Sweden/gpt-sw3-350m''': 2048, '''AI-Sweden/gpt-sw3-1.6b''': 2048, '''AI-Sweden/gpt-sw3-6.7b''': 2048, '''AI-Sweden/gpt-sw3-20b''': 2048, } class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Dict = VOCAB_FILES_NAMES __lowercase : str = PRETRAINED_VOCAB_FILES_MAP __lowercase : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowercase : Optional[int] = ['''input_ids''', '''attention_mask'''] def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=False ,__UpperCAmelCase=False ,__UpperCAmelCase=False ,__UpperCAmelCase=None ,__UpperCAmelCase=None ,__UpperCAmelCase=None ,__UpperCAmelCase=None ,__UpperCAmelCase = None ,**__UpperCAmelCase ,) -> None: lowerCAmelCase__ : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ : Dict = kwargs.get("""name_or_path""" ) if name_or_path is None: logger.warning( """name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,""" """ you are testing the model, this can safely be ignored""" ) lowerCAmelCase__ : Tuple = """None""" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing lowerCAmelCase__ : Union[str, Any] = """<|endoftext|>""" if eos_token is None else eos_token lowerCAmelCase__ : Dict = """<unk>""" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: lowerCAmelCase__ : Any = unk_token if pad_token is None else pad_token lowerCAmelCase__ : Dict = eos_token if bos_token is None else bos_token else: lowerCAmelCase__ : List[str] = """<pad>""" if pad_token is None else pad_token lowerCAmelCase__ : Optional[int] = """<s>""" if bos_token is None else bos_token super().__init__( do_lower_case=__UpperCAmelCase ,remove_space=__UpperCAmelCase ,keep_accents=__UpperCAmelCase ,bos_token=__UpperCAmelCase ,eos_token=__UpperCAmelCase ,unk_token=__UpperCAmelCase ,pad_token=__UpperCAmelCase ,sp_model_kwargs=self.sp_model_kwargs ,**__UpperCAmelCase ,) lowerCAmelCase__ : Optional[int] = do_lower_case lowerCAmelCase__ : Dict = remove_space lowerCAmelCase__ : Optional[Any] = keep_accents lowerCAmelCase__ : int = vocab_file lowerCAmelCase__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCAmelCase ) # Used for whitespace normalization in input texts # fmt : off lowerCAmelCase__ : int = {""" """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """ """, """""", """„"""} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing lowerCAmelCase__ : List[str] = re.compile( F"""[{''.join(map(__UpperCAmelCase ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(127 ,160 ) ) + [160, 173, 8203] ) )}]""" ) def __getstate__( self ) -> Any: lowerCAmelCase__ : int = self.__dict__.copy() lowerCAmelCase__ : Optional[int] = None return state def __setstate__( self ,__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : List[str] = d # for backward compatibility if not hasattr(self ,"""sp_model_kwargs""" ): lowerCAmelCase__ : Tuple = {} lowerCAmelCase__ : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCAmelCase_ ( self ) -> int: return len(self.sp_model ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: lowerCAmelCase__ : Tuple = self.non_printing_characters_re.sub("""""" ,__UpperCAmelCase ) # Normalize whitespaces lowerCAmelCase__ : List[Any] = """""".join([char if char not in self.whitespaces else """ """ for char in text] ) # NFC Unicode normalization lowerCAmelCase__ : List[Any] = unicodedata.normalize("""NFC""" ,__UpperCAmelCase ) return text def UpperCAmelCase_ ( self ,__UpperCAmelCase ,**__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : List[Any] = self.preprocess_text(__UpperCAmelCase ) return self.sp_model.encode(__UpperCAmelCase ,out_type=__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> int: return self.sp_model.PieceToId(__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: return self.sp_model.IdToPiece(__UpperCAmelCase ) @staticmethod def UpperCAmelCase_ ( __UpperCAmelCase ) -> str: return out_string def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: lowerCAmelCase__ : int = [] lowerCAmelCase__ : Optional[int] = """""" lowerCAmelCase__ : Tuple = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__UpperCAmelCase ) + token lowerCAmelCase__ : Union[str, Any] = True lowerCAmelCase__ : Optional[Any] = [] else: current_sub_tokens.append(__UpperCAmelCase ) lowerCAmelCase__ : Any = False out_string += self.sp_model.decode(__UpperCAmelCase ) return out_string def UpperCAmelCase_ ( self ) -> Dict[str, int]: lowerCAmelCase__ : Optional[int] = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ : Optional[int] = os.path.join( __UpperCAmelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,__UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase ,"""wb""" ) as fi: lowerCAmelCase__ : str = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) return (out_vocab_file,) def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(__UpperCAmelCase ,__UpperCAmelCase ): lowerCAmelCase__ : Tuple = self.preprocess_text(__UpperCAmelCase ) lowerCAmelCase__ : int = self.sp_model.encode(__UpperCAmelCase ) else: lowerCAmelCase__ : int = [self.preprocess_text(__UpperCAmelCase ) for t in text] lowerCAmelCase__ : Any = self.sp_model.encode(__UpperCAmelCase ) if return_tensors is True or return_tensors == "pt": lowerCAmelCase__ : Tuple = torch.tensor(__UpperCAmelCase ) return token_ids def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> str: return self.sp_model.decode(__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> List[int]: lowerCAmelCase__ : List[Any] = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] lowerCAmelCase__ : Any = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(__UpperCAmelCase ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=__UpperCAmelCase )
37
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
0
def SCREAMING_SNAKE_CASE_ ( __magic_name__ : Dict ) -> int: """simple docstring""" UpperCamelCase :str = len(__magic_name__ ) while cur > 1: # Find the maximum number in arr UpperCamelCase :Optional[int] = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi UpperCamelCase :List[Any] = arr[mi::-1] + arr[mi + 1 : len(__magic_name__ )] # Reverse whole list UpperCamelCase :Dict = arr[cur - 1 :: -1] + arr[cur : len(__magic_name__ )] cur -= 1 return arr if __name__ == "__main__": UpperCAmelCase_ : Union[str, Any] = input('''Enter numbers separated by a comma:\n''').strip() UpperCAmelCase_ : List[str] = [int(item) for item in user_input.split(''',''')] print(pancake_sort(unsorted))
38
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class a__ : """simple docstring""" __lowerCamelCase = BlenderbotSmallConfig __lowerCamelCase = {} __lowerCamelCase = 'gelu' def __init__( self , lowercase , lowercase=13 , lowercase=7 , lowercase=True , lowercase=False , lowercase=99 , lowercase=32 , lowercase=2 , lowercase=4 , lowercase=37 , lowercase=0.1 , lowercase=0.1 , lowercase=20 , lowercase=2 , lowercase=1 , lowercase=0 , ) -> Any: '''simple docstring''' A__ = parent A__ = batch_size A__ = seq_length A__ = is_training A__ = use_labels A__ = vocab_size A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_size A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = max_position_embeddings A__ = eos_token_id A__ = pad_token_id A__ = bos_token_id def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) A__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) A__ = tf.concat([input_ids, eos_tensor] , axis=1 ) A__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) A__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) A__ = prepare_blenderbot_small_inputs_dict(lowercase , lowercase , lowercase ) return config, inputs_dict def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = TFBlenderbotSmallModel(config=lowercase ).get_decoder() A__ = inputs_dict["input_ids"] A__ = input_ids[:1, :] A__ = inputs_dict["attention_mask"][:1, :] A__ = inputs_dict["head_mask"] A__ = 1 # first forward pass A__ = model(lowercase , attention_mask=lowercase , head_mask=lowercase , use_cache=lowercase ) A__ , A__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids A__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) A__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and A__ = tf.concat([input_ids, next_tokens] , axis=-1 ) A__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) A__ = model(lowercase , attention_mask=lowercase )[0] A__ = model(lowercase , attention_mask=lowercase , past_key_values=lowercase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice A__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) A__ = output_from_no_past[:, -3:, random_slice_idx] A__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(lowercase , lowercase , rtol=1e-3 ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: Optional[Any]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Optional[int]=None , SCREAMING_SNAKE_CASE_: Dict=None , SCREAMING_SNAKE_CASE_: List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: A__ = tf.cast(tf.math.not_equal(SCREAMING_SNAKE_CASE_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: A__ = 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: A__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: A__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) __lowerCamelCase = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () __lowerCamelCase = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) __lowerCamelCase = True __lowerCamelCase = False __lowerCamelCase = False def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = TFBlenderbotSmallModelTester(self ) A__ = ConfigTester(self , config_class=lowercase ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*lowercase ) @require_tokenizers @require_tf class a__ ( unittest.TestCase ): """simple docstring""" __lowerCamelCase = [ 'Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like ' ' i\'m going to throw up.\nand why is that?' ] __lowerCamelCase = 'facebook/blenderbot_small-90M' @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.tokenizer(self.src_text , return_tensors="tf" ) A__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=lowercase , ) A__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=lowercase )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
68
0
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# _a = [ # (stable-diffusion, HF Diffusers) ('''time_embed.0.weight''', '''time_embedding.linear_1.weight'''), ('''time_embed.0.bias''', '''time_embedding.linear_1.bias'''), ('''time_embed.2.weight''', '''time_embedding.linear_2.weight'''), ('''time_embed.2.bias''', '''time_embedding.linear_2.bias'''), ('''input_blocks.0.0.weight''', '''conv_in.weight'''), ('''input_blocks.0.0.bias''', '''conv_in.bias'''), ('''out.0.weight''', '''conv_norm_out.weight'''), ('''out.0.bias''', '''conv_norm_out.bias'''), ('''out.2.weight''', '''conv_out.weight'''), ('''out.2.bias''', '''conv_out.bias'''), ] _a = [ # (stable-diffusion, HF Diffusers) ('''in_layers.0''', '''norm1'''), ('''in_layers.2''', '''conv1'''), ('''out_layers.0''', '''norm2'''), ('''out_layers.3''', '''conv2'''), ('''emb_layers.1''', '''time_emb_proj'''), ('''skip_connection''', '''conv_shortcut'''), ] _a = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks _a = F'''down_blocks.{i}.resnets.{j}.''' _a = F'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 _a = F'''down_blocks.{i}.attentions.{j}.''' _a = F'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks _a = F'''up_blocks.{i}.resnets.{j}.''' _a = F'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 _a = F'''up_blocks.{i}.attentions.{j}.''' _a = F'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 _a = F'''down_blocks.{i}.downsamplers.0.conv.''' _a = F'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 _a = F'''up_blocks.{i}.upsamplers.0.''' _a = F'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) _a = '''mid_block.attentions.0.''' _a = '''middle_block.1.''' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): _a = F'''mid_block.resnets.{j}.''' _a = F'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" _UpperCAmelCase = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: _UpperCAmelCase = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: _UpperCAmelCase = v.replace(__lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: _UpperCAmelCase = v.replace(__lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase = v _UpperCAmelCase = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# _a = [ # (stable-diffusion, HF Diffusers) ('''nin_shortcut''', '''conv_shortcut'''), ('''norm_out''', '''conv_norm_out'''), ('''mid.attn_1.''', '''mid_block.attentions.0.'''), ] for i in range(4): # down_blocks have two resnets for j in range(2): _a = F'''encoder.down_blocks.{i}.resnets.{j}.''' _a = F'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: _a = F'''down_blocks.{i}.downsamplers.0.''' _a = F'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) _a = F'''up_blocks.{i}.upsamplers.0.''' _a = F'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): _a = F'''decoder.up_blocks.{i}.resnets.{j}.''' _a = F'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): _a = F'''mid_block.resnets.{i}.''' _a = F'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) _a = [ # (stable-diffusion, HF Diffusers) ('''norm.''', '''group_norm.'''), ('''q.''', '''query.'''), ('''k.''', '''key.'''), ('''v.''', '''value.'''), ('''proj_out.''', '''proj_attn.'''), ] def __A ( __lowerCAmelCase )-> Optional[int]: """simple docstring""" return w.reshape(*w.shape , 1 , 1 ) def __A ( __lowerCAmelCase )-> Optional[int]: """simple docstring""" _UpperCAmelCase = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: _UpperCAmelCase = v.replace(__lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: _UpperCAmelCase = v.replace(__lowerCAmelCase , __lowerCAmelCase ) _UpperCAmelCase = v _UpperCAmelCase = {v: vae_state_dict[k] for k, v in mapping.items()} _UpperCAmelCase = ['q', 'k', 'v', 'proj_out'] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if F"""mid.attn_1.{weight_name}.weight""" in k: print(F"""Reshaping {k} for SD format""" ) _UpperCAmelCase = reshape_weight_for_sd(__lowerCAmelCase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# _a = [ # (stable-diffusion, HF Diffusers) ('''resblocks.''', '''text_model.encoder.layers.'''), ('''ln_1''', '''layer_norm1'''), ('''ln_2''', '''layer_norm2'''), ('''.c_fc.''', '''.fc1.'''), ('''.c_proj.''', '''.fc2.'''), ('''.attn''', '''.self_attn'''), ('''ln_final.''', '''transformer.text_model.final_layer_norm.'''), ('''token_embedding.weight''', '''transformer.text_model.embeddings.token_embedding.weight'''), ('''positional_embedding''', '''transformer.text_model.embeddings.position_embedding.weight'''), ] _a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} _a = re.compile('''|'''.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp _a = {'''q''': 0, '''k''': 1, '''v''': 2} def __A ( __lowerCAmelCase )-> Union[str, Any]: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} _UpperCAmelCase = {} for k, v in text_enc_dict.items(): if ( k.endswith('.self_attn.q_proj.weight' ) or k.endswith('.self_attn.k_proj.weight' ) or k.endswith('.self_attn.v_proj.weight' ) ): _UpperCAmelCase = k[: -len('.q_proj.weight' )] _UpperCAmelCase = k[-len('q_proj.weight' )] if k_pre not in capture_qkv_weight: _UpperCAmelCase = [None, None, None] _UpperCAmelCase = v continue if ( k.endswith('.self_attn.q_proj.bias' ) or k.endswith('.self_attn.k_proj.bias' ) or k.endswith('.self_attn.v_proj.bias' ) ): _UpperCAmelCase = k[: -len('.q_proj.bias' )] _UpperCAmelCase = k[-len('q_proj.bias' )] if k_pre not in capture_qkv_bias: _UpperCAmelCase = [None, None, None] _UpperCAmelCase = v continue _UpperCAmelCase = textenc_pattern.sub(lambda __lowerCAmelCase : protected[re.escape(m.group(0 ) )] , __lowerCAmelCase ) _UpperCAmelCase = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) _UpperCAmelCase = textenc_pattern.sub(lambda __lowerCAmelCase : protected[re.escape(m.group(0 ) )] , __lowerCAmelCase ) _UpperCAmelCase = torch.cat(__lowerCAmelCase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) _UpperCAmelCase = textenc_pattern.sub(lambda __lowerCAmelCase : protected[re.escape(m.group(0 ) )] , __lowerCAmelCase ) _UpperCAmelCase = torch.cat(__lowerCAmelCase ) return new_state_dict def __A ( __lowerCAmelCase )-> Optional[Any]: """simple docstring""" return text_enc_dict if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument('''--model_path''', default=None, type=str, required=True, help='''Path to the model to convert.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--use_safetensors''', action='''store_true''', help='''Save weights use safetensors, default is ckpt.''' ) _a = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors _a = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.safetensors''') _a = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.safetensors''') _a = osp.join(args.model_path, '''text_encoder''', '''model.safetensors''') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): _a = load_file(unet_path, device='''cpu''') else: _a = osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.bin''') _a = torch.load(unet_path, map_location='''cpu''') if osp.exists(vae_path): _a = load_file(vae_path, device='''cpu''') else: _a = osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.bin''') _a = torch.load(vae_path, map_location='''cpu''') if osp.exists(text_enc_path): _a = load_file(text_enc_path, device='''cpu''') else: _a = osp.join(args.model_path, '''text_encoder''', '''pytorch_model.bin''') _a = torch.load(text_enc_path, map_location='''cpu''') # Convert the UNet model _a = convert_unet_state_dict(unet_state_dict) _a = {'''model.diffusion_model.''' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model _a = convert_vae_state_dict(vae_state_dict) _a = {'''first_stage_model.''' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper _a = '''text_model.encoder.layers.22.layer_norm2.bias''' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm _a = {'''transformer.''' + k: v for k, v in text_enc_dict.items()} _a = convert_text_enc_state_dict_vaa(text_enc_dict) _a = {'''cond_stage_model.model.''' + k: v for k, v in text_enc_dict.items()} else: _a = convert_text_enc_state_dict(text_enc_dict) _a = {'''cond_stage_model.transformer.''' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint _a = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: _a = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: _a = {'''state_dict''': state_dict} torch.save(state_dict, args.checkpoint_path)
39
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 convert_to_rgb, 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 if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = ['pixel_values'] def __init__( self , lowercase = True , lowercase = None , lowercase = PILImageResampling.BICUBIC , lowercase = True , lowercase = 1 / 255 , lowercase = True , lowercase = None , lowercase = None , lowercase = True , **lowercase , ) -> None: '''simple docstring''' super().__init__(**lowercase ) A__ = size if size is not None else {"height": 384, "width": 384} A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = do_resize A__ = size A__ = resample A__ = do_rescale A__ = rescale_factor A__ = do_normalize A__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN A__ = image_std if image_std is not None else OPENAI_CLIP_STD A__ = do_convert_rgb def UpperCamelCase ( self , lowercase , lowercase , lowercase = PILImageResampling.BICUBIC , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' A__ = get_size_dict(lowercase , default_to_square=lowercase ) if "height" not in size or "width" not in size: raise ValueError(F'The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}' ) A__ = (size["height"], size["width"]) return resize(lowercase , size=lowercase , resample=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase = None , **lowercase , ) -> Optional[Any]: '''simple docstring''' return rescale(lowercase , scale=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase , lowercase , lowercase = None , **lowercase , ) -> np.ndarray: '''simple docstring''' return normalize(lowercase , mean=lowercase , std=lowercase , data_format=lowercase , **lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = None , lowercase = ChannelDimension.FIRST , **lowercase , ) -> PIL.Image.Image: '''simple docstring''' A__ = do_resize if do_resize is not None else self.do_resize A__ = resample if resample is not None else self.resample A__ = do_rescale if do_rescale is not None else self.do_rescale A__ = rescale_factor if rescale_factor is not None else self.rescale_factor A__ = do_normalize if do_normalize is not None else self.do_normalize A__ = image_mean if image_mean is not None else self.image_mean A__ = image_std if image_std is not None else self.image_std A__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb A__ = size if size is not None else self.size A__ = get_size_dict(lowercase , default_to_square=lowercase ) A__ = make_list_of_images(lowercase ) if not valid_images(lowercase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_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: A__ = [convert_to_rgb(lowercase ) for image in images] # All transformations expect numpy arrays. A__ = [to_numpy_array(lowercase ) for image in images] if do_resize: A__ = [self.resize(image=lowercase , size=lowercase , resample=lowercase ) for image in images] if do_rescale: A__ = [self.rescale(image=lowercase , scale=lowercase ) for image in images] if do_normalize: A__ = [self.normalize(image=lowercase , mean=lowercase , std=lowercase ) for image in images] A__ = [to_channel_dimension_format(lowercase , lowercase ) for image in images] A__ = BatchFeature(data={"pixel_values": images} , tensor_type=lowercase ) return encoded_outputs
68
0
"""simple docstring""" from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(""">=""", """4.25.0""")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
40
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) lowerCAmelCase__ = """hf-internal-testing/tiny-random-bert""" lowerCAmelCase__ = os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""") lowerCAmelCase__ = """9b8c223d42b2188cb49d29af482996f9d0f3e5a6""" class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = cached_file(lowercase , lowercase ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(lowercase ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(lowercase , lowercase ) ) ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) self.assertTrue(os.path.isfile(lowercase ) ) # File is cached at the same place the second time. A__ = cached_file(lowercase , lowercase ) self.assertEqual(lowercase , lowercase ) # Using a specific revision to test the full commit hash. A__ = cached_file(lowercase , lowercase , revision="9b8c223" ) self.assertEqual(lowercase , os.path.join(lowercase , "snapshots" , lowercase , lowercase ) ) def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): A__ = cached_file("tiny-random-bert" , lowercase ) with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): A__ = cached_file(lowercase , lowercase , revision="aaaa" ) with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex(lowercase , "does not appear to have a file named" ): A__ = cached_file(lowercase , "conf" ) with open(os.path.join(lowercase , "refs" , "main" ) ) as f: A__ = f.read() self.assertTrue(os.path.isfile(os.path.join(lowercase , ".no_exist" , lowercase , "conf" ) ) ) A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = cached_file(lowercase , "conf" , local_files_only=lowercase , _raise_exceptions_for_missing_entries=lowercase ) self.assertIsNone(lowercase ) A__ = mock.Mock() A__ = 500 A__ = {} A__ = HTTPError A__ = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch("requests.Session.request" , return_value=lowercase ) as mock_head: A__ = cached_file(lowercase , "conf" , _raise_exceptions_for_connection_errors=lowercase ) self.assertIsNone(lowercase ) # This check we did call the fake head request mock_head.assert_called() def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only" , lowercase ) ) def UpperCamelCase ( self ) -> str: '''simple docstring''' self.assertIsNone(get_file_from_repo("bert-base-cased" , "ahah.txt" ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(lowercase , "is not a valid model identifier" ): get_file_from_repo("bert-base-case" , lowercase ) # The function raises if the revision does not exist. with self.assertRaisesRegex(lowercase , "is not a valid git identifier" ): get_file_from_repo("bert-base-cased" , lowercase , revision="ahaha" ) A__ = get_file_from_repo("bert-base-cased" , lowercase ) # The name is the cached name which is not very easy to test, so instead we load the content. A__ = json.loads(open(lowercase , "r" ).read() ) self.assertEqual(config["hidden_size"] , 768 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: A__ = Path(lowercase ) / "a.txt" filename.touch() self.assertEqual(get_file_from_repo(lowercase , "a.txt" ) , str(lowercase ) ) self.assertIsNone(get_file_from_repo(lowercase , "b.txt" ) )
68
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _A : str =logging.get_logger(__name__) _A : List[str] ={ '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class _lowercase ( _lowercase , _lowercase ): a = """focalnet""" def __init__( self: Dict , UpperCamelCase__: List[str]=224 , UpperCamelCase__: str=4 , UpperCamelCase__: List[Any]=3 , UpperCamelCase__: List[Any]=96 , UpperCamelCase__: Dict=False , UpperCamelCase__: Union[str, Any]=[192, 384, 768, 768] , UpperCamelCase__: Union[str, Any]=[2, 2, 6, 2] , UpperCamelCase__: Any=[2, 2, 2, 2] , UpperCamelCase__: Union[str, Any]=[3, 3, 3, 3] , UpperCamelCase__: Dict="gelu" , UpperCamelCase__: Dict=4.0 , UpperCamelCase__: Optional[int]=0.0 , UpperCamelCase__: str=0.1 , UpperCamelCase__: Union[str, Any]=False , UpperCamelCase__: str=1e-4 , UpperCamelCase__: List[str]=False , UpperCamelCase__: str=False , UpperCamelCase__: List[str]=False , UpperCamelCase__: Optional[Any]=0.02 , UpperCamelCase__: str=1e-5 , UpperCamelCase__: Union[str, Any]=32 , UpperCamelCase__: int=None , UpperCamelCase__: Optional[int]=None , **UpperCamelCase__: int , ): super().__init__(**UpperCamelCase__ ) lowerCamelCase__ : List[str] = image_size lowerCamelCase__ : Dict = patch_size lowerCamelCase__ : int = num_channels lowerCamelCase__ : str = embed_dim lowerCamelCase__ : List[str] = use_conv_embed lowerCamelCase__ : Dict = hidden_sizes lowerCamelCase__ : List[Any] = depths lowerCamelCase__ : int = focal_levels lowerCamelCase__ : Dict = focal_windows lowerCamelCase__ : str = hidden_act lowerCamelCase__ : Optional[Any] = mlp_ratio lowerCamelCase__ : int = hidden_dropout_prob lowerCamelCase__ : Any = drop_path_rate lowerCamelCase__ : Dict = use_layerscale lowerCamelCase__ : Union[str, Any] = layerscale_value lowerCamelCase__ : Optional[Any] = use_post_layernorm lowerCamelCase__ : Tuple = use_post_layernorm_in_modulation lowerCamelCase__ : Optional[int] = normalize_modulator lowerCamelCase__ : Dict = initializer_range lowerCamelCase__ : Any = layer_norm_eps lowerCamelCase__ : Union[str, Any] = encoder_stride lowerCamelCase__ : Union[str, Any] = ["""stem"""] + [F'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] lowerCamelCase__ , lowerCamelCase__ : str = get_aligned_output_features_output_indices( out_features=UpperCamelCase__ , out_indices=UpperCamelCase__ , stage_names=self.stage_names )
41
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class a__ ( snake_case , snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = AutoencoderKL __lowerCamelCase = 'sample' __lowerCamelCase = 1e-2 @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = 4 A__ = 3 A__ = (32, 32) A__ = floats_tensor((batch_size, num_channels) + sizes ).to(lowercase ) return {"sample": image} @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) @property def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return (3, 32, 32) def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } A__ = self.dummy_input return init_dict, inputs_dict def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ , A__ = self.prepare_init_args_and_inputs_for_common() A__ = self.model_class(**lowercase ) model.to(lowercase ) assert not model.is_gradient_checkpointing and model.training A__ = model(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() A__ = torch.randn_like(lowercase ) A__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing A__ = self.model_class(**lowercase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowercase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training A__ = model_a(**lowercase ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() A__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1e-5 ) A__ = dict(model.named_parameters() ) A__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ , A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowercase ) self.assertIsNotNone(lowercase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowercase ) A__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) A__ = model.to(lowercase ) model.eval() if torch_device == "mps": A__ = torch.manual_seed(0 ) else: A__ = torch.Generator(device=lowercase ).manual_seed(0 ) A__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) A__ = image.to(lowercase ) with torch.no_grad(): A__ = model(lowercase , sample_posterior=lowercase , generator=lowercase ).sample A__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": A__ = torch.tensor( [ -4.00_78e-01, -3.83_23e-04, -1.26_81e-01, -1.14_62e-01, 2.00_95e-01, 1.08_93e-01, -8.82_47e-02, -3.03_61e-01, -9.86_44e-03, ] ) elif torch_device == "cpu": A__ = torch.tensor( [-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] ) else: A__ = torch.tensor( [-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] ) self.assertTrue(torch_all_close(lowercase , lowercase , rtol=1e-2 ) ) @slow class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' return F'gaussian_noise_s={seed}_shape={"_".join([str(lowercase ) for s in shape] )}.npy' def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self , lowercase=0 , lowercase=(4, 3, 512, 512) , lowercase=False ) -> Optional[int]: '''simple docstring''' A__ = torch.floataa if fpaa else torch.floataa A__ = torch.from_numpy(load_hf_numpy(self.get_file_format(lowercase , lowercase ) ) ).to(lowercase ).to(lowercase ) return image def UpperCamelCase ( self , lowercase="CompVis/stable-diffusion-v1-4" , lowercase=False ) -> Any: '''simple docstring''' A__ = "fp16" if fpaa else None A__ = torch.floataa if fpaa else torch.floataa A__ = AutoencoderKL.from_pretrained( lowercase , subfolder="vae" , torch_dtype=lowercase , revision=lowercase , ) model.to(lowercase ).eval() return model def UpperCamelCase ( self , lowercase=0 ) -> List[str]: '''simple docstring''' if torch_device == "mps": return torch.manual_seed(lowercase ) return torch.Generator(device=lowercase ).manual_seed(lowercase ) @parameterized.expand( [ # fmt: off [33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> int: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]], [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , fpaa=lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model(lowercase , generator=lowercase , sample_posterior=lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]], [47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Dict: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) with torch.no_grad(): A__ = model(lowercase ).sample assert sample.shape == image.shape A__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() A__ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowercase , lowercase , atol=3e-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]], [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Tuple: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=1e-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]], [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]], # fmt: on ] ) @require_torch_gpu def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] A__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() A__ = torch.tensor(lowercase ) assert torch_all_close(lowercase , lowercase , atol=5e-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = self.get_sd_vae_model(fpaa=lowercase ) A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) , fpaa=lowercase ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase , shape=(3, 4, 64, 64) ) with torch.no_grad(): A__ = model.decode(lowercase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): A__ = model.decode(lowercase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowercase , lowercase , atol=1e-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]], [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]], # fmt: on ] ) def UpperCamelCase ( self , lowercase , lowercase ) -> str: '''simple docstring''' A__ = self.get_sd_vae_model() A__ = self.get_sd_image(lowercase ) A__ = self.get_generator(lowercase ) with torch.no_grad(): A__ = model.encode(lowercase ).latent_dist A__ = dist.sample(generator=lowercase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] A__ = sample[0, -1, -3:, -3:].flatten().cpu() A__ = torch.tensor(lowercase ) A__ = 3e-3 if torch_device != "mps" else 1e-2 assert torch_all_close(lowercase , lowercase , atol=lowercase )
68
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __UpperCAmelCase ( metaclass=_lowerCamelCase ): __lowercase = ["""torch""", """transformers""", """onnx"""] def __init__( self , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def lowerCamelCase ( cls , *lowerCAmelCase_ , **lowerCAmelCase_ ): """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] )
42
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCAmelCase__ = logging.getLogger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = label_idx def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: A__ = [] A__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 A__ = [] A__ = [] else: A__ = line.split(" " ) words.append(splits[0] ) if len(lowercase ) > 1: labels.append(splits[self.label_idx].replace("\n" , "" ) ) else: # Examples could have no label for mode = "test" labels.append("O" ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> Optional[Any]: '''simple docstring''' A__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(lowercase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: A__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(lowercase ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a__ ( snake_case ): """simple docstring""" def __init__( self ) -> Union[str, Any]: '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: A__ = f.read().splitlines() if "O" not in labels: A__ = ["O"] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a__ ( snake_case ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> List[InputExample]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = mode.value A__ = os.path.join(lowercase , F'{mode}.txt' ) A__ = 1 A__ = [] with open(lowercase , encoding="utf-8" ) as f: for sentence in parse_incr(lowercase ): A__ = [] A__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(lowercase ) == len(lowercase ) if words: examples.append(InputExample(guid=F'{mode}-{guid_index}' , words=lowercase , labels=lowercase ) ) guid_index += 1 return examples def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = 0 for sentence in parse_incr(lowercase ): A__ = preds_list[example_id] A__ = "" for token in sentence: out += F'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(lowercase ) example_id += 1 def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' if path: with open(lowercase , "r" ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
68
0
from __future__ import annotations from PIL import Image # Define glider example __lowercase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [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], ] # Define blinker example __lowercase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :int = [] for i in range(len(SCREAMING_SNAKE_CASE ) ): __UpperCamelCase :Dict = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __UpperCamelCase :List[str] = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(SCREAMING_SNAKE_CASE ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(SCREAMING_SNAKE_CASE ) - 1: neighbour_count += cells[i + 1][j] if i < len(SCREAMING_SNAKE_CASE ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __UpperCamelCase :List[str] = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(SCREAMING_SNAKE_CASE ) return next_generation def lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): '''simple docstring''' __UpperCamelCase :Optional[Any] = [] for _ in range(SCREAMING_SNAKE_CASE ): # Create output image __UpperCamelCase :Dict = Image.new('''RGB''' , (len(cells[0] ), len(SCREAMING_SNAKE_CASE )) ) __UpperCamelCase :Any = img.load() # Save cells to image for x in range(len(SCREAMING_SNAKE_CASE ) ): for y in range(len(cells[0] ) ): __UpperCamelCase :Optional[Any] = 255 - cells[y][x] * 255 __UpperCamelCase :int = (colour, colour, colour) # Save image images.append(SCREAMING_SNAKE_CASE ) __UpperCamelCase :Optional[int] = new_generation(SCREAMING_SNAKE_CASE ) return images if __name__ == "__main__": __lowercase = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
43
import random class a__ : """simple docstring""" @staticmethod def UpperCamelCase ( lowercase ) -> tuple[list[int], list[int]]: '''simple docstring''' A__ = [ord(lowercase ) for i in text] A__ = [] A__ = [] for i in plain: A__ = random.randint(1 , 300 ) A__ = (i + k) * k cipher.append(lowercase ) key.append(lowercase ) return cipher, key @staticmethod def UpperCamelCase ( lowercase , lowercase ) -> str: '''simple docstring''' A__ = [] for i in range(len(lowercase ) ): A__ = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowercase ) ) return "".join(lowercase ) if __name__ == "__main__": lowerCAmelCase__ , lowerCAmelCase__ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
68
0
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig _a : List[Any] = logging.get_logger(__name__) # General docstring _a : Optional[int] = 'RegNetConfig' # Base docstring _a : Union[str, Any] = 'facebook/regnet-y-040' _a : Tuple = [1, 1_088, 7, 7] # Image classification docstring _a : Tuple = 'facebook/regnet-y-040' _a : Union[str, Any] = 'tabby, tabby cat' _a : Union[str, Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 3 , a__ = 1 , a__ = 1 , a__ = "relu" , ): super().__init__() _lowerCAmelCase : str = nn.Convad( a__ , a__ , kernel_size=a__ , stride=a__ , padding=kernel_size // 2 , groups=a__ , bias=a__ , ) _lowerCAmelCase : str = nn.BatchNormad(a__ ) _lowerCAmelCase : Optional[int] = ACTaFN[activation] if activation is not None else nn.Identity() def __A ( self , a__ ): _lowerCAmelCase : List[str] = self.convolution(a__ ) _lowerCAmelCase : Union[str, Any] = self.normalization(a__ ) _lowerCAmelCase : List[Any] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) _lowerCAmelCase : List[Any] = config.num_channels def __A ( self , a__ ): _lowerCAmelCase : Tuple = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) _lowerCAmelCase : List[Any] = self.embedder(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 2 ): super().__init__() _lowerCAmelCase : Union[str, Any] = nn.Convad(a__ , a__ , kernel_size=1 , stride=a__ , bias=a__ ) _lowerCAmelCase : Optional[int] = nn.BatchNormad(a__ ) def __A ( self , a__ ): _lowerCAmelCase : str = self.convolution(a__ ) _lowerCAmelCase : Tuple = self.normalization(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ ): super().__init__() _lowerCAmelCase : Dict = nn.AdaptiveAvgPoolad((1, 1) ) _lowerCAmelCase : Tuple = nn.Sequential( nn.Convad(a__ , a__ , kernel_size=1 ) , nn.ReLU() , nn.Convad(a__ , a__ , kernel_size=1 ) , nn.Sigmoid() , ) def __A ( self , a__ ): # b c h w -> b c 1 1 _lowerCAmelCase : Tuple = self.pooler(a__ ) _lowerCAmelCase : int = self.attention(a__ ) _lowerCAmelCase : Optional[Any] = hidden_state * attention return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Optional[Any] = in_channels != out_channels or stride != 1 _lowerCAmelCase : Optional[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : Tuple = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : str = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Union[str, Any] = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : Any = hidden_state _lowerCAmelCase : Any = self.layer(a__ ) _lowerCAmelCase : str = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : int = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Dict = in_channels != out_channels or stride != 1 _lowerCAmelCase : List[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : List[Any] = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : Tuple = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetSELayer(a__ , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Dict = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : List[str] = hidden_state _lowerCAmelCase : Optional[int] = self.layer(a__ ) _lowerCAmelCase : List[Any] = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : List[str] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 2 , a__ = 2 , ): super().__init__() _lowerCAmelCase : List[Any] = RegNetXLayer if config.layer_type == """x""" else RegNetYLayer _lowerCAmelCase : str = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( a__ , a__ , a__ , stride=a__ , ) , *[layer(a__ , a__ , a__ ) for _ in range(depth - 1 )] , ) def __A ( self , a__ ): _lowerCAmelCase : List[Any] = self.layers(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( a__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) _lowerCAmelCase : List[str] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(a__ , config.depths[1:] ): self.stages.append(RegNetStage(a__ , a__ , a__ , depth=a__ ) ) def __A ( self , a__ , a__ = False , a__ = True ): _lowerCAmelCase : Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _lowerCAmelCase : Union[str, Any] = hidden_states + (hidden_state,) _lowerCAmelCase : Union[str, Any] = stage_module(a__ ) if output_hidden_states: _lowerCAmelCase : Union[str, Any] = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=a__ , hidden_states=a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = RegNetConfig _UpperCamelCase : int = "regnet" _UpperCamelCase : List[str] = "pixel_values" _UpperCamelCase : Union[str, Any] = True def __A ( self , a__ ): if isinstance(a__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __A ( self , a__ , a__=False ): if isinstance(a__ , a__ ): _lowerCAmelCase : Optional[int] = value _a : List[Any] = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' _a : List[Any] = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[Any] = config _lowerCAmelCase : Any = RegNetEmbeddings(a__ ) _lowerCAmelCase : List[str] = RegNetEncoder(a__ ) _lowerCAmelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self , a__ , a__ = None , a__ = None ): _lowerCAmelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : List[Any] = self.embedder(a__ ) _lowerCAmelCase : Optional[Any] = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = encoder_outputs[0] _lowerCAmelCase : Optional[Any] = self.pooler(a__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a__ , pooler_output=a__ , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config.num_labels _lowerCAmelCase : Optional[int] = RegNetModel(a__ ) # classification head _lowerCAmelCase : Optional[Any] = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self , a__ = None , a__ = None , a__ = None , a__ = None , ): _lowerCAmelCase : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : Union[str, Any] = self.regnet(a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = outputs.pooler_output if return_dict else outputs[1] _lowerCAmelCase : str = self.classifier(a__ ) _lowerCAmelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _lowerCAmelCase : str = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _lowerCAmelCase : Optional[int] = """single_label_classification""" else: _lowerCAmelCase : Optional[int] = """multi_label_classification""" if self.config.problem_type == "regression": _lowerCAmelCase : Optional[Any] = MSELoss() if self.num_labels == 1: _lowerCAmelCase : int = loss_fct(logits.squeeze() , labels.squeeze() ) else: _lowerCAmelCase : Dict = loss_fct(a__ , a__ ) elif self.config.problem_type == "single_label_classification": _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _lowerCAmelCase : Dict = BCEWithLogitsLoss() _lowerCAmelCase : Tuple = loss_fct(a__ , a__ ) if not return_dict: _lowerCAmelCase : Optional[int] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states )
44
def lowerCAmelCase__ ( ) -> Any: '''simple docstring''' for n in range(1 , 1_0_0_0_0_0_0 ): yield n * (n + 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Tuple ) -> Any: '''simple docstring''' A__ = 1 A__ = 2 while i * i <= n: A__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE_ ) > 5_0_0 ) if __name__ == "__main__": print(solution())
68
0
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) lowercase_ = logging.getLogger() lowercase_ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCAmelCase ( self , _a ): os.makedirs(_a , exist_ok=_a ) __a = {'''source''': '''What is love ?''', '''target''': '''life'''} __a = {'''train''': 12, '''val''': 2, '''test''': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: __a = '''\n'''.join([contents[field]] * n_lines[split] ) with open(os.path.join(_a , f'''{split}.{field}''' ) , '''w''' ) as f: f.write(_a ) def __UpperCAmelCase ( self , _a , _a = "pytorch" ): __a = self.get_auto_remove_tmp_dir() __a = os.path.join(_a , '''output''' ) __a = os.path.join(_a , '''data''' ) self._create_dummy_data(data_dir=_a ) __a = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append('''--fp16''' ) else: testargs.append('''--gpus=0''' ) testargs.append('''--distributed_backend=ddp_cpu''' ) testargs.append('''--num_processes=2''' ) __a = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(_a , env=self.get_env() ) __a = os.path.join(_a , '''metrics.json''' ) with open(_a ) as f: __a = json.load(_a ) return result @require_torch_gpu def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_gpu @require_ray def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu @require_ray def __UpperCAmelCase ( self ): __a = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
45
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu lowerCAmelCase__ = get_tests_dir() + """/test_data/fsmt/fsmt_val_data.json""" with io.open(filename, """r""", encoding="""utf-8""") as f: lowerCAmelCase__ = json.load(f) @require_torch class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return FSMTTokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = FSMTForConditionalGeneration.from_pretrained(lowercase ).to(lowercase ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ["en-ru", 26.0], ["ru-en", 22.0], ["en-de", 22.0], ["de-en", 29.0], ] ) @slow def UpperCamelCase ( self , lowercase , lowercase ) -> List[Any]: '''simple docstring''' A__ = F'facebook/wmt19-{pair}' A__ = self.get_tokenizer(lowercase ) A__ = self.get_model(lowercase ) A__ = bleu_data[pair]["src"] A__ = bleu_data[pair]["tgt"] A__ = tokenizer(lowercase , return_tensors="pt" , truncation=lowercase , padding="longest" ).to(lowercase ) A__ = model.generate( input_ids=batch.input_ids , num_beams=8 , ) A__ = tokenizer.batch_decode( lowercase , skip_special_tokens=lowercase , clean_up_tokenization_spaces=lowercase ) A__ = calculate_bleu(lowercase , lowercase ) print(lowercase ) self.assertGreaterEqual(scores["bleu"] , lowercase )
68
0
"""simple docstring""" def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : list ): '''simple docstring''' lowerCAmelCase = 0 while len(SCREAMING_SNAKE_CASE ) > 1: lowerCAmelCase = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): lowerCAmelCase = files.index(min(SCREAMING_SNAKE_CASE ) ) temp += files[min_index] files.pop(SCREAMING_SNAKE_CASE ) files.append(SCREAMING_SNAKE_CASE ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
46
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> list: '''simple docstring''' A__ = int(SCREAMING_SNAKE_CASE_ ) if n_element < 1: A__ = ValueError("a should be a positive number" ) raise my_error A__ = [1] A__ , A__ , A__ = (0, 0, 0) A__ = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowerCAmelCase__ = input("""Enter the last number (nth term) of the Hamming Number Series: """) print("""Formula of Hamming Number Series => 2^i * 3^j * 5^k""") lowerCAmelCase__ = hamming(int(n)) print("""-----------------------------------------------------""") print(f"""The list with nth numbers is: {hamming_numbers}""") print("""-----------------------------------------------------""")
68
0
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A__ ( A__ ): A__ = ['image_processor', 'tokenizer'] A__ = 'LayoutLMv2ImageProcessor' A__ = ('LayoutXLMTokenizer', 'LayoutXLMTokenizerFast') def __init__( self : Tuple , _a : List[Any]=None , _a : Any=None , **_a : int ) -> str: '''simple docstring''' if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , _a , ) _SCREAMING_SNAKE_CASE =kwargs.pop('feature_extractor' ) _SCREAMING_SNAKE_CASE =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(_a , _a ) def __call__( self : int , _a : List[str] , _a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , _a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , _a : Union[List[List[int]], List[List[List[int]]]] = None , _a : Optional[Union[List[int], List[List[int]]]] = None , _a : bool = True , _a : Union[bool, str, PaddingStrategy] = False , _a : Union[bool, str, TruncationStrategy] = None , _a : Optional[int] = None , _a : int = 0 , _a : Optional[int] = None , _a : Optional[bool] = None , _a : Optional[bool] = None , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = False , _a : bool = True , _a : Optional[Union[str, TensorType]] = None , **_a : List[str] , ) -> BatchEncoding: '''simple docstring''' if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( 'You cannot provide bounding boxes ' 'if you initialized the image processor with apply_ocr set to True.' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( 'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('You cannot return overflowing tokens without returning the offsets mapping.' ) # first, apply the image processor _SCREAMING_SNAKE_CASE =self.image_processor(images=_a , return_tensors=_a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(_a , _a ): _SCREAMING_SNAKE_CASE =[text] # add batch dimension (as the image processor always adds a batch dimension) _SCREAMING_SNAKE_CASE =features['words'] _SCREAMING_SNAKE_CASE =self.tokenizer( text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel values _SCREAMING_SNAKE_CASE =features.pop('pixel_values' ) if return_overflowing_tokens is True: _SCREAMING_SNAKE_CASE =self.get_overflowing_images(_a , encoded_inputs['overflow_to_sample_mapping'] ) _SCREAMING_SNAKE_CASE =images return encoded_inputs def A ( self : Any , _a : int , _a : Optional[Any] ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =[] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(_a ) != len(_a ): raise ValueError( 'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got' f" {len(_a )} and {len(_a )}" ) return images_with_overflow def A ( self : Dict , *_a : Any , **_a : Tuple ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*_a , **_a ) def A ( self : List[Any] , *_a : Any , **_a : Optional[int] ) -> List[Any]: '''simple docstring''' return self.tokenizer.decode(*_a , **_a ) @property def A ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' return ["input_ids", "bbox", "attention_mask", "image"] @property def A ( self : int ) -> List[Any]: '''simple docstring''' warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _a , ) return self.image_processor_class @property def A ( self : List[Any] ) -> Dict: '''simple docstring''' warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _a , ) return self.image_processor
47
import copy import random from transformers import CLIPTokenizer class a__ ( snake_case ): """simple docstring""" def __init__( self , *lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' super().__init__(*lowercase , **lowercase ) A__ = {} def UpperCamelCase ( self , lowercase , *lowercase , **lowercase ) -> str: '''simple docstring''' A__ = super().add_tokens(lowercase , *lowercase , **lowercase ) if num_added_tokens == 0: raise ValueError( F'The tokenizer already contains the token {placeholder_token}. Please pass a different' " `placeholder_token` that is not already in the tokenizer." ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=1 , **lowercase ) -> Any: '''simple docstring''' A__ = [] if num_vec_per_token == 1: self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) else: A__ = [] for i in range(lowercase ): A__ = placeholder_token + F'_{i}' self.try_adding_tokens(lowercase , *lowercase , **lowercase ) output.append(lowercase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( F'The tokenizer already has placeholder token {token} that can get confused with' F' {placeholder_token}keep placeholder tokens independent' ) A__ = output def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=1.0 ) -> List[Any]: '''simple docstring''' if isinstance(lowercase , lowercase ): A__ = [] for i in range(len(lowercase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=lowercase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: A__ = self.token_map[placeholder_token] A__ = tokens[: 1 + int(len(lowercase ) * prop_tokens_to_load )] if vector_shuffle: A__ = copy.copy(lowercase ) random.shuffle(lowercase ) A__ = text.replace(lowercase , " ".join(lowercase ) ) return text def __call__( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> str: '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , ) def UpperCamelCase ( self , lowercase , *lowercase , lowercase=False , lowercase=1.0 , **lowercase ) -> List[str]: '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( lowercase , vector_shuffle=lowercase , prop_tokens_to_load=lowercase ) , *lowercase , **lowercase , )
68
0
class UpperCamelCase__ : '''simple docstring''' def __init__( self , UpperCamelCase__ ) -> List[Any]: lowerCamelCase : int = val lowerCamelCase : Optional[int] = None lowerCamelCase : Any = None def _lowercase ( self , UpperCamelCase__ ) -> List[str]: if self.val: if val < self.val: if self.left is None: lowerCamelCase : Union[str, Any] = Node(UpperCamelCase__ ) else: self.left.insert(UpperCamelCase__ ) elif val > self.val: if self.right is None: lowerCamelCase : Optional[Any] = Node(UpperCamelCase__ ) else: self.right.insert(UpperCamelCase__ ) else: lowerCamelCase : List[str] = val def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) -> Optional[int]: # Recursive traversal if root: inorder(root.left ,_SCREAMING_SNAKE_CASE ) res.append(root.val ) inorder(root.right ,_SCREAMING_SNAKE_CASE ) def A ( _SCREAMING_SNAKE_CASE ) -> Dict: # Build BST if len(_SCREAMING_SNAKE_CASE ) == 0: return arr lowerCamelCase : List[Any] = Node(arr[0] ) for i in range(1 ,len(_SCREAMING_SNAKE_CASE ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCamelCase : Optional[Any] = [] inorder(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
48
from collections import deque from math import floor from random import random from time import time class a__ : """simple docstring""" def __init__( self ) -> Dict: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Tuple: '''simple docstring''' if self.graph.get(lowercase ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: A__ = [[w, v]] if not self.graph.get(lowercase ): A__ = [] def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase , lowercase ) -> int: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Any: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' A__ = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def UpperCamelCase ( self , lowercase ) -> int: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self , lowercase=-2 ) -> str: '''simple docstring''' A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s A__ = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return sorted_nodes def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Any: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> int: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin class a__ : """simple docstring""" def __init__( self ) -> int: '''simple docstring''' A__ = {} def UpperCamelCase ( self , lowercase , lowercase , lowercase=1 ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist A__ = [[w, v]] # add the other way if self.graph.get(lowercase ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist A__ = [[w, u]] def UpperCamelCase ( self , lowercase , lowercase ) -> Union[str, Any]: '''simple docstring''' if self.graph.get(lowercase ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowercase ) # the other way round if self.graph.get(lowercase ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowercase ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] A__ = [] A__ = [] if s == -2: A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowercase ) return visited else: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return visited def UpperCamelCase ( self , lowercase=-1 ) -> str: '''simple docstring''' if c == -1: A__ = floor(random() * 10000 ) + 10 for i in range(lowercase ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): A__ = floor(random() * c ) + 1 if n != i: self.add_pair(lowercase , lowercase , 1 ) def UpperCamelCase ( self , lowercase=-2 ) -> Dict: '''simple docstring''' A__ = deque() A__ = [] if s == -2: A__ = list(self.graph )[0] d.append(lowercase ) visited.append(lowercase ) while d: A__ = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def UpperCamelCase ( self , lowercase ) -> Tuple: '''simple docstring''' return len(self.graph[u] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return list(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] A__ = [] A__ = list(self.graph )[0] stack.append(lowercase ) visited.append(lowercase ) A__ = -2 A__ = [] A__ = s A__ = False A__ = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: A__ = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): A__ = len(lowercase ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) A__ = node[1] break # check if all the children are visited if s == ss: stack.pop() A__ = True if len(lowercase ) != 0: A__ = stack[len(lowercase ) - 1] else: A__ = False indirect_parents.append(lowercase ) A__ = s A__ = ss # check if se have reached the starting point if len(lowercase ) == 0: return False def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' return list(self.graph ) def UpperCamelCase ( self , lowercase=-2 , lowercase=-1 ) -> Optional[Any]: '''simple docstring''' A__ = time() self.dfs(lowercase , lowercase ) A__ = time() return end - begin def UpperCamelCase ( self , lowercase=-2 ) -> List[Any]: '''simple docstring''' A__ = time() self.bfs(lowercase ) A__ = time() return end - begin
68
0
from collections import namedtuple __snake_case :Tuple = namedtuple('''from_to''', '''from_ to''') __snake_case :Dict = { '''cubicmeter''': from_to(1, 1), '''litre''': from_to(0.0_0_1, 1000), '''kilolitre''': from_to(1, 1), '''gallon''': from_to(0.0_0_4_5_4, 2_6_4.1_7_2), '''cubicyard''': from_to(0.7_6_4_5_5, 1.3_0_7_9_5), '''cubicfoot''': from_to(0.0_2_8, 3_5.3_1_4_7), '''cup''': from_to(0.0_0_0_2_3_6_5_8_8, 4_2_2_6.7_5), } def __snake_case ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if from_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'from_type\' value: {from_type!r} Supported values are:\n' + ''', '''.join(_UpperCAmelCase ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f'Invalid \'to_type\' value: {to_type!r}. Supported values are:\n' + ''', '''.join(_UpperCAmelCase ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
49
import datasets from .evaluate import evaluate lowerCAmelCase__ = """\ @article{hendrycks2021cuad, title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review}, author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball}, journal={arXiv preprint arXiv:2103.06268}, year={2021} } """ lowerCAmelCase__ = """ This metric wrap the official scoring script for version 1 of the Contract Understanding Atticus Dataset (CUAD). Contract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510 commercial legal contracts that have been manually labeled to identify 41 categories of important clauses that lawyers look for when reviewing contracts in connection with corporate transactions. """ lowerCAmelCase__ = """ Computes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall). Args: predictions: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair as given in the references (see below) - 'prediction_text': list of possible texts for the answer, as a list of strings depending on a threshold on the confidence probability of each prediction. references: List of question-answers dictionaries with the following key-values: - 'id': id of the question-answer pair (see above), - 'answers': a Dict in the CUAD dataset format { 'text': list of possible texts for the answer, as a list of strings 'answer_start': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: 'exact_match': Exact match (the normalized answer exactly match the gold answer) 'f1': The F-score of predicted tokens versus the gold answer 'aupr': Area Under the Precision-Recall curve 'prec_at_80_recall': Precision at 80% recall 'prec_at_90_recall': Precision at 90% recall Examples: >>> predictions = [{'prediction_text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.'], 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> references = [{'answers': {'answer_start': [143, 49], 'text': ['The seller:', 'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.']}, 'id': 'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties'}] >>> cuad_metric = datasets.load_metric(\"cuad\") >>> results = cuad_metric.compute(predictions=predictions, references=references) >>> print(results) {'exact_match': 100.0, 'f1': 100.0, 'aupr': 0.0, 'prec_at_80_recall': 1.0, 'prec_at_90_recall': 1.0} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__ ( datasets.Metric ): """simple docstring""" def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": { "id": datasets.Value("string" ), "prediction_text": datasets.features.Sequence(datasets.Value("string" ) ), }, "references": { "id": datasets.Value("string" ), "answers": datasets.features.Sequence( { "text": datasets.Value("string" ), "answer_start": datasets.Value("int32" ), } ), }, } ) , codebase_urls=["https://www.atticusprojectai.org/cuad"] , reference_urls=["https://www.atticusprojectai.org/cuad"] , ) def UpperCamelCase ( self , lowercase , lowercase ) -> Optional[int]: '''simple docstring''' A__ = {prediction["id"]: prediction["prediction_text"] for prediction in predictions} A__ = [ { "paragraphs": [ { "qas": [ { "answers": [{"text": answer_text} for answer_text in ref["answers"]["text"]], "id": ref["id"], } for ref in references ] } ] } ] A__ = evaluate(dataset=lowercase , predictions=lowercase ) return score
68
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 CLIPImageProcessor, CLIPProcessor @require_vision class lowerCAmelCase ( unittest.TestCase ): def A_ ( self : List[Any] ) -> str: lowerCamelCase__ : int = tempfile.mkdtemp() # fmt: off lowerCamelCase__ : Optional[Any] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on lowerCamelCase__ : int = dict(zip(UpperCAmelCase , range(len(UpperCAmelCase ) ) ) ) lowerCamelCase__ : Any = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] lowerCamelCase__ : List[str] = {'unk_token': '<unk>'} lowerCamelCase__ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCamelCase__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(UpperCAmelCase ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(UpperCAmelCase ) ) lowerCamelCase__ : Optional[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], } lowerCamelCase__ : int = os.path.join(self.tmpdirname , UpperCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[int] , **UpperCAmelCase : Tuple ) -> Optional[int]: return CLIPTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : Union[str, Any] , **UpperCAmelCase : Any ) -> str: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : str , **UpperCAmelCase : Dict ) -> Optional[int]: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase ) def A_ ( self : int ) -> Any: shutil.rmtree(self.tmpdirname ) def A_ ( self : List[str] ) -> str: lowerCamelCase__ : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] lowerCamelCase__ : List[Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def A_ ( self : int ) -> int: lowerCamelCase__ : str = self.get_tokenizer() lowerCamelCase__ : Optional[Any] = self.get_rust_tokenizer() lowerCamelCase__ : str = self.get_image_processor() lowerCamelCase__ : List[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Dict = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase ) lowerCamelCase__ : Any = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Tuple = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase ) self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase ) def A_ ( self : int ) -> Any: lowerCamelCase__ : Any = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCamelCase__ : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowerCamelCase__ : Any = self.get_image_processor(do_normalize=UpperCAmelCase , padding_value=1.0 ) lowerCamelCase__ : Any = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=UpperCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase ) def A_ ( self : Any ) -> List[Any]: lowerCamelCase__ : int = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Dict = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Optional[int] = self.prepare_image_inputs() lowerCamelCase__ : str = image_processor(UpperCAmelCase , return_tensors='np' ) lowerCamelCase__ : Tuple = processor(images=UpperCAmelCase , return_tensors='np' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def A_ ( self : List[str] ) -> Optional[int]: lowerCamelCase__ : List[Any] = self.get_image_processor() lowerCamelCase__ : Any = self.get_tokenizer() lowerCamelCase__ : List[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = 'lower newer' lowerCamelCase__ : Dict = processor(text=UpperCAmelCase ) lowerCamelCase__ : Tuple = tokenizer(UpperCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A_ ( self : Union[str, Any] ) -> str: lowerCamelCase__ : str = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Optional[Any] = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Union[str, Any] = 'lower newer' lowerCamelCase__ : Union[str, Any] = self.prepare_image_inputs() lowerCamelCase__ : List[Any] = processor(text=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase ): processor() def A_ ( self : Optional[Any] ) -> Tuple: lowerCamelCase__ : int = self.get_image_processor() lowerCamelCase__ : Union[str, Any] = self.get_tokenizer() lowerCamelCase__ : Tuple = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCamelCase__ : Optional[Any] = processor.batch_decode(UpperCAmelCase ) lowerCamelCase__ : Optional[int] = tokenizer.batch_decode(UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , UpperCAmelCase ) def A_ ( self : Optional[int] ) -> Dict: lowerCamelCase__ : Any = self.get_image_processor() lowerCamelCase__ : Tuple = self.get_tokenizer() lowerCamelCase__ : Tuple = CLIPProcessor(tokenizer=UpperCAmelCase , image_processor=UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = 'lower newer' lowerCamelCase__ : List[str] = self.prepare_image_inputs() lowerCamelCase__ : str = processor(text=UpperCAmelCase , images=UpperCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
50
import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) A__ = nn.functional.normalize(SCREAMING_SNAKE_CASE_ ) return torch.mm(SCREAMING_SNAKE_CASE_ , normalized_text_embeds.t() ) class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = CLIPConfig __lowerCamelCase = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: '''simple docstring''' super().__init__(lowercase ) A__ = CLIPVisionModel(config.vision_config ) A__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) A__ = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) A__ = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 A__ = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() A__ = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() A__ = [] A__ = image_embeds.shape[0] for i in range(lowercase ): A__ = {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): A__ = special_cos_dist[i][concept_idx] A__ = self.special_care_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]} ) A__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): A__ = cos_dist[i][concept_idx] A__ = self.concept_embeds_weights[concept_idx].item() A__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) A__ = [len(res["bad_concepts"] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = self.vision_model(lowercase )[1] # pooled_output A__ = self.visual_projection(lowercase ) A__ = cosine_distance(lowercase , self.special_care_embeds ) A__ = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images A__ = 0.0 A__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) A__ = torch.any(special_scores > 0 , dim=1 ) A__ = special_care * 0.01 A__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) A__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) A__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
68
0
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class __snake_case ( a , unittest.TestCase ): UpperCAmelCase__ : Tuple = PriorTransformer UpperCAmelCase__ : Tuple = '''hidden_states''' @property def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = 4 UpperCAmelCase_ = 8 UpperCAmelCase_ = 7 UpperCAmelCase_ = floats_tensor((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = floats_tensor((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = floats_tensor((batch_size, num_embeddings, embedding_dim)).to(_snake_case) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def lowerCamelCase ( self : int , _snake_case : List[str]=0): """simple docstring""" torch.manual_seed(_snake_case) UpperCAmelCase_ = 4 UpperCAmelCase_ = 8 UpperCAmelCase_ = 7 UpperCAmelCase_ = torch.randn((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = torch.randn((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = torch.randn((batch_size, num_embeddings, embedding_dim)).to(_snake_case) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def lowerCamelCase ( self : List[Any]): """simple docstring""" return (4, 8) @property def lowerCamelCase ( self : str): """simple docstring""" return (4, 8) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = { '''num_attention_heads''': 2, '''attention_head_dim''': 4, '''num_layers''': 2, '''embedding_dim''': 8, '''num_embeddings''': 7, '''additional_embeddings''': 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def lowerCamelCase ( self : int): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = PriorTransformer.from_pretrained( '''hf-internal-testing/prior-dummy''' , output_loading_info=_snake_case) self.assertIsNotNone(_snake_case) self.assertEqual(len(loading_info['''missing_keys''']) , 0) model.to(_snake_case) UpperCAmelCase_ = model(**self.dummy_input)[0] assert hidden_states is not None, "Make sure output is not None" def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**_snake_case) UpperCAmelCase_ = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ['''hidden_states''', '''timestep'''] self.assertListEqual(arg_names[:2] , _snake_case) def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = PriorTransformer.from_pretrained('''hf-internal-testing/prior-dummy''') UpperCAmelCase_ = model.to(_snake_case) if hasattr(_snake_case , '''set_default_attn_processor'''): model.set_default_attn_processor() UpperCAmelCase_ = self.get_dummy_seed_input() with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case)[0] UpperCAmelCase_ = output[0, :5].flatten().cpu() print(_snake_case) # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. UpperCAmelCase_ = torch.tensor([-1.3_4_3_6, -0.2_8_7_0, 0.7_5_3_8, 0.4_3_6_8, -0.0_2_3_9]) self.assertTrue(torch_all_close(_snake_case , _snake_case , rtol=1e-2)) @slow class __snake_case ( unittest.TestCase ): def lowerCamelCase ( self : Union[str, Any] , _snake_case : Optional[Any]=1 , _snake_case : Any=768 , _snake_case : Optional[Any]=77 , _snake_case : Optional[int]=0): """simple docstring""" torch.manual_seed(_snake_case) UpperCAmelCase_ = batch_size UpperCAmelCase_ = embedding_dim UpperCAmelCase_ = num_embeddings UpperCAmelCase_ = torch.randn((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = torch.randn((batch_size, embedding_dim)).to(_snake_case) UpperCAmelCase_ = torch.randn((batch_size, num_embeddings, embedding_dim)).to(_snake_case) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def lowerCamelCase ( self : str): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.5_8_6_1, 0.1_2_8_3, -0.0_9_3_1, 0.0_8_8_2, 0.4_4_7_6, 0.1_3_2_9, -0.0_4_9_8, 0.0_6_4_0]], [37, [-0.4_9_1_3, 0.0_1_1_0, -0.0_4_8_3, 0.0_5_4_1, 0.4_9_5_4, -0.0_1_7_0, 0.0_3_5_4, 0.1_6_5_1]], # fmt: on ]) def lowerCamelCase ( self : List[str] , _snake_case : List[Any] , _snake_case : List[Any]): """simple docstring""" UpperCAmelCase_ = PriorTransformer.from_pretrained('''kandinsky-community/kandinsky-2-1-prior''' , subfolder='''prior''') model.to(_snake_case) UpperCAmelCase_ = self.get_dummy_seed_input(seed=_snake_case) with torch.no_grad(): UpperCAmelCase_ = model(**_snake_case)[0] assert list(sample.shape) == [1, 768] UpperCAmelCase_ = sample[0, :8].flatten().cpu() print(_snake_case) UpperCAmelCase_ = torch.tensor(_snake_case) assert torch_all_close(_snake_case , _snake_case , atol=1e-3)
51
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
68
0
import os def A_ ( ) -> List[str]: UpperCamelCase : Optional[Any] = os.path.dirname(os.path.realpath(_lowerCAmelCase ) ) UpperCamelCase : Optional[int] = os.path.join(_lowerCAmelCase , "triangle.txt" ) with open(_lowerCAmelCase ) as f: UpperCamelCase : Optional[int] = f.readlines() UpperCamelCase : Tuple = [] for line in triangle: UpperCamelCase : int = [] for number in line.strip().split(" " ): numbers_from_line.append(int(_lowerCAmelCase ) ) a.append(_lowerCAmelCase ) for i in range(1 , len(_lowerCAmelCase ) ): for j in range(len(a[i] ) ): UpperCamelCase : Dict = a[i - 1][j] if j != len(a[i - 1] ) else 0 UpperCamelCase : Tuple = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(_lowerCAmelCase , _lowerCAmelCase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
52
import string def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> None: '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): A__ = "" for symbol in message: if symbol in string.ascii_uppercase: A__ = string.ascii_uppercase.find(SCREAMING_SNAKE_CASE_ ) A__ = num - key if num < 0: A__ = num + len(string.ascii_uppercase ) A__ = translated + string.ascii_uppercase[num] else: A__ = translated + symbol print(F'Decryption using Key #{key}: {translated}' ) def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = input("Encrypted message: " ) A__ = message.upper() decrypt(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
0
'''simple docstring''' from __future__ import annotations a__ : Dict ={ '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } class snake_case : """simple docstring""" def __init__( self : int , __A : dict[str, list[str]] , __A : str ): __UpperCamelCase = graph # mapping node to its parent in resulting breadth first tree __UpperCamelCase = {} __UpperCamelCase = source_vertex def _lowerCamelCase ( self : Any ): __UpperCamelCase = {self.source_vertex} __UpperCamelCase = None __UpperCamelCase = [self.source_vertex] # first in first out queue while queue: __UpperCamelCase = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__A ) __UpperCamelCase = vertex queue.append(__A ) def _lowerCamelCase ( self : Union[str, Any] , __A : str ): if target_vertex == self.source_vertex: return self.source_vertex __UpperCamelCase = self.parent.get(__A ) if target_vertex_parent is None: __UpperCamelCase = ( f'''No path from vertex: {self.source_vertex} to vertex: {target_vertex}''' ) raise ValueError(__A ) return self.shortest_path(__A ) + f'''->{target_vertex}''' if __name__ == "__main__": a__ : Any =Graph(graph, '''G''') g.breath_first_search() print(g.shortest_path('''D''')) print(g.shortest_path('''G''')) print(g.shortest_path('''Foo'''))
53
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("""fixtures/test_sentencepiece_bpe_char.model""") @require_sentencepiece @require_tokenizers class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = SpeechTaTokenizer __lowerCamelCase = False __lowerCamelCase = True def UpperCamelCase ( self ) -> Any: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing A__ = SpeechTaTokenizer(lowercase ) A__ = AddedToken("<mask>" , lstrip=lowercase , rstrip=lowercase ) A__ = mask_token tokenizer.add_special_tokens({"mask_token": mask_token} ) tokenizer.add_tokens(["<ctc_blank>"] ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase ( self , lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = "this is a test" A__ = "this is a test" return input_text, output_text def UpperCamelCase ( self , lowercase , lowercase=False , lowercase=20 , lowercase=5 ) -> Optional[Any]: '''simple docstring''' A__ , A__ = self.get_input_output_texts(lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , clean_up_tokenization_spaces=lowercase ) return text, ids def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = "<pad>" A__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase ) , lowercase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase ) , lowercase ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-4] , "œ" ) self.assertEqual(vocab_keys[-2] , "<mask>" ) self.assertEqual(vocab_keys[-1] , "<ctc_blank>" ) self.assertEqual(len(lowercase ) , 81 ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) A__ = ["aaaaa bbbbbb", "cccccccccdddddddd"] A__ = tokenizer.add_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size + len(lowercase ) ) A__ = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) A__ = {"eos_token": ">>>>|||<||<<|<<", "pad_token": "<<<<<|||>|>>>>|>"} A__ = tokenizer.add_special_tokens(lowercase ) A__ = tokenizer.vocab_size A__ = len(lowercase ) self.assertNotEqual(lowercase , 0 ) self.assertEqual(lowercase , lowercase ) self.assertEqual(lowercase , len(lowercase ) ) self.assertEqual(lowercase , all_size_a + len(lowercase ) ) A__ = tokenizer.encode( ">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l" , add_special_tokens=lowercase ) self.assertGreaterEqual(len(lowercase ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizer() A__ = tokenizer.tokenize("This is a test" ) # fmt: off self.assertListEqual(lowercase , [SPIECE_UNDERLINE, "T", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "a", SPIECE_UNDERLINE, "t", "e", "s", "t"] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) A__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "92000", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) A__ = tokenizer.convert_tokens_to_ids(lowercase ) # fmt: off self.assertListEqual(lowercase , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on A__ = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , [SPIECE_UNDERLINE, "I", SPIECE_UNDERLINE, "w", "a", "s", SPIECE_UNDERLINE, "b", "o", "r", "n", SPIECE_UNDERLINE, "i", "n", SPIECE_UNDERLINE, "<unk>", ",", SPIECE_UNDERLINE, "a", "n", "d", SPIECE_UNDERLINE, "t", "h", "i", "s", SPIECE_UNDERLINE, "i", "s", SPIECE_UNDERLINE, "f", "a", "l", "s", "é", "."] ) @slow def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [ "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " "general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural " "Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained " "models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.", "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " "conditioning on both left and right context in all layers.", "The quick brown fox jumps over the lazy dog.", ] # fmt: off A__ = { "input_ids": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase , model_name="microsoft/speecht5_asr" , revision="c5ef64c71905caeccde0e4462ef3f9077224c524" , sequences=lowercase , )
68
0
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import importlib.metadata import json import os from dataclasses import dataclass from typing import Any, Dict, Union from packaging import version from ..utils import is_torch_available, logging if is_torch_available(): import torch a__ : Union[str, Any] = logging.get_logger(__name__) @dataclass class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : List[Any]=6.0 , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Union[str, Any]="fp4" , UpperCAmelCase__ : Optional[int]=False , **UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = load_in_abit __SCREAMING_SNAKE_CASE = load_in_abit __SCREAMING_SNAKE_CASE = llm_inta_threshold __SCREAMING_SNAKE_CASE = llm_inta_skip_modules __SCREAMING_SNAKE_CASE = llm_inta_enable_fpaa_cpu_offload __SCREAMING_SNAKE_CASE = llm_inta_has_fpaa_weight __SCREAMING_SNAKE_CASE = bnb_abit_quant_type __SCREAMING_SNAKE_CASE = bnb_abit_use_double_quant if bnb_abit_compute_dtype is None: __SCREAMING_SNAKE_CASE = torch.floataa elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , torch.dtype ): __SCREAMING_SNAKE_CASE = bnb_abit_compute_dtype else: raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype" ) self.post_init() def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: if not isinstance(self.llm_inta_threshold , UpperCAmelCase__ ): raise ValueError("llm_int8_threshold must be a float" ) if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules , UpperCAmelCase__ ): raise ValueError("llm_int8_skip_modules must be a list of strings" ) if not isinstance(self.llm_inta_enable_fpaa_cpu_offload , UpperCAmelCase__ ): raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean" ) if not isinstance(self.llm_inta_has_fpaa_weight , UpperCAmelCase__ ): raise ValueError("llm_int8_has_fp16_weight must be a boolean" ) if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype , torch.dtype ): raise ValueError("bnb_4bit_compute_dtype must be torch.dtype" ) if not isinstance(self.bnb_abit_quant_type , UpperCAmelCase__ ): raise ValueError("bnb_4bit_quant_type must be a string" ) if not isinstance(self.bnb_abit_use_double_quant , UpperCAmelCase__ ): raise ValueError("bnb_4bit_use_double_quant must be a boolean" ) if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes" ) ) >= version.parse( "0.39.0" ): raise ValueError( "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: return self.load_in_abit or self.load_in_abit def UpperCAmelCase_ ( self : List[str] ) -> int: if self.load_in_abit: return "llm_int8" elif self.load_in_abit and self.bnb_abit_quant_type == "fp4": return "fp4" elif self.load_in_abit and self.bnb_abit_quant_type == "nf4": return "nf4" else: return None @classmethod def UpperCAmelCase_ ( cls : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = cls(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] for key, value in kwargs.items(): if hasattr(UpperCAmelCase__ , UpperCAmelCase__ ): setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) to_remove.append(UpperCAmelCase__ ) for key in to_remove: kwargs.pop(UpperCAmelCase__ , UpperCAmelCase__ ) if return_unused_kwargs: return config, kwargs else: return config def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[str, os.PathLike] ) -> List[Any]: with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as writer: __SCREAMING_SNAKE_CASE = self.to_dict() __SCREAMING_SNAKE_CASE = json.dumps(UpperCAmelCase__ , indent=2 , sort_keys=UpperCAmelCase__ ) + "\n" writer.write(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict[str, Any]: __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = str(output["bnb_4bit_compute_dtype"] ).split("." )[1] return output def __repr__( self : Optional[int] ) -> List[Any]: return F"""{self.__class__.__name__} {self.to_json_string()}""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : bool = True ) -> str: if use_diff is True: __SCREAMING_SNAKE_CASE = self.to_diff_dict() else: __SCREAMING_SNAKE_CASE = self.to_dict() return json.dumps(UpperCAmelCase__ , indent=2 , sort_keys=UpperCAmelCase__ ) + "\n" def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict[str, Any]: __SCREAMING_SNAKE_CASE = self.to_dict() # get the default config dict __SCREAMING_SNAKE_CASE = BitsAndBytesConfig().to_dict() __SCREAMING_SNAKE_CASE = {} # only serialize values that differ from the default config for key, value in config_dict.items(): if value != default_config_dict[key]: __SCREAMING_SNAKE_CASE = value return serializable_config_dict
54
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: int ) -> List[str]: '''simple docstring''' A__ = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] A__ = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } A__ = F'{src_lang}-{tgt_lang}' A__ = F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) A__ = os.path.join(SCREAMING_SNAKE_CASE_ , "README.md" ) print(F'Generating {path}' ) with open(SCREAMING_SNAKE_CASE_ , "w" , encoding="utf-8" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) # make sure we are under the root of the project lowerCAmelCase__ = Path(__file__).resolve().parent.parent.parent lowerCAmelCase__ = repo_dir / """model_cards""" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = model_name.split("""-""") lowerCAmelCase__ = model_cards_dir / """facebook""" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
68
0
'''simple docstring''' import os import re import sys import traceback import warnings from pathlib import Path from typing import Dict, Optional, Union from uuid import uuida from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami from huggingface_hub.file_download import REGEX_COMMIT_HASH from huggingface_hub.utils import ( EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError, is_jinja_available, ) from packaging import version from requests import HTTPError from .. import __version__ from .constants import ( DEPRECATED_REVISION_ARGS, DIFFUSERS_CACHE, HUGGINGFACE_CO_RESOLVE_ENDPOINT, SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, ) from .import_utils import ( ENV_VARS_TRUE_VALUES, _flax_version, _jax_version, _onnxruntime_version, _torch_version, is_flax_available, is_onnx_available, is_torch_available, ) from .logging import get_logger a_ : Tuple = get_logger(__name__) a_ : Union[str, Any] = Path(__file__).parent / """model_card_template.md""" a_ : Any = uuida().hex a_ : List[Any] = os.getenv("""HF_HUB_OFFLINE""", """""").upper() in ENV_VARS_TRUE_VALUES a_ : Optional[Any] = os.getenv("""DISABLE_TELEMETRY""", """""").upper() in ENV_VARS_TRUE_VALUES a_ : int = HUGGINGFACE_CO_RESOLVE_ENDPOINT + """/api/telemetry/""" def __snake_case ( UpperCAmelCase_ : Union[Dict, str, None] = None ): lowerCamelCase_ = F'''diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}''' if DISABLE_TELEMETRY or HF_HUB_OFFLINE: return ua + "; telemetry/off" if is_torch_available(): ua += F'''; torch/{_torch_version}''' if is_flax_available(): ua += F'''; jax/{_jax_version}''' ua += F'''; flax/{_flax_version}''' if is_onnx_available(): ua += F'''; onnxruntime/{_onnxruntime_version}''' # CI will set this value to True if os.environ.get("DIFFUSERS_IS_CI" , "" ).upper() in ENV_VARS_TRUE_VALUES: ua += "; is_ci/true" if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): ua += "; " + "; ".join(F'''{k}/{v}''' for k, v in user_agent.items() ) elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): ua += "; " + user_agent return ua def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : Optional[str] = None ): if token is None: lowerCamelCase_ = HfFolder.get_token() if organization is None: lowerCamelCase_ = whoami(UpperCAmelCase_ )["name"] return F'''{username}/{model_id}''' else: return F'''{organization}/{model_id}''' def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : str ): if not is_jinja_available(): raise ValueError( "Modelcard rendering is based on Jinja templates." " Please make sure to have `jinja` installed before using `create_model_card`." " To install it, please run `pip install Jinja2`." ) if hasattr(UpperCAmelCase_ , "local_rank" ) and args.local_rank not in [-1, 0]: return lowerCamelCase_ = args.hub_token if hasattr(UpperCAmelCase_ , "hub_token" ) else None lowerCamelCase_ = get_full_repo_name(UpperCAmelCase_ , token=UpperCAmelCase_ ) lowerCamelCase_ = ModelCard.from_template( card_data=ModelCardData( # Card metadata object that will be converted to YAML block language="en" , license="apache-2.0" , library_name="diffusers" , tags=[] , datasets=args.dataset_name , metrics=[] , ) , template_path=UpperCAmelCase_ , model_name=UpperCAmelCase_ , repo_name=UpperCAmelCase_ , dataset_name=args.dataset_name if hasattr(UpperCAmelCase_ , "dataset_name" ) else None , learning_rate=args.learning_rate , train_batch_size=args.train_batch_size , eval_batch_size=args.eval_batch_size , gradient_accumulation_steps=( args.gradient_accumulation_steps if hasattr(UpperCAmelCase_ , "gradient_accumulation_steps" ) else None ) , adam_betaa=args.adam_betaa if hasattr(UpperCAmelCase_ , "adam_beta1" ) else None , adam_betaa=args.adam_betaa if hasattr(UpperCAmelCase_ , "adam_beta2" ) else None , adam_weight_decay=args.adam_weight_decay if hasattr(UpperCAmelCase_ , "adam_weight_decay" ) else None , adam_epsilon=args.adam_epsilon if hasattr(UpperCAmelCase_ , "adam_epsilon" ) else None , lr_scheduler=args.lr_scheduler if hasattr(UpperCAmelCase_ , "lr_scheduler" ) else None , lr_warmup_steps=args.lr_warmup_steps if hasattr(UpperCAmelCase_ , "lr_warmup_steps" ) else None , ema_inv_gamma=args.ema_inv_gamma if hasattr(UpperCAmelCase_ , "ema_inv_gamma" ) else None , ema_power=args.ema_power if hasattr(UpperCAmelCase_ , "ema_power" ) else None , ema_max_decay=args.ema_max_decay if hasattr(UpperCAmelCase_ , "ema_max_decay" ) else None , mixed_precision=args.mixed_precision , ) lowerCamelCase_ = os.path.join(args.output_dir , "README.md" ) model_card.save(UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] = None ): if resolved_file is None or commit_hash is not None: return commit_hash lowerCamelCase_ = str(Path(UpperCAmelCase_ ).as_posix() ) lowerCamelCase_ = re.search(r"snapshots/([^/]+)/" , UpperCAmelCase_ ) if search is None: return None lowerCamelCase_ = search.groups()[0] return commit_hash if REGEX_COMMIT_HASH.match(UpperCAmelCase_ ) else None # Old default cache path, potentially to be migrated. # This logic was more or less taken from `transformers`, with the following differences: # - Diffusers doesn't use custom environment variables to specify the cache path. # - There is no need to migrate the cache format, just move the files to the new location. a_ : Dict = os.path.expanduser( os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface""")) ) a_ : Any = os.path.join(hf_cache_home, """diffusers""") def __snake_case ( UpperCAmelCase_ : Optional[str] = None , UpperCAmelCase_ : Optional[str] = None ): if new_cache_dir is None: lowerCamelCase_ = DIFFUSERS_CACHE if old_cache_dir is None: lowerCamelCase_ = old_diffusers_cache lowerCamelCase_ = Path(UpperCAmelCase_ ).expanduser() lowerCamelCase_ = Path(UpperCAmelCase_ ).expanduser() for old_blob_path in old_cache_dir.glob("**/blobs/*" ): if old_blob_path.is_file() and not old_blob_path.is_symlink(): lowerCamelCase_ = new_cache_dir / old_blob_path.relative_to(UpperCAmelCase_ ) new_blob_path.parent.mkdir(parents=UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) os.replace(UpperCAmelCase_ , UpperCAmelCase_ ) try: os.symlink(UpperCAmelCase_ , UpperCAmelCase_ ) except OSError: logger.warning( "Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded." ) # At this point, old_cache_dir contains symlinks to the new cache (it can still be used). a_ : str = os.path.join(DIFFUSERS_CACHE, """version_diffusers_cache.txt""") if not os.path.isfile(cache_version_file): a_ : Union[str, Any] = 0 else: with open(cache_version_file) as f: try: a_ : int = int(f.read()) except ValueError: a_ : List[str] = 0 if cache_version < 1: a_ : Optional[int] = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0 if old_cache_is_not_empty: logger.warning( """The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your """ """existing cached models. This is a one-time operation, you can interrupt it or run it """ """later by calling `diffusers.utils.hub_utils.move_cache()`.""" ) try: move_cache() except Exception as e: a_ : Any = """\n""".join(traceback.format_tb(e.__traceback__)) logger.error( f'''There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease ''' """file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole """ """message and we will do our best to help.""" ) if cache_version < 1: try: os.makedirs(DIFFUSERS_CACHE, exist_ok=True) with open(cache_version_file, """w""") as f: f.write("""1""") except Exception: logger.warning( f'''There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure ''' """the directory exists and can be written to.""" ) def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): if variant is not None: lowerCamelCase_ = weights_name.split("." ) lowerCamelCase_ = splits[:-1] + [variant] + splits[-1:] lowerCamelCase_ = ".".join(UpperCAmelCase_ ) return weights_name def __snake_case ( UpperCAmelCase_ : List[str] , *, UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : int , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Any , UpperCAmelCase_ : Optional[int]=None , ): lowerCamelCase_ = str(UpperCAmelCase_ ) if os.path.isfile(UpperCAmelCase_ ): return pretrained_model_name_or_path elif os.path.isdir(UpperCAmelCase_ ): if os.path.isfile(os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) ): # Load from a PyTorch checkpoint lowerCamelCase_ = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ ) return model_file elif subfolder is not None and os.path.isfile( os.path.join(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) ): lowerCamelCase_ = os.path.join(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) return model_file else: raise EnvironmentError( F'''Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.''' ) else: # 1. First check if deprecated way of loading from branches is used if ( revision in DEPRECATED_REVISION_ARGS and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME) and version.parse(version.parse(UpperCAmelCase_ ).base_version ) >= version.parse("0.20.0" ) ): try: lowerCamelCase_ = hf_hub_download( UpperCAmelCase_ , filename=_add_variant(UpperCAmelCase_ , UpperCAmelCase_ ) , cache_dir=UpperCAmelCase_ , force_download=UpperCAmelCase_ , proxies=UpperCAmelCase_ , resume_download=UpperCAmelCase_ , local_files_only=UpperCAmelCase_ , use_auth_token=UpperCAmelCase_ , user_agent=UpperCAmelCase_ , subfolder=UpperCAmelCase_ , revision=revision or commit_hash , ) warnings.warn( F'''Loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'` is deprecated. Loading instead from `revision=\'main\'` with `variant={revision}`. Loading model variants via `revision=\'{revision}\'` will be removed in diffusers v1. Please use `variant=\'{revision}\'` instead.''' , UpperCAmelCase_ , ) return model_file except: # noqa: E722 warnings.warn( F'''You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant=\'{revision}\'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(UpperCAmelCase_ , UpperCAmelCase_ )} file in the \'main\' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title \'{pretrained_model_name_or_path} is missing {_add_variant(UpperCAmelCase_ , UpperCAmelCase_ )}\' so that the correct variant file can be added.''' , UpperCAmelCase_ , ) try: # 2. Load model file as usual lowerCamelCase_ = hf_hub_download( UpperCAmelCase_ , filename=UpperCAmelCase_ , cache_dir=UpperCAmelCase_ , force_download=UpperCAmelCase_ , proxies=UpperCAmelCase_ , resume_download=UpperCAmelCase_ , local_files_only=UpperCAmelCase_ , use_auth_token=UpperCAmelCase_ , user_agent=UpperCAmelCase_ , subfolder=UpperCAmelCase_ , revision=revision or commit_hash , ) return model_file except RepositoryNotFoundError: raise EnvironmentError( F'''{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier ''' "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a " "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli " "login`." ) except RevisionNotFoundError: raise EnvironmentError( F'''{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for ''' "this model name. Check the model page at " F'''\'https://huggingface.co/{pretrained_model_name_or_path}\' for available revisions.''' ) except EntryNotFoundError: raise EnvironmentError( F'''{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.''' ) except HTTPError as err: raise EnvironmentError( F'''There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}''' ) except ValueError: raise EnvironmentError( F'''We couldn\'t connect to \'{HUGGINGFACE_CO_RESOLVE_ENDPOINT}\' to load this model, couldn\'t find it''' F''' in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a''' F''' directory containing a file named {weights_name} or''' " \nCheckout your internet connection or see how to run the library in" " offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'." ) except EnvironmentError: raise EnvironmentError( F'''Can\'t load the model for \'{pretrained_model_name_or_path}\'. If you were trying to load it from ''' "'https://huggingface.co/models', make sure you don't have a local directory with the same name. " F'''Otherwise, make sure \'{pretrained_model_name_or_path}\' is the correct path to a directory ''' F'''containing a file named {weights_name}''' )
55
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase__ = logging.get_logger(__name__) class a__ ( snake_case ): """simple docstring""" def __init__( self , lowercase , lowercase , lowercase , **lowercase ) -> Union[str, Any]: '''simple docstring''' A__ = feature_size A__ = sampling_rate A__ = padding_value A__ = kwargs.pop("padding_side" , "right" ) A__ = kwargs.pop("return_attention_mask" , lowercase ) super().__init__(**lowercase ) def UpperCamelCase ( self , lowercase , lowercase = True , lowercase = None , lowercase = False , lowercase = None , lowercase = None , lowercase = None , ) -> BatchFeature: '''simple docstring''' if isinstance(lowercase , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A__ = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( "You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`" F' to this method that includes {self.model_input_names[0]}, but you provided' F' {list(processed_features.keys() )}' ) A__ = processed_features[self.model_input_names[0]] A__ = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(lowercase ) == 0: if return_attention_mask: A__ = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A__ = required_input[0] if isinstance(lowercase , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A__ = 0 while len(required_input[index] ) == 0: index += 1 if index < len(lowercase ): A__ = required_input[index][0] if return_tensors is None: if is_tf_tensor(lowercase ): A__ = "tf" elif is_torch_tensor(lowercase ): A__ = "pt" elif isinstance(lowercase , (int, float, list, tuple, np.ndarray) ): A__ = "np" else: raise ValueError( F'type of {first_element} unknown: {type(lowercase )}. ' "Should be one of a python, numpy, pytorch or tensorflow object." ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A__ = to_numpy(lowercase ) else: A__ = [to_numpy(lowercase ) for v in value] # Convert padding_strategy in PaddingStrategy A__ = self._get_padding_strategies(padding=lowercase , max_length=lowercase ) A__ = processed_features[self.model_input_names[0]] A__ = len(lowercase ) if not all(len(lowercase ) == batch_size for v in processed_features.values() ): raise ValueError("Some items in the output dictionary have a different batch size than others." ) A__ = [] for i in range(lowercase ): A__ = {k: v[i] for k, v in processed_features.items()} # truncation A__ = self._truncate( lowercase , max_length=lowercase , pad_to_multiple_of=lowercase , truncation=lowercase , ) truncated_inputs.append(lowercase ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A__ = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A__ = PaddingStrategy.MAX_LENGTH A__ = {} for i in range(lowercase ): # padding A__ = self._pad( truncated_inputs[i] , max_length=lowercase , padding_strategy=lowercase , pad_to_multiple_of=lowercase , return_attention_mask=lowercase , ) for key, value in outputs.items(): if key not in batch_outputs: A__ = [] if value.dtype is np.dtype(np.floataa ): A__ = value.astype(np.floataa ) batch_outputs[key].append(lowercase ) return BatchFeature(lowercase , tensor_type=lowercase ) def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = PaddingStrategy.DO_NOT_PAD , lowercase = None , lowercase = None , ) -> dict: '''simple docstring''' A__ = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A__ = len(lowercase ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(lowercase ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A__ = np.ones(len(lowercase ) , dtype=np.intaa ) if needs_to_be_padded: A__ = max_length - len(lowercase ) if self.padding_side == "right": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (0, difference) ) A__ = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A__ = np.pad( processed_features["attention_mask"] , (difference, 0) ) A__ = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A__ = np.pad( lowercase , lowercase , "constant" , constant_values=self.padding_value ) else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return processed_features def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = None , lowercase = None , ) -> Union[str, Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError("When setting ``truncation=True``, make sure that ``max_length`` is defined." ) A__ = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A__ = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A__ = len(lowercase ) > max_length if needs_to_be_truncated: A__ = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A__ = processed_features["attention_mask"][:max_length] return processed_features def UpperCamelCase ( self , lowercase=False , lowercase=None ) -> Any: '''simple docstring''' if padding is not False: if padding is True: A__ = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(lowercase , lowercase ): A__ = PaddingStrategy(lowercase ) elif isinstance(lowercase , lowercase ): A__ = padding else: A__ = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( "Asking to pad but the feature_extractor does not have a padding value. Please select a value to use" " as `padding_value`. For example: `feature_extractor.padding_value = 0.0`." ) return padding_strategy
68
0
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: a : Dict = None a : List[Any] = logging.get_logger(__name__) a : List[Any] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} a : str = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 a : List[Any] = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class a ( _lowerCamelCase ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = TaTokenizer snake_case_ = [] def __init__( self : List[Any] , lowercase_ : int=None , lowercase_ : Dict=None , lowercase_ : Dict="</s>" , lowercase_ : List[Any]="<unk>" , lowercase_ : int="<pad>" , lowercase_ : int=100 , lowercase_ : List[Any]=None , **lowercase_ : List[str] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: snake_case_ = [F"<extra_id_{i}>" for i in range(lowercase_ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens snake_case_ = len(set(filter(lambda lowercase_ : bool('''extra_id_''' in str(lowercase_ ) ) , lowercase_ ) ) ) if extra_tokens != extra_ids: raise ValueError( F"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( lowercase_ , tokenizer_file=lowercase_ , eos_token=lowercase_ , unk_token=lowercase_ , pad_token=lowercase_ , extra_ids=lowercase_ , additional_special_tokens=lowercase_ , **lowercase_ , ) snake_case_ = vocab_file snake_case_ = False if not self.vocab_file else True snake_case_ = extra_ids @staticmethod def A_ ( lowercase_ : Optional[int] , lowercase_ : List[str] , lowercase_ : int ): if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: snake_case_ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' F" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' F" {pretrained_model_name_or_path} automatically truncating your input to" F" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" F" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , lowercase_ , ) return max_model_length def A_ ( self : Optional[Any] , lowercase_ : str , lowercase_ : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(lowercase_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ = os.path.join( lowercase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowercase_ ): copyfile(self.vocab_file , lowercase_ ) logger.info(F"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def A_ ( self : Optional[int] , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): snake_case_ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: snake_case_ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def A_ ( self : int , lowercase_ : List[int] , lowercase_ : Optional[List[int]] = None ): snake_case_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def A_ ( self : Dict ): return list( set(filter(lambda lowercase_ : bool(re.search(R'''<extra_id_\d+>''' , lowercase_ ) ) is not None , self.additional_special_tokens ) ) ) def A_ ( self : Any ): return [self.convert_tokens_to_ids(lowercase_ ) for token in self.get_sentinel_tokens()]
56
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase__ = { """configuration_groupvit""": [ """GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GroupViTConfig""", """GroupViTOnnxConfig""", """GroupViTTextConfig""", """GroupViTVisionConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """GroupViTModel""", """GroupViTPreTrainedModel""", """GroupViTTextModel""", """GroupViTVisionModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ """TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFGroupViTModel""", """TFGroupViTPreTrainedModel""", """TFGroupViTTextModel""", """TFGroupViTVisionModel""", ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
68
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu A : Any = False class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def snake_case ( self ): return 12 @property def snake_case ( self ): return 12 @property def snake_case ( self ): return 32 @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def snake_case ( self ): __lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(__a ) @property def snake_case ( self ): torch.manual_seed(0 ) __lowerCAmelCase = 12 __lowerCAmelCase = 12 __lowerCAmelCase = { "attention_bias": True, "cross_attention_dim": 32, "attention_head_dim": height * width, "num_attention_heads": 1, "num_vector_embeds": self.num_embed, "num_embeds_ada_norm": self.num_embeds_ada_norm, "norm_num_groups": 32, "sample_size": width, "activation_fn": "geglu-approximate", } __lowerCAmelCase = TransformeraDModel(**__a ) return model def snake_case ( self ): __lowerCAmelCase = "cpu" __lowerCAmelCase = self.dummy_vqvae __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_transformer __lowerCAmelCase = VQDiffusionScheduler(self.num_embed ) __lowerCAmelCase = LearnedClassifierFreeSamplingEmbeddings(learnable=__a ) __lowerCAmelCase = VQDiffusionPipeline( vqvae=__a , text_encoder=__a , tokenizer=__a , transformer=__a , scheduler=__a , learned_classifier_free_sampling_embeddings=__a , ) __lowerCAmelCase = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __lowerCAmelCase = "teddy bear playing in the pool" __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(0 ) __lowerCAmelCase = pipe([prompt] , generator=__a , num_inference_steps=2 , output_type="np" ) __lowerCAmelCase = output.images __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(0 ) __lowerCAmelCase = pipe( [prompt] , generator=__a , output_type="np" , return_dict=__a , num_inference_steps=2 )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) __lowerCAmelCase = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case ( self ): __lowerCAmelCase = "cpu" __lowerCAmelCase = self.dummy_vqvae __lowerCAmelCase = self.dummy_text_encoder __lowerCAmelCase = self.dummy_tokenizer __lowerCAmelCase = self.dummy_transformer __lowerCAmelCase = VQDiffusionScheduler(self.num_embed ) __lowerCAmelCase = LearnedClassifierFreeSamplingEmbeddings( learnable=__a , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) __lowerCAmelCase = VQDiffusionPipeline( vqvae=__a , text_encoder=__a , tokenizer=__a , transformer=__a , scheduler=__a , learned_classifier_free_sampling_embeddings=__a , ) __lowerCAmelCase = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) __lowerCAmelCase = "teddy bear playing in the pool" __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(0 ) __lowerCAmelCase = pipe([prompt] , generator=__a , num_inference_steps=2 , output_type="np" ) __lowerCAmelCase = output.images __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(0 ) __lowerCAmelCase = pipe( [prompt] , generator=__a , output_type="np" , return_dict=__a , num_inference_steps=2 )[0] __lowerCAmelCase = image[0, -3:, -3:, -1] __lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) __lowerCAmelCase = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def snake_case ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self ): __lowerCAmelCase = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy" ) __lowerCAmelCase = VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq" ) __lowerCAmelCase = pipeline.to(__a ) pipeline.set_progress_bar_config(disable=__a ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though __lowerCAmelCase = torch.Generator(device=__a ).manual_seed(0 ) __lowerCAmelCase = pipeline( "teddy bear playing in the pool" , num_images_per_prompt=1 , generator=__a , output_type="np" , ) __lowerCAmelCase = output.images[0] assert image.shape == (2_56, 2_56, 3) assert np.abs(expected_image - image ).max() < 2.0
57
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { """abeja/gpt-neox-japanese-2.7b""": """https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json""", } class a__ ( snake_case ): """simple docstring""" __lowerCamelCase = 'gpt_neox_japanese' def __init__( self , lowercase=32000 , lowercase=2560 , lowercase=32 , lowercase=32 , lowercase=4 , lowercase="gelu" , lowercase=1.00 , lowercase=10000 , lowercase=2048 , lowercase=0.02 , lowercase=1e-5 , lowercase=True , lowercase=31996 , lowercase=31999 , lowercase=0.1 , lowercase=0.0 , **lowercase , ) -> Dict: '''simple docstring''' super().__init__(bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) A__ = vocab_size A__ = max_position_embeddings A__ = hidden_size A__ = num_hidden_layers A__ = num_attention_heads A__ = intermediate_multiple_size A__ = hidden_act A__ = rotary_pct A__ = rotary_emb_base A__ = initializer_range A__ = layer_norm_eps A__ = use_cache A__ = attention_dropout A__ = hidden_dropout
68
0
'''simple docstring''' import argparse import os 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 ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, 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) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # 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 # ######################################################################## lowercase_ = 16 lowercase_ = 32 def lowerCamelCase ( __lowerCamelCase : Accelerator , __lowerCamelCase : int = 16 ) ->int: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCamelCase : int ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCamelCase , max_length=__lowerCamelCase ) 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(): _SCREAMING_SNAKE_CASE = datasets.map( __lowerCamelCase , batched=__lowerCamelCase , 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 _SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCamelCase : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE = 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": _SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE = 8 else: _SCREAMING_SNAKE_CASE = None return tokenizer.pad( __lowerCamelCase , padding="""longest""" , max_length=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCamelCase , collate_fn=__lowerCamelCase , batch_size=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCamelCase , collate_fn=__lowerCamelCase , batch_size=__lowerCamelCase ) 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 lowercase_ = mocked_dataloaders # noqa: F811 def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Any ) ->Optional[Any]: # For testing only if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __lowerCamelCase ) == "1": _SCREAMING_SNAKE_CASE = 2 # Initialize accelerator _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = get_dataloaders(__lowerCamelCase , __lowerCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCamelCase ) # 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). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=__lowerCamelCase ) # Instantiate scheduler _SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=__lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCamelCase ) * num_epochs) // gradient_accumulation_steps , ) # 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. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase ): model.train() for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.loss _SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(__lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(__lowerCamelCase ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples _SCREAMING_SNAKE_CASE = predictions[: len(eval_dataloader.dataset ) - samples_seen] _SCREAMING_SNAKE_CASE = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=__lowerCamelCase , references=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , __lowerCamelCase ) def lowerCamelCase ( ) ->List[str]: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , 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.""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
import warnings from functools import wraps from typing import Callable def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Callable ) -> Callable: '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_: int , **SCREAMING_SNAKE_CASE_: Union[str, Any] ): warnings.warn( (F'\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.') , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
68
0
def UpperCamelCase ( __lowerCamelCase : list ): if any(not isinstance(__lowerCamelCase , __lowerCamelCase ) or x < 0 for x in sequence ): raise TypeError("Sequence must be list of non-negative integers" ) for _ in range(len(__lowerCamelCase ) ): for i, (rod_upper, rod_lower) in enumerate(zip(__lowerCamelCase , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ = """\ Text data. Second line of data.""" lowerCAmelCase__ = """file""" @pytest.fixture(scope="session" ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[Any] ) -> Optional[int]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") A__ = bytes(SCREAMING_SNAKE_CASE_ , "utf-8" ) with zstd.open(SCREAMING_SNAKE_CASE_ , "wb" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return path @pytest.fixture def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any ) -> List[str]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , SCREAMING_SNAKE_CASE_ ) , "w" ) as f: f.write(SCREAMING_SNAKE_CASE_ ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: Optional[Any] , SCREAMING_SNAKE_CASE_: int ) -> Any: '''simple docstring''' A__ = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} A__ = input_paths[compression_format] A__ = tmp_path / "cache" A__ = DownloadConfig(cache_dir=SCREAMING_SNAKE_CASE_ , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: List[Any] , SCREAMING_SNAKE_CASE_: Optional[int] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str ) -> Dict: '''simple docstring''' A__ = "custom_cache" A__ = "custom_extracted_dir" A__ = tmp_path / "custom_extracted_path" if default_extracted: A__ = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , SCREAMING_SNAKE_CASE_ ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(SCREAMING_SNAKE_CASE_ ) ) A__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) A__ = xz_file A__ = ( DownloadConfig(extract_compressed_file=SCREAMING_SNAKE_CASE_ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE_ ) ) A__ = cached_path(SCREAMING_SNAKE_CASE_ , download_config=SCREAMING_SNAKE_CASE_ ) assert Path(SCREAMING_SNAKE_CASE_ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> Optional[int]: '''simple docstring''' A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve() ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file # relative path A__ = str(Path(SCREAMING_SNAKE_CASE_ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(SCREAMING_SNAKE_CASE_ ) == text_file def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[str]: '''simple docstring''' A__ = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) # relative path A__ = "./__missing_file__.txt" with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> Union[str, Any]: '''simple docstring''' A__ = get_from_cache(F'tmp://{tmpfs_file}' ) with open(SCREAMING_SNAKE_CASE_ ) as f: A__ = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' with pytest.raises(SCREAMING_SNAKE_CASE_ ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: List[str] ) -> int: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_get("https://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Dict ) -> List[Any]: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_get("ftp://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Union[str, Any] ) -> str: '''simple docstring''' A__ = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_get("s3://huggingface.co" , temp_file=SCREAMING_SNAKE_CASE_ ) with pytest.raises(SCREAMING_SNAKE_CASE_ ): fsspec_head("s3://huggingface.co" )
68
0