code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' def A ( ) -> Any: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , 10_01 ): total += i**i return str(UpperCamelCase_ )[-10:] if __name__ == "__main__": print(solution())
48
'''simple docstring''' from math import sqrt def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , int(sqrt(UpperCamelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase_ ): total += i + n // i elif i == sqrt(UpperCamelCase_ ): total += i return total - n def A ( UpperCamelCase_ : int = 1_00_00 ) -> int: '''simple docstring''' lowerCAmelCase__ = sum( i for i in range(1 , UpperCamelCase_ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase_ ) ) == i and sum_of_divisors(UpperCamelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
48
1
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class A : def __init__( self : int , __magic_name__ : Optional[int] ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden lowerCAmelCase__ = deepcopy(__magic_name__ ) elif os.path.exists(__magic_name__ ): with io.open(__magic_name__ , "r" , encoding="utf-8" ) as f: lowerCAmelCase__ = json.load(__magic_name__ ) else: try: lowerCAmelCase__ = baseaa.urlsafe_baadecode(__magic_name__ ).decode("utf-8" ) lowerCAmelCase__ = json.loads(__magic_name__ ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( f"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) lowerCAmelCase__ = config self.set_stage_and_offload() def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.get_value("zero_optimization.stage" , -1 ) # offload lowerCAmelCase__ = False if self.is_zeroa() or self.is_zeroa(): lowerCAmelCase__ = set(["cpu", "nvme"] ) lowerCAmelCase__ = set( [ self.get_value("zero_optimization.offload_optimizer.device" ), self.get_value("zero_optimization.offload_param.device" ), ] ) if len(offload_devices & offload_devices_valid ) > 0: lowerCAmelCase__ = True def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = self.config # find the config node of interest if it exists lowerCAmelCase__ = ds_key_long.split("." ) lowerCAmelCase__ = nodes.pop() for node in nodes: lowerCAmelCase__ = config.get(__magic_name__ ) if config is None: return None, ds_key return config, ds_key def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=None ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.find_config_node(__magic_name__ ) if config is None: return default return config.get(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict , __magic_name__ : Union[str, Any]=False ): """simple docstring""" lowerCAmelCase__ = self.config # find the config node of interest if it exists lowerCAmelCase__ = ds_key_long.split("." ) for node in nodes: lowerCAmelCase__ = config lowerCAmelCase__ = config.get(__magic_name__ ) if config is None: if must_exist: raise ValueError(f"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = self.get_value(__magic_name__ ) return False if value is None else bool(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = self.get_value(__magic_name__ ) return False if value is None else not bool(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return self._stage == 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self._stage == 3 def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self._offload class A : def __init__( self : Union[str, Any] , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = engine def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : int , **__magic_name__ : int ): """simple docstring""" self.engine.backward(__magic_name__ , **__magic_name__ ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(__magic_name__ , device_placement=__magic_name__ , scaler=__magic_name__ ) lowerCAmelCase__ = hasattr(self.optimizer , "overflow" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any]=None ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" if self.__has_overflow__: return self.optimizer.overflow return False class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : str , __magic_name__ : List[str] , __magic_name__ : Tuple ): """simple docstring""" super().__init__(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class A : def __init__( self : List[Any] , __magic_name__ : Any , __magic_name__ : List[Any]=0.001 , __magic_name__ : Any=0 , **__magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = params lowerCAmelCase__ = lr lowerCAmelCase__ = weight_decay lowerCAmelCase__ = kwargs class A : def __init__( self : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : List[Any]=None , __magic_name__ : Tuple=0 , **__magic_name__ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = optimizer lowerCAmelCase__ = total_num_steps lowerCAmelCase__ = warmup_num_steps lowerCAmelCase__ = kwargs
48
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class A : def __init__( self : Dict , __magic_name__ : Collection[float] | None = None ): """simple docstring""" if components is None: lowerCAmelCase__ = [] lowerCAmelCase__ = list(__magic_name__ ) def __len__( self : Optional[Any] ): """simple docstring""" return len(self.__components ) def __str__( self : Optional[Any] ): """simple docstring""" return "(" + ",".join(map(__magic_name__ , self.__components ) ) + ")" def __add__( self : Dict , __magic_name__ : Vector ): """simple docstring""" lowerCAmelCase__ = len(self ) if size == len(__magic_name__ ): lowerCAmelCase__ = [self.__components[i] + other.component(__magic_name__ ) for i in range(__magic_name__ )] return Vector(__magic_name__ ) else: raise Exception("must have the same size" ) def __sub__( self : Tuple , __magic_name__ : Vector ): """simple docstring""" lowerCAmelCase__ = len(self ) if size == len(__magic_name__ ): lowerCAmelCase__ = [self.__components[i] - other.component(__magic_name__ ) for i in range(__magic_name__ )] return Vector(__magic_name__ ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self : Optional[Any] , __magic_name__ : float ): """simple docstring""" ... @overload def __mul__( self : Union[str, Any] , __magic_name__ : Vector ): """simple docstring""" ... def __mul__( self : Union[str, Any] , __magic_name__ : float | Vector ): """simple docstring""" if isinstance(__magic_name__ , (float, int) ): lowerCAmelCase__ = [c * other for c in self.__components] return Vector(__magic_name__ ) elif isinstance(__magic_name__ , __magic_name__ ) and len(self ) == len(__magic_name__ ): lowerCAmelCase__ = len(self ) lowerCAmelCase__ = [self.__components[i] * other.component(__magic_name__ ) for i in range(__magic_name__ )] return sum(__magic_name__ ) else: # error case raise Exception("invalid operand!" ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return Vector(self.__components ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : int ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : int , __magic_name__ : float ): """simple docstring""" assert -len(self.__components ) <= pos < len(self.__components ) lowerCAmelCase__ = value def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" if len(self.__components ) == 0: raise Exception("Vector is empty" ) lowerCAmelCase__ = [c**2 for c in self.__components] return math.sqrt(sum(__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Vector , __magic_name__ : bool = False ): """simple docstring""" lowerCAmelCase__ = self * other lowerCAmelCase__ = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def A ( UpperCamelCase_ : int ) -> Vector: '''simple docstring''' assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) return Vector([0] * dimension ) def A ( UpperCamelCase_ : int , UpperCamelCase_ : int ) -> Vector: '''simple docstring''' assert isinstance(UpperCamelCase_ , UpperCamelCase_ ) and (isinstance(UpperCamelCase_ , UpperCamelCase_ )) lowerCAmelCase__ = [0] * dimension lowerCAmelCase__ = 1 return Vector(UpperCamelCase_ ) def A ( UpperCamelCase_ : float , UpperCamelCase_ : Vector , UpperCamelCase_ : Vector ) -> Vector: '''simple docstring''' assert ( isinstance(UpperCamelCase_ , UpperCamelCase_ ) and isinstance(UpperCamelCase_ , UpperCamelCase_ ) and (isinstance(UpperCamelCase_ , (int, float) )) ) return x * scalar + y def A ( UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> Vector: '''simple docstring''' random.seed(UpperCamelCase_ ) lowerCAmelCase__ = [random.randint(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(UpperCamelCase_ )] return Vector(UpperCamelCase_ ) class A : def __init__( self : Dict , __magic_name__ : list[list[float]] , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = matrix lowerCAmelCase__ = w lowerCAmelCase__ = h def __str__( self : str ): """simple docstring""" lowerCAmelCase__ = "" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : int , __magic_name__ : Matrix ): """simple docstring""" if self.__width == other.width() and self.__height == other.height(): lowerCAmelCase__ = [] for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] + other.component(__magic_name__ , __magic_name__ ) for j in range(self.__width ) ] matrix.append(__magic_name__ ) return Matrix(__magic_name__ , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self : Dict , __magic_name__ : Matrix ): """simple docstring""" if self.__width == other.width() and self.__height == other.height(): lowerCAmelCase__ = [] for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] - other.component(__magic_name__ , __magic_name__ ) for j in range(self.__width ) ] matrix.append(__magic_name__ ) return Matrix(__magic_name__ , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self : Optional[Any] , __magic_name__ : float ): """simple docstring""" ... @overload def __mul__( self : Optional[Any] , __magic_name__ : Vector ): """simple docstring""" ... def __mul__( self : Optional[int] , __magic_name__ : float | Vector ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): # matrix-vector if len(__magic_name__ ) == self.__width: lowerCAmelCase__ = zero_vector(self.__height ) for i in range(self.__height ): lowerCAmelCase__ = [ self.__matrix[i][j] * other.component(__magic_name__ ) for j in range(self.__width ) ] ans.change_component(__magic_name__ , sum(__magic_name__ ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(__magic_name__ , (int, float) ): # matrix-scalar lowerCAmelCase__ = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(__magic_name__ , self.__width , self.__height ) return None def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.__height def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return self.__width def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : int , __magic_name__ : int , __magic_name__ : float ): """simple docstring""" if 0 <= x < self.__height and 0 <= y < self.__width: lowerCAmelCase__ = value else: raise Exception("change_component: indices out of bounds" ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" if self.__height != self.__width: raise Exception("Matrix is not square" ) lowerCAmelCase__ = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(__magic_name__ ) ): lowerCAmelCase__ = minor[i][:y] + minor[i][y + 1 :] return Matrix(__magic_name__ , self.__width - 1 , self.__height - 1 ).determinant() def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(__magic_name__ , __magic_name__ ) else: raise Exception("Indices out of bounds" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: lowerCAmelCase__ = [ self.__matrix[0][y] * self.cofactor(0 , __magic_name__ ) for y in range(self.__width ) ] return sum(__magic_name__ ) def A ( UpperCamelCase_ : int ) -> Matrix: '''simple docstring''' lowerCAmelCase__ = [[0] * n for _ in range(UpperCamelCase_ )] return Matrix(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def A ( UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> Matrix: '''simple docstring''' random.seed(UpperCamelCase_ ) lowerCAmelCase__ = [ [random.randint(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(UpperCamelCase_ )] for _ in range(UpperCamelCase_ ) ] return Matrix(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
48
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
1
'''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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase__ : int = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'facebook/nllb-200-distilled-600M' snake_case__ :Optional[Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) snake_case__ :List[Any] = 'translator' snake_case__ :List[Any] = AutoTokenizer snake_case__ :Optional[Any] = AutoModelForSeqaSeqLM snake_case__ :List[str] = LANGUAGE_CODES snake_case__ :List[Any] = ['text', 'text', 'text'] snake_case__ :List[Any] = ['text'] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ): """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __magic_name__ , return_tensors="pt" , src_lang=__magic_name__ , tgt_lang=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__magic_name__ )
48
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ : str = sys.version_info >= (3, 10) def A ( UpperCamelCase_ : Any=None , UpperCamelCase_ : List[Any]=None ) -> Optional[int]: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase_ ) @dataclass class A : snake_case__ :int snake_case__ :float snake_case__ :str snake_case__ :bool @dataclass class A : snake_case__ :int = 42 snake_case__ :str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :Optional[bool] = None class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'titi' snake_case__ :Optional[int] = 'toto' class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'titi' snake_case__ :str = 'toto' snake_case__ :int = 42 @dataclass class A : snake_case__ :BasicEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.foo ) @dataclass class A : snake_case__ :MixedTypeEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MixedTypeEnum(self.foo ) @dataclass class A : snake_case__ :Optional[int] = None snake_case__ :Optional[float] = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :Optional[str] = None snake_case__ :Optional[List[str]] = list_field(default=[] ) snake_case__ :Optional[List[int]] = list_field(default=[] ) @dataclass class A : snake_case__ :List[int] = list_field(default=[] ) snake_case__ :List[int] = list_field(default=[1, 2, 3] ) snake_case__ :List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) snake_case__ :List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A : snake_case__ :List[int] = field() snake_case__ :str = field() snake_case__ :BasicEnum = field() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.required_enum ) @dataclass class A : snake_case__ :int snake_case__ :"BasicEnum" = field() snake_case__ :"Optional[bool]" = None snake_case__ :"str" = field(default='toto' , metadata={'help': 'help message'} ) snake_case__ :"List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :bool | None = None @dataclass class A : snake_case__ :int | None = None snake_case__ :float | None = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :str | None = None snake_case__ :list[str] | None = list_field(default=[] ) snake_case__ :list[int] | None = list_field(default=[] ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : argparse.ArgumentParser , __magic_name__ : argparse.ArgumentParser ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , __magic_name__ ) and yy.get("choices" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](__magic_name__ ) , yy["type"](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--bar" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--baz" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--flag" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCAmelCase__) ,) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) expected.add_argument("--baz" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=__magic_name__ , dest="baz" ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) lowerCAmelCase__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" @dataclass class A : snake_case__ :Literal["titi", "toto", 42] = "toto" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) lowerCAmelCase__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--bar" , default=__magic_name__ , type=__magic_name__ , help="help message" ) expected.add_argument("--baz" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=__magic_name__ ) lowerCAmelCase__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) lowerCAmelCase__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--required_str" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCAmelCase__ = parser.parse_dict(__magic_name__ )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_json" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_yaml" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
48
1
'''simple docstring''' def A ( UpperCamelCase_ : int = 50 ) -> int: '''simple docstring''' lowerCAmelCase__ = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F"{solution() = }")
48
'''simple docstring''' import sys from collections import defaultdict class A : def __init__( self : Any ): """simple docstring""" lowerCAmelCase__ = [] def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[Any] ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = pos def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase__ = 2 * start + 1 else: lowerCAmelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase__ ,lowerCAmelCase__ = heap[smallest_child], positions[smallest_child] lowerCAmelCase__ ,lowerCAmelCase__ = ( heap[start], positions[start], ) lowerCAmelCase__ ,lowerCAmelCase__ = temp, tempa lowerCAmelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = position[index] while index != 0: lowerCAmelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase__ = heap[parent] lowerCAmelCase__ = position[parent] self.set_position(position[parent] , __magic_name__ ) else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , __magic_name__ ) break lowerCAmelCase__ = parent else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , 0 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = positions[0] lowerCAmelCase__ = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def A ( UpperCamelCase_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = Heap() lowerCAmelCase__ = [0] * len(UpperCamelCase_ ) lowerCAmelCase__ = [-1] * len(UpperCamelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase__ = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase__ = [] for vertex in range(len(UpperCamelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase_ ) heap.node_position.append(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = 1 lowerCAmelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase__ = 0 lowerCAmelCase__ = distance heap.heapify(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(1 , len(UpperCamelCase_ ) ): lowerCAmelCase__ = heap.delete_minimum(UpperCamelCase_ , UpperCamelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase_ )] ): lowerCAmelCase__ = distance heap.bottom_to_top( UpperCamelCase_ , heap.get_position(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ : Optional[int] = int(input("Enter number of edges: ").strip()) UpperCAmelCase__ : str = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
48
1
'''simple docstring''' import copy import random from transformers import CLIPTokenizer class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(*__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Dict , *__magic_name__ : List[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = super().add_tokens(__magic_name__ , *__magic_name__ , **__magic_name__ ) 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 __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Any , *__magic_name__ : Optional[Any] , __magic_name__ : Optional[int]=1 , **__magic_name__ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = [] if num_vec_per_token == 1: self.try_adding_tokens(__magic_name__ , *__magic_name__ , **__magic_name__ ) output.append(__magic_name__ ) else: lowerCAmelCase__ = [] for i in range(__magic_name__ ): lowerCAmelCase__ = placeholder_token + f"""_{i}""" self.try_adding_tokens(__magic_name__ , *__magic_name__ , **__magic_name__ ) output.append(__magic_name__ ) # 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""" ) lowerCAmelCase__ = output def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int]=False , __magic_name__ : List[str]=1.0 ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = [] for i in range(len(__magic_name__ ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=__magic_name__ ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: lowerCAmelCase__ = self.token_map[placeholder_token] lowerCAmelCase__ = tokens[: 1 + int(len(__magic_name__ ) * prop_tokens_to_load )] if vector_shuffle: lowerCAmelCase__ = copy.copy(__magic_name__ ) random.shuffle(__magic_name__ ) lowerCAmelCase__ = text.replace(__magic_name__ , " ".join(__magic_name__ ) ) return text def __call__( self : List[Any] , __magic_name__ : Union[str, Any] , *__magic_name__ : int , __magic_name__ : Union[str, Any]=False , __magic_name__ : Union[str, Any]=1.0 , **__magic_name__ : List[str] ): """simple docstring""" return super().__call__( self.replace_placeholder_tokens_in_text( __magic_name__ , vector_shuffle=__magic_name__ , prop_tokens_to_load=__magic_name__ ) , *__magic_name__ , **__magic_name__ , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Union[str, Any] , *__magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any]=False , __magic_name__ : Union[str, Any]=1.0 , **__magic_name__ : Any ): """simple docstring""" return super().encode( self.replace_placeholder_tokens_in_text( __magic_name__ , vector_shuffle=__magic_name__ , prop_tokens_to_load=__magic_name__ ) , *__magic_name__ , **__magic_name__ , )
48
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") if is_sentencepiece_available(): import sentencepiece as sp UpperCAmelCase__ : Tuple = 5 UpperCAmelCase__ : List[Any] = 10 @require_sentencepiece @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = SpeechaTextTokenizer snake_case__ :Dict = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().setUp() lowerCAmelCase__ = sp.SentencePieceProcessor() spm_model.Load(__magic_name__ ) lowerCAmelCase__ = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__magic_name__ ) , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [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 __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = 'valhalla/s2t_mustc_multilinguial_medium' snake_case__ :Tuple = 'C\'est trop cool' snake_case__ :List[str] = 'Esto es genial' @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) lowerCAmelCase__ = [ES_CODE, 4, 1601, 47, 7647, 2] lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = "fr" lowerCAmelCase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , __magic_name__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowerCAmelCase__ = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
48
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class A ( unittest.TestCase ): def __init__( self : List[Any] , __magic_name__ : List[str] , __magic_name__ : Dict=7 , __magic_name__ : int=3 , __magic_name__ : int=18 , __magic_name__ : Optional[Any]=30 , __magic_name__ : Tuple=400 , __magic_name__ : Dict=True , __magic_name__ : Dict=None , __magic_name__ : Tuple=True , __magic_name__ : int=None , ): """simple docstring""" lowerCAmelCase__ = size if size is not None else {"shortest_edge": 20} lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 18, "width": 18} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :List[str] = MobileNetVaImageProcessor if is_vision_available() else None def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = MobileNetVaImageProcessingTester(self ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , "do_resize" ) ) self.assertTrue(hasattr(__magic_name__ , "size" ) ) self.assertTrue(hasattr(__magic_name__ , "do_center_crop" ) ) self.assertTrue(hasattr(__magic_name__ , "crop_size" ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 20} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(__magic_name__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(__magic_name__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched lowerCAmelCase__ = image_processing(__magic_name__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
48
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCAmelCase__ : Tuple = logging.get_logger(__name__) # General docstring UpperCAmelCase__ : int = "RegNetConfig" # Base docstring UpperCAmelCase__ : Optional[int] = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[int] = [1, 10_88, 7, 7] # Image classification docstring UpperCAmelCase__ : Tuple = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[Any] = "tabby, tabby cat" UpperCAmelCase__ : int = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A ( tf.keras.layers.Layer ): def __init__( self : str , __magic_name__ : int , __magic_name__ : int = 3 , __magic_name__ : int = 1 , __magic_name__ : int = 1 , __magic_name__ : Optional[str] = "relu" , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=__magic_name__ , strides=__magic_name__ , padding="VALID" , groups=__magic_name__ , use_bias=__magic_name__ , name="convolution" , ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else tf.identity def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convolution(self.padding(__magic_name__ ) ) lowerCAmelCase__ = self.normalization(__magic_name__ ) lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : List[Any] , __magic_name__ : RegNetConfig , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config.num_channels lowerCAmelCase__ = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = shape_list(__magic_name__ )[1] if tf.executing_eagerly() and 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." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 2, 3, 1) ) lowerCAmelCase__ = self.embedder(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Any , __magic_name__ : int , __magic_name__ : int = 2 , **__magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=1 , strides=__magic_name__ , use_bias=__magic_name__ , name="convolution" ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : bool = False ): """simple docstring""" return self.normalization(self.convolution(__magic_name__ ) , training=__magic_name__ ) class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) lowerCAmelCase__ = [ tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.pooler(__magic_name__ ) for layer_module in self.attention: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = hidden_state * pooled return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.2" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(__magic_name__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.3" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 2 , __magic_name__ : int = 2 , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer lowerCAmelCase__ = [ # downsampling is done in the first layer with stride of 2 layer(__magic_name__ , __magic_name__ , __magic_name__ , stride=__magic_name__ , name="layers.0" ), *[layer(__magic_name__ , __magic_name__ , __magic_name__ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[str] ): """simple docstring""" for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __magic_name__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__magic_name__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__magic_name__ , __magic_name__ , __magic_name__ , depth=__magic_name__ , name=f"""stages.{i+1}""" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : tf.Tensor , __magic_name__ : bool = False , __magic_name__ : bool = True ): """simple docstring""" lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__magic_name__ ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__magic_name__ , hidden_states=__magic_name__ ) @keras_serializable class A ( tf.keras.layers.Layer ): snake_case__ :List[Any] = RegNetConfig def __init__( self : str , __magic_name__ : Union[str, Any] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config lowerCAmelCase__ = TFRegNetEmbeddings(__magic_name__ , name="embedder" ) lowerCAmelCase__ = TFRegNetEncoder(__magic_name__ , name="encoder" ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) @unpack_inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = self.encoder( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__magic_name__ ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ = tuple([tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__magic_name__ , pooler_output=__magic_name__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = RegNetConfig snake_case__ :Optional[Any] = 'regnet' snake_case__ :Tuple = 'pixel_values' @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} UpperCAmelCase__ : List[str] = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ : Tuple = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~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__ , ) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : RegNetConfig , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : int=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( pixel_values=__magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=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__ , ) class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , *__magic_name__ : Tuple , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) # classification head lowerCAmelCase__ = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : tf.Tensor = None , __magic_name__ : tf.Tensor = None , __magic_name__ : bool = None , __magic_name__ : bool = None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier[0](__magic_name__ ) lowerCAmelCase__ = self.classifier[1](__magic_name__ ) lowerCAmelCase__ = None if labels is None else self.hf_compute_loss(labels=__magic_name__ , logits=__magic_name__ ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__magic_name__ , logits=__magic_name__ , hidden_states=outputs.hidden_states )
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available UpperCAmelCase__ : Union[str, Any] = { "configuration_conditional_detr": [ "CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConditionalDetrConfig", "ConditionalDetrOnnxConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["ConditionalDetrFeatureExtractor"] UpperCAmelCase__ : Dict = ["ConditionalDetrImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = [ "CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST", "ConditionalDetrForObjectDetection", "ConditionalDetrForSegmentation", "ConditionalDetrModel", "ConditionalDetrPreTrainedModel", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys UpperCAmelCase__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def A ( UpperCamelCase_ : Tuple ) -> int: '''simple docstring''' for param in module.parameters(): lowerCAmelCase__ = False def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = datetime.now() lowerCAmelCase__ = current_time.strftime("%H:%M:%S" ) return timestamp
48
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class A ( metaclass=SCREAMING_SNAKE_CASE__ ): snake_case__ :int = ['onnx'] def __init__( self : Dict , *__magic_name__ : Optional[Any] , **__magic_name__ : Optional[Any] ): """simple docstring""" requires_backends(self , ["onnx"] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Union[str, Any] , *__magic_name__ : str , **__magic_name__ : List[str] ): """simple docstring""" requires_backends(cls , ["onnx"] ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] , *__magic_name__ : Any , **__magic_name__ : Union[str, Any] ): """simple docstring""" requires_backends(cls , ["onnx"] )
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ : List[Any] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
1
'''simple docstring''' import random def A ( UpperCamelCase_ : int ) -> bool: '''simple docstring''' lowerCAmelCase__ = num - 1 lowerCAmelCase__ = 0 while s % 2 == 0: lowerCAmelCase__ = s // 2 t += 1 for _ in range(5 ): lowerCAmelCase__ = random.randrange(2 , num - 1 ) lowerCAmelCase__ = pow(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if v != 1: lowerCAmelCase__ = 0 while v != (num - 1): if i == t - 1: return False else: lowerCAmelCase__ = i + 1 lowerCAmelCase__ = (v**2) % num return True def A ( UpperCamelCase_ : int ) -> bool: '''simple docstring''' if num < 2: return False lowerCAmelCase__ = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(UpperCamelCase_ ) def A ( UpperCamelCase_ : int = 10_24 ) -> int: '''simple docstring''' while True: lowerCAmelCase__ = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(UpperCamelCase_ ): return num if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
48
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = ['image_processor', 'tokenizer'] snake_case__ :List[Any] = 'ChineseCLIPImageProcessor' snake_case__ :Optional[int] = ('BertTokenizer', 'BertTokenizerFast') def __init__( self : Dict , __magic_name__ : List[str]=None , __magic_name__ : List[Any]=None , **__magic_name__ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __magic_name__ , ) lowerCAmelCase__ = kwargs.pop("feature_extractor" ) lowerCAmelCase__ = 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__(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = self.image_processor def __call__( self : List[Any] , __magic_name__ : Tuple=None , __magic_name__ : Any=None , __magic_name__ : str=None , **__magic_name__ : List[str] ): """simple docstring""" if text is None and images is None: raise ValueError("You have to specify either text or images. Both cannot be none." ) if text is not None: lowerCAmelCase__ = self.tokenizer(__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) if images is not None: lowerCAmelCase__ = self.image_processor(__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) if text is not None and images is not None: lowerCAmelCase__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__magic_name__ ) , tensor_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , *__magic_name__ : Union[str, Any] , **__magic_name__ : List[str] ): """simple docstring""" return self.tokenizer.batch_decode(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any , *__magic_name__ : str , **__magic_name__ : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*__magic_name__ , **__magic_name__ ) @property def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = self.tokenizer.model_input_names lowerCAmelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __magic_name__ , ) return self.image_processor_class
48
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A : def __init__( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : str=13 , __magic_name__ : List[str]=7 , __magic_name__ : Tuple=True , __magic_name__ : Tuple=True , __magic_name__ : str=True , __magic_name__ : int=True , __magic_name__ : int=99 , __magic_name__ : List[str]=[1, 1, 2] , __magic_name__ : Dict=1 , __magic_name__ : Tuple=32 , __magic_name__ : Any=4 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : List[str]=0.1 , __magic_name__ : Tuple=0.0 , __magic_name__ : int=512 , __magic_name__ : Optional[int]=3 , __magic_name__ : List[str]=0.02 , __magic_name__ : Dict=3 , __magic_name__ : List[Any]=4 , __magic_name__ : Any=None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = block_sizes lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = d_model lowerCAmelCase__ = n_head lowerCAmelCase__ = d_head lowerCAmelCase__ = d_inner lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = 2 lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope lowerCAmelCase__ = initializer_std # Used in the tests to check the size of the first attention layer lowerCAmelCase__ = n_head # Used in the tests to check the size of the first hidden state lowerCAmelCase__ = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCAmelCase__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCAmelCase__ = self.num_hidden_layers + 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForPreTraining(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForMaskedLM(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForSequenceClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : List[str] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = TFFunnelForMultipleChoice(config=__magic_name__ ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForTokenClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForQuestionAnswering(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) snake_case__ :Any = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) snake_case__ :str = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @require_tf class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) snake_case__ :int = False snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self , base=__magic_name__ ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__magic_name__ )
48
1
'''simple docstring''' import sys from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers UpperCAmelCase__ : int = "python tqdm regex requests packaging filelock numpy tokenizers".split() if sys.version_info < (3, 7): pkgs_to_check_at_runtime.append("dataclasses") if sys.version_info < (3, 8): pkgs_to_check_at_runtime.append("importlib_metadata") for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def A ( UpperCamelCase_ : str , UpperCamelCase_ : Dict=None ) -> int: '''simple docstring''' require_version(deps[pkg] , UpperCamelCase_ )
48
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
1
'''simple docstring''' import argparse import shutil from pathlib import Path from tqdm import tqdm from transformers import AutoTokenizer def A ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[Any]=10_24 ) -> Any: '''simple docstring''' lowerCAmelCase__ ,lowerCAmelCase__ = [], [] lowerCAmelCase__ = list(zip(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase__ ,lowerCAmelCase__ = sorted_examples[0] def is_too_big(UpperCamelCase_ : Union[str, Any] ): return tok(UpperCamelCase_ , return_tensors="pt" ).input_ids.shape[1] > max_tokens for src, tgt in tqdm(sorted_examples[1:] ): lowerCAmelCase__ = new_src + " " + src lowerCAmelCase__ = new_tgt + " " + tgt if is_too_big(UpperCamelCase_ ) or is_too_big(UpperCamelCase_ ): # cant fit, finalize example finished_src.append(UpperCamelCase_ ) finished_tgt.append(UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = src, tgt else: # can fit, keep adding lowerCAmelCase__ ,lowerCAmelCase__ = cand_src, cand_tgt # cleanup if new_src: assert new_tgt finished_src.append(UpperCamelCase_ ) finished_tgt.append(UpperCamelCase_ ) return finished_src, finished_tgt def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Path , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int] ) -> List[str]: '''simple docstring''' lowerCAmelCase__ = Path(UpperCamelCase_ ) save_path.mkdir(exist_ok=UpperCamelCase_ ) for split in ["train"]: lowerCAmelCase__ ,lowerCAmelCase__ = data_dir / F"""{split}.source""", data_dir / F"""{split}.target""" lowerCAmelCase__ = [x.rstrip() for x in Path(UpperCamelCase_ ).open().readlines()] lowerCAmelCase__ = [x.rstrip() for x in Path(UpperCamelCase_ ).open().readlines()] lowerCAmelCase__ ,lowerCAmelCase__ = pack_examples(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) print(F"""packed {split} split from {len(UpperCamelCase_ )} examples -> {len(UpperCamelCase_ )}.""" ) Path(save_path / F"""{split}.source""" ).open("w" ).write("\n".join(UpperCamelCase_ ) ) Path(save_path / F"""{split}.target""" ).open("w" ).write("\n".join(UpperCamelCase_ ) ) for split in ["val", "test"]: lowerCAmelCase__ ,lowerCAmelCase__ = data_dir / F"""{split}.source""", data_dir / F"""{split}.target""" shutil.copyfile(UpperCamelCase_ , save_path / F"""{split}.source""" ) shutil.copyfile(UpperCamelCase_ , save_path / F"""{split}.target""" ) def A ( ) -> int: '''simple docstring''' lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument("--tok_name" , type=UpperCamelCase_ , help="like facebook/bart-large-cnn,t5-base, etc." ) parser.add_argument("--max_seq_len" , type=UpperCamelCase_ , default=1_28 ) parser.add_argument("--data_dir" , type=UpperCamelCase_ ) parser.add_argument("--save_path" , type=UpperCamelCase_ ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = AutoTokenizer.from_pretrained(args.tok_name ) return pack_data_dir(UpperCamelCase_ , Path(args.data_dir ) , args.max_seq_len , args.save_path ) if __name__ == "__main__": packer_cli()
48
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : str , __magic_name__ : float ): """simple docstring""" if nodea not in self.connections: self.add_node(__magic_name__ ) if nodea not in self.connections: self.add_node(__magic_name__ ) lowerCAmelCase__ = probability def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return list(self.connections ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[tuple[str, str, float]] , UpperCamelCase_ : int ) -> dict[str, int]: '''simple docstring''' lowerCAmelCase__ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = Counter(graph.get_nodes() ) lowerCAmelCase__ = start for _ in range(UpperCamelCase_ ): lowerCAmelCase__ = graph.transition(UpperCamelCase_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask UpperCAmelCase__ : Union[str, Any] = logging.getLogger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Optional[Any] , __magic_name__ : Dict=-1 ): """simple docstring""" lowerCAmelCase__ = label_idx def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Union[Split, str] ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = mode.value lowerCAmelCase__ = os.path.join(__magic_name__ , f"""{mode}.txt""" ) lowerCAmelCase__ = 1 lowerCAmelCase__ = [] with open(__magic_name__ , encoding="utf-8" ) as f: lowerCAmelCase__ = [] lowerCAmelCase__ = [] for line in f: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"""{mode}-{guid_index}""" , words=__magic_name__ , labels=__magic_name__ ) ) guid_index += 1 lowerCAmelCase__ = [] lowerCAmelCase__ = [] else: lowerCAmelCase__ = line.split(" " ) words.append(splits[0] ) if len(__magic_name__ ) > 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=__magic_name__ , labels=__magic_name__ ) ) return examples def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : TextIO , __magic_name__ : TextIO , __magic_name__ : List ): """simple docstring""" lowerCAmelCase__ = 0 for line in test_input_reader: if line.startswith("-DOCSTART-" ) or line == "" or line == "\n": writer.write(__magic_name__ ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowerCAmelCase__ = line.split()[0] + " " + preds_list[example_id].pop(0 ) + "\n" writer.write(__magic_name__ ) else: logger.warning("Maximum sequence length exceeded: No prediction for '%s'." , line.split()[0] ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : str ): """simple docstring""" if path: with open(__magic_name__ , "r" ) as f: lowerCAmelCase__ = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ = ["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 ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Optional[int] ): """simple docstring""" super().__init__(label_idx=-2 ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" if path: with open(__magic_name__ , "r" ) as f: lowerCAmelCase__ = f.read().splitlines() if "O" not in labels: lowerCAmelCase__ = ["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 ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Union[Split, str] ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = mode.value lowerCAmelCase__ = os.path.join(__magic_name__ , f"""{mode}.txt""" ) lowerCAmelCase__ = 1 lowerCAmelCase__ = [] with open(__magic_name__ , encoding="utf-8" ) as f: for sentence in parse_incr(__magic_name__ ): lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in sentence: words.append(token["form"] ) labels.append(token["upos"] ) assert len(__magic_name__ ) == len(__magic_name__ ) if words: examples.append(InputExample(guid=f"""{mode}-{guid_index}""" , words=__magic_name__ , labels=__magic_name__ ) ) guid_index += 1 return examples def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : TextIO , __magic_name__ : TextIO , __magic_name__ : List ): """simple docstring""" lowerCAmelCase__ = 0 for sentence in parse_incr(__magic_name__ ): lowerCAmelCase__ = preds_list[example_id] lowerCAmelCase__ = "" for token in sentence: out += f"""{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) """ out += "\n" writer.write(__magic_name__ ) example_id += 1 def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" if path: with open(__magic_name__ , "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", ]
48
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
1
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py UpperCAmelCase__ : List[Any] = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. UpperCAmelCase__ : Dict = direct_transformers_import(PATH_TO_TRANSFORMERS) UpperCAmelCase__ : Optional[int] = transformers.models.auto.configuration_auto.CONFIG_MAPPING UpperCAmelCase__ : Dict = { # used to compute the property `self.chunk_length` "EncodecConfig": ["overlap"], # used as `self.bert_model = BertModel(config, ...)` "DPRConfig": True, # not used in modeling files, but it's an important information "FSMTConfig": ["langs"], # used internally in the configuration class file "GPTNeoConfig": ["attention_types"], # used internally in the configuration class file "EsmConfig": ["is_folding_model"], # used during training (despite we don't have training script for these models yet) "Mask2FormerConfig": ["ignore_value"], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) "OneFormerConfig": ["ignore_value", "norm"], # used during preprocessing and collation, see `collating_graphormer.py` "GraphormerConfig": ["spatial_pos_max"], # used internally in the configuration class file "T5Config": ["feed_forward_proj"], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally "MT5Config": ["feed_forward_proj", "tokenizer_class"], "UMT5Config": ["feed_forward_proj", "tokenizer_class"], # used internally in the configuration class file "LongT5Config": ["feed_forward_proj"], # used internally in the configuration class file "SwitchTransformersConfig": ["feed_forward_proj"], # having default values other than `1e-5` - we can't fix them without breaking "BioGptConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "GLPNConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "SegformerConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "CvtConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "PerceiverConfig": ["layer_norm_eps"], # used internally to calculate the feature size "InformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "AutoformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate `mlp_dim` "SamVisionConfig": ["mlp_ratio"], # For (head) training, but so far not implemented "ClapAudioConfig": ["num_classes"], # Not used, but providing useful information to users "SpeechT5HifiGanConfig": ["sampling_rate"], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { "CLIPSegConfig": True, "DeformableDetrConfig": True, "DetaConfig": True, "DinatConfig": True, "DonutSwinConfig": True, "EfficientFormerConfig": True, "FSMTConfig": True, "JukeboxConfig": True, "LayoutLMv2Config": True, "MaskFormerSwinConfig": True, "MT5Config": True, "NatConfig": True, "OneFormerConfig": True, "PerceiverConfig": True, "RagConfig": True, "SpeechT5Config": True, "SwinConfig": True, "Swin2SRConfig": True, "Swinv2Config": True, "SwitchTransformersConfig": True, "TableTransformerConfig": True, "TapasConfig": True, "TransfoXLConfig": True, "UniSpeechConfig": True, "UniSpeechSatConfig": True, "WavLMConfig": True, "WhisperConfig": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) "JukeboxPriorConfig": True, # TODO: @Younes (for `is_decoder`) "Pix2StructTextConfig": True, } ) def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F"""config.{attribute}""" in modeling_source or F"""getattr(config, \"{attribute}\"""" in modeling_source or F"""getattr(self.config, \"{attribute}\"""" in modeling_source ): lowerCAmelCase__ = True # Deal with multi-line cases elif ( re.search( rF"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , UpperCamelCase_ , ) is not None ): lowerCAmelCase__ = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: lowerCAmelCase__ = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files lowerCAmelCase__ = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] lowerCAmelCase__ = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed lowerCAmelCase__ = True if not attribute_used: lowerCAmelCase__ = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: lowerCAmelCase__ = True elif attribute in ["tie_word_embeddings"] and default_value is False: lowerCAmelCase__ = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: lowerCAmelCase__ = True elif attribute.endswith("_token_id" ): lowerCAmelCase__ = True # configuration class specific cases if not case_allowed: lowerCAmelCase__ = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) lowerCAmelCase__ = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def A ( UpperCamelCase_ : str ) -> Dict: '''simple docstring''' lowerCAmelCase__ = dict(inspect.signature(config_class.__init__ ).parameters ) lowerCAmelCase__ = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] lowerCAmelCase__ = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass lowerCAmelCase__ = {} if len(config_class.attribute_map ) > 0: lowerCAmelCase__ = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files lowerCAmelCase__ = inspect.getsourcefile(UpperCamelCase_ ) lowerCAmelCase__ = os.path.dirname(UpperCamelCase_ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. lowerCAmelCase__ = [os.path.join(UpperCamelCase_ , UpperCamelCase_ ) for fn in os.listdir(UpperCamelCase_ ) if fn.startswith("modeling_" )] # Get the source code strings lowerCAmelCase__ = [] for path in modeling_paths: if os.path.isfile(UpperCamelCase_ ): with open(UpperCamelCase_ ) as fp: modeling_sources.append(fp.read() ) lowerCAmelCase__ = [] for config_param, default_value in zip(UpperCamelCase_ , UpperCamelCase_ ): # `attributes` here is all the variant names for `config_param` lowerCAmelCase__ = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): unused_attributes.append(attributes[0] ) return sorted(UpperCamelCase_ ) def A ( ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) lowerCAmelCase__ = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda UpperCamelCase_ : inspect.isclass(UpperCamelCase_ ) and issubclass(UpperCamelCase_ , UpperCamelCase_ ) and inspect.getmodule(UpperCamelCase_ ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: lowerCAmelCase__ = check_config_attributes_being_used(UpperCamelCase_ ) if len(UpperCamelCase_ ) > 0: lowerCAmelCase__ = unused_attributes if len(UpperCamelCase_ ) > 0: lowerCAmelCase__ = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += F"""{name}: {attributes}\n""" raise ValueError(UpperCamelCase_ ) if __name__ == "__main__": check_config_attributes()
48
'''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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase__ : int = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'facebook/nllb-200-distilled-600M' snake_case__ :Optional[Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) snake_case__ :List[Any] = 'translator' snake_case__ :List[Any] = AutoTokenizer snake_case__ :Optional[Any] = AutoModelForSeqaSeqLM snake_case__ :List[str] = LANGUAGE_CODES snake_case__ :List[Any] = ['text', 'text', 'text'] snake_case__ :List[Any] = ['text'] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ): """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __magic_name__ , return_tensors="pt" , src_lang=__magic_name__ , tgt_lang=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__magic_name__ )
48
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} # See all BART models at https://huggingface.co/models?filter=bart UpperCAmelCase__ : Optional[int] = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, "tokenizer_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json", }, } UpperCAmelCase__ : int = { "facebook/bart-base": 10_24, "facebook/bart-large": 10_24, "facebook/bart-large-mnli": 10_24, "facebook/bart-large-cnn": 10_24, "facebook/bart-large-xsum": 10_24, "yjernite/bart_eli5": 10_24, } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ :int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :List[Any] = ['input_ids', 'attention_mask'] snake_case__ :Union[str, Any] = BartTokenizer def __init__( self : List[str] , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Tuple=None , __magic_name__ : List[Any]="replace" , __magic_name__ : Union[str, Any]="<s>" , __magic_name__ : Optional[int]="</s>" , __magic_name__ : Dict="</s>" , __magic_name__ : Union[str, Any]="<s>" , __magic_name__ : Optional[int]="<unk>" , __magic_name__ : str="<pad>" , __magic_name__ : Dict="<mask>" , __magic_name__ : Optional[int]=False , __magic_name__ : str=True , **__magic_name__ : Optional[Any] , ): """simple docstring""" super().__init__( __magic_name__ , __magic_name__ , tokenizer_file=__magic_name__ , errors=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , add_prefix_space=__magic_name__ , trim_offsets=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , __magic_name__ ) != add_prefix_space: lowerCAmelCase__ = getattr(__magic_name__ , pre_tok_state.pop("type" ) ) lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = pre_tok_class(**__magic_name__ ) lowerCAmelCase__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` lowerCAmelCase__ = "post_processor" lowerCAmelCase__ = getattr(self.backend_tokenizer , __magic_name__ , __magic_name__ ) if tokenizer_component_instance: lowerCAmelCase__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowerCAmelCase__ = tuple(state["sep"] ) if "cls" in state: lowerCAmelCase__ = tuple(state["cls"] ) lowerCAmelCase__ = False if state.get("add_prefix_space" , __magic_name__ ) != add_prefix_space: lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = True if state.get("trim_offsets" , __magic_name__ ) != trim_offsets: lowerCAmelCase__ = trim_offsets lowerCAmelCase__ = True if changes_to_apply: lowerCAmelCase__ = getattr(__magic_name__ , state.pop("type" ) ) lowerCAmelCase__ = component_class(**__magic_name__ ) setattr(self.backend_tokenizer , __magic_name__ , __magic_name__ ) @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else value lowerCAmelCase__ = value def __SCREAMING_SNAKE_CASE ( self : str , *__magic_name__ : List[Any] , **__magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = kwargs.get("is_split_into_words" , __magic_name__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , *__magic_name__ : Any , **__magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = kwargs.get("is_split_into_words" , __magic_name__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" lowerCAmelCase__ = self._tokenizer.model.save(__magic_name__ , name=__magic_name__ ) return tuple(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Any , __magic_name__ : int=None ): """simple docstring""" lowerCAmelCase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
48
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'timm_backbone' def __init__( self : Tuple , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=3 , __magic_name__ : Dict=True , __magic_name__ : str=True , __magic_name__ : List[Any]=None , **__magic_name__ : Tuple , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = backbone lowerCAmelCase__ = num_channels lowerCAmelCase__ = features_only lowerCAmelCase__ = use_pretrained_backbone lowerCAmelCase__ = True lowerCAmelCase__ = out_indices if out_indices is not None else (-1,)
48
1
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
'''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. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'Salesforce/blip-image-captioning-base' snake_case__ :List[Any] = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case__ :List[Any] = 'image_captioner' snake_case__ :Optional[int] = AutoModelForVisionaSeq snake_case__ :Optional[int] = ['image'] snake_case__ :Any = ['text'] def __init__( self : str , *__magic_name__ : List[str] , **__magic_name__ : Tuple ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : "Image" ): """simple docstring""" return self.pre_processor(images=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Optional[int] ): """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0].strip()
48
1
'''simple docstring''' from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) @add_end_docstrings( SCREAMING_SNAKE_CASE__ , r'\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n ' , ) class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : GenericTensor ): """simple docstring""" if self.framework == "tf": lowerCAmelCase__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": lowerCAmelCase__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__magic_name__ ) else: raise ValueError("Unsupported framework" ) return masked_index def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : GenericTensor ): """simple docstring""" lowerCAmelCase__ = self.get_masked_index(__magic_name__ ) lowerCAmelCase__ = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , f"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : GenericTensor ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Dict , __magic_name__ : Any=None , **__magic_name__ : Union[str, Any] ): """simple docstring""" if return_tensors is None: lowerCAmelCase__ = self.framework lowerCAmelCase__ = self.tokenizer(__magic_name__ , return_tensors=__magic_name__ ) self.ensure_exactly_one_mask_token(__magic_name__ ) return model_inputs def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model(**__magic_name__ ) lowerCAmelCase__ = model_inputs["input_ids"] return model_outputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : str=5 , __magic_name__ : Any=None ): """simple docstring""" if target_ids is not None and target_ids.shape[0] < top_k: lowerCAmelCase__ = target_ids.shape[0] lowerCAmelCase__ = model_outputs["input_ids"][0] lowerCAmelCase__ = model_outputs["logits"] if self.framework == "tf": lowerCAmelCase__ = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] lowerCAmelCase__ = outputs.numpy() lowerCAmelCase__ = outputs[0, masked_index, :] lowerCAmelCase__ = stable_softmax(__magic_name__ , axis=-1 ) if target_ids is not None: lowerCAmelCase__ = tf.gather_nd(tf.squeeze(__magic_name__ , 0 ) , target_ids.reshape(-1 , 1 ) ) lowerCAmelCase__ = tf.expand_dims(__magic_name__ , 0 ) lowerCAmelCase__ = tf.math.top_k(__magic_name__ , k=__magic_name__ ) lowerCAmelCase__ ,lowerCAmelCase__ = topk.values.numpy(), topk.indices.numpy() else: lowerCAmelCase__ = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=__magic_name__ ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample lowerCAmelCase__ = outputs[0, masked_index, :] lowerCAmelCase__ = logits.softmax(dim=-1 ) if target_ids is not None: lowerCAmelCase__ = probs[..., target_ids] lowerCAmelCase__ ,lowerCAmelCase__ = probs.topk(__magic_name__ ) lowerCAmelCase__ = [] lowerCAmelCase__ = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): lowerCAmelCase__ = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place lowerCAmelCase__ = input_ids.numpy().copy() if target_ids is not None: lowerCAmelCase__ = target_ids[p].tolist() lowerCAmelCase__ = p # Filter padding out: lowerCAmelCase__ = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(__magic_name__ ) result.append(__magic_name__ ) if single_mask: return result[0] return result def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Tuple , __magic_name__ : int=None ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = [targets] try: lowerCAmelCase__ = self.tokenizer.get_vocab() except Exception: lowerCAmelCase__ = {} lowerCAmelCase__ = [] for target in targets: lowerCAmelCase__ = vocab.get(__magic_name__ , __magic_name__ ) if id_ is None: lowerCAmelCase__ = self.tokenizer( __magic_name__ , add_special_tokens=__magic_name__ , return_attention_mask=__magic_name__ , return_token_type_ids=__magic_name__ , max_length=1 , truncation=__magic_name__ , )["input_ids"] if len(__magic_name__ ) == 0: logger.warning( f"""The specified target token `{target}` does not exist in the model vocabulary. """ "We cannot replace it with anything meaningful, ignoring it" ) continue lowerCAmelCase__ = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f"""The specified target token `{target}` does not exist in the model vocabulary. """ f"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" ) target_ids.append(id_ ) lowerCAmelCase__ = list(set(__magic_name__ ) ) if len(__magic_name__ ) == 0: raise ValueError("At least one target must be provided when passed." ) lowerCAmelCase__ = np.array(__magic_name__ ) return target_ids def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str=None , __magic_name__ : int=None ): """simple docstring""" lowerCAmelCase__ = {} if targets is not None: lowerCAmelCase__ = self.get_target_ids(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = target_ids if top_k is not None: lowerCAmelCase__ = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : List[str] , __magic_name__ : List[str] , *__magic_name__ : Any , **__magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = super().__call__(__magic_name__ , **__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) and len(__magic_name__ ) == 1: return outputs[0] return outputs
48
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = "▁" UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model"} UpperCAmelCase__ : Union[str, Any] = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } UpperCAmelCase__ : Optional[Any] = { "facebook/mbart-large-50-one-to-many-mmt": 10_24, } # fmt: off UpperCAmelCase__ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Any = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : int , __magic_name__ : int , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]="</s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : List[Any]="<s>" , __magic_name__ : Tuple="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : List[Any]="<mask>" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__magic_name__ , tgt_lang=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__magic_name__ ) ) lowerCAmelCase__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__magic_name__ ) } lowerCAmelCase__ = {v: k for k, v in self.lang_code_to_id.items()} lowerCAmelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowerCAmelCase__ = src_lang if src_lang is not None else "en_XX" lowerCAmelCase__ = self.lang_code_to_id[self._src_lang] lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : List[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str ): """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(__magic_name__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = 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(__magic_name__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(__magic_name__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) lowerCAmelCase__ = [1] * len(self.prefix_tokens ) lowerCAmelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__magic_name__ )) + suffix_ones return prefix_ones + ([0] * len(__magic_name__ )) + ([0] * len(__magic_name__ )) + suffix_ones def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str = "en_XX" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "ro_RO" , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[src_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[tgt_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id]
48
1
'''simple docstring''' from typing import Any, Dict, List, Optional, Tuple, Union import torch from torch import nn from torch.utils.data import DistributedSampler, RandomSampler from transformers import PreTrainedModel, Trainer, logging from transformers.integrations import is_fairscale_available from transformers.models.fsmt.configuration_fsmt import FSMTConfig from transformers.optimization import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) from transformers.trainer_pt_utils import get_tpu_sampler from transformers.training_args import ParallelMode from transformers.utils import is_torch_tpu_available if is_fairscale_available(): from fairscale.optim import OSS UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = { "linear": get_linear_schedule_with_warmup, "cosine": get_cosine_schedule_with_warmup, "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup, "polynomial": get_polynomial_decay_schedule_with_warmup, "constant": get_constant_schedule, "constant_w_warmup": get_constant_schedule_with_warmup, } class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : str , __magic_name__ : int=None , __magic_name__ : Optional[int]=None , *__magic_name__ : Union[str, Any] , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(*__magic_name__ , **__magic_name__ ) if config is None: assert isinstance(self.model , __magic_name__ ), ( "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is" f""" {self.model.__class__}""" ) lowerCAmelCase__ = self.model.config else: lowerCAmelCase__ = config lowerCAmelCase__ = data_args lowerCAmelCase__ = self.config.tgt_vocab_size if isinstance(self.config , __magic_name__ ) else self.config.vocab_size if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss): assert self.config.pad_token_id is not None, ( "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss" " calculation or doing label smoothing." ) if self.config.pad_token_id is None and self.config.eos_token_id is not None: logger.warning( f"""The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for""" " padding.." ) if self.args.label_smoothing == 0: lowerCAmelCase__ = torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id ) else: # dynamically import label_smoothed_nll_loss from utils import label_smoothed_nll_loss lowerCAmelCase__ = label_smoothed_nll_loss def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int ): """simple docstring""" if self.optimizer is None: lowerCAmelCase__ = ["bias", "LayerNorm.weight"] lowerCAmelCase__ = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay )], "weight_decay": self.args.weight_decay, }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay )], "weight_decay": 0.0, }, ] lowerCAmelCase__ = Adafactor if self.args.adafactor else AdamW if self.args.adafactor: lowerCAmelCase__ = Adafactor lowerCAmelCase__ = {"scale_parameter": False, "relative_step": False} else: lowerCAmelCase__ = AdamW lowerCAmelCase__ = { "betas": (self.args.adam_betaa, self.args.adam_betaa), "eps": self.args.adam_epsilon, } lowerCAmelCase__ = self.args.learning_rate if self.sharded_ddp: lowerCAmelCase__ = OSS( params=__magic_name__ , optim=__magic_name__ , **__magic_name__ , ) else: lowerCAmelCase__ = optimizer_cls(__magic_name__ , **__magic_name__ ) if self.lr_scheduler is None: lowerCAmelCase__ = self._get_lr_scheduler(__magic_name__ ) else: # ignoring --lr_scheduler logger.warning("scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored." ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = arg_to_scheduler[self.args.lr_scheduler] if self.args.lr_scheduler == "constant": lowerCAmelCase__ = schedule_func(self.optimizer ) elif self.args.lr_scheduler == "constant_w_warmup": lowerCAmelCase__ = schedule_func(self.optimizer , num_warmup_steps=self.args.warmup_steps ) else: lowerCAmelCase__ = schedule_func( self.optimizer , num_warmup_steps=self.args.warmup_steps , num_training_steps=__magic_name__ ) return scheduler def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" if isinstance(self.train_dataset , torch.utils.data.IterableDataset ): return None elif is_torch_tpu_available(): return get_tpu_sampler(self.train_dataset ) else: if self.args.sortish_sampler: self.train_dataset.make_sortish_sampler( self.args.per_device_train_batch_size , distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED) , ) return ( RandomSampler(self.train_dataset ) if self.args.local_rank == -1 else DistributedSampler(self.train_dataset ) ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any ): """simple docstring""" if self.args.label_smoothing == 0: if self.data_args is not None and self.data_args.ignore_pad_token_for_loss: # force training to ignore pad token lowerCAmelCase__ = model(**__magic_name__ , use_cache=__magic_name__ )[0] lowerCAmelCase__ = self.loss_fn(logits.view(-1 , logits.shape[-1] ) , labels.view(-1 ) ) else: # compute usual loss via models lowerCAmelCase__ ,lowerCAmelCase__ = model(**__magic_name__ , labels=__magic_name__ , use_cache=__magic_name__ )[:2] else: # compute label smoothed loss lowerCAmelCase__ = model(**__magic_name__ , use_cache=__magic_name__ )[0] lowerCAmelCase__ = torch.nn.functional.log_softmax(__magic_name__ , dim=-1 ) lowerCAmelCase__ ,lowerCAmelCase__ = self.loss_fn(__magic_name__ , __magic_name__ , self.args.label_smoothing , ignore_index=self.config.pad_token_id ) return loss, logits def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = inputs.pop("labels" ) lowerCAmelCase__ ,lowerCAmelCase__ = self._compute_loss(__magic_name__ , __magic_name__ , __magic_name__ ) return loss def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : nn.Module , __magic_name__ : Dict[str, Union[torch.Tensor, Any]] , __magic_name__ : bool , __magic_name__ : Optional[List[str]] = None , ): """simple docstring""" lowerCAmelCase__ = self._prepare_inputs(__magic_name__ ) lowerCAmelCase__ = { "max_length": self.data_args.val_max_target_length if self.data_args is not None else self.config.max_length, "num_beams": self.data_args.eval_beams if self.data_args is not None else self.config.num_beams, } if self.args.predict_with_generate and not self.args.prediction_loss_only: lowerCAmelCase__ = self.model.generate( inputs["input_ids"] , attention_mask=inputs["attention_mask"] , **__magic_name__ , ) # in case the batch is shorter than max length, the output should be padded if generated_tokens.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase__ = self._pad_tensors_to_max_len(__magic_name__ , gen_kwargs["max_length"] ) lowerCAmelCase__ = inputs.pop("labels" ) with torch.no_grad(): # compute loss on predict data lowerCAmelCase__ ,lowerCAmelCase__ = self._compute_loss(__magic_name__ , __magic_name__ , __magic_name__ ) lowerCAmelCase__ = loss.mean().detach() if self.args.prediction_loss_only: return (loss, None, None) lowerCAmelCase__ = generated_tokens if self.args.predict_with_generate else logits if labels.shape[-1] < gen_kwargs["max_length"]: lowerCAmelCase__ = self._pad_tensors_to_max_len(__magic_name__ , gen_kwargs["max_length"] ) return (loss, logits, labels) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int , __magic_name__ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id if pad_token_id is None: raise ValueError( "Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be" f""" padded to `max_length`={max_length}""" ) lowerCAmelCase__ = pad_token_id * torch.ones( (tensor.shape[0], max_length) , dtype=tensor.dtype , device=tensor.device ) lowerCAmelCase__ = tensor return padded_tensor
48
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _in_place_partition(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) count += _in_place_quick_sort(UpperCamelCase_ , UpperCamelCase_ , p - 1 ) count += _in_place_quick_sort(UpperCamelCase_ , p + 1 , UpperCamelCase_ ) return count def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = start - 1 for index in range(UpperCamelCase_ , UpperCamelCase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class A ( unittest.TestCase ): @slow def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = XLMRobertaModel.from_pretrained("xlm-roberta-base" ) lowerCAmelCase__ = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]] ) # The dog is cute and lives in the garden house lowerCAmelCase__ = torch.Size((1, 12, 768) ) # batch_size, sequence_length, embedding_vector_dim lowerCAmelCase__ = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowerCAmelCase__ = model(__magic_name__ )["last_hidden_state"].detach() self.assertEqual(output.shape , __magic_name__ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __magic_name__ , atol=1E-3 ) ) @slow def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = XLMRobertaModel.from_pretrained("xlm-roberta-large" ) lowerCAmelCase__ = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]] ) # The dog is cute and lives in the garden house lowerCAmelCase__ = torch.Size((1, 12, 1024) ) # batch_size, sequence_length, embedding_vector_dim lowerCAmelCase__ = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): lowerCAmelCase__ = model(__magic_name__ )["last_hidden_state"].detach() self.assertEqual(output.shape , __magic_name__ ) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1] , __magic_name__ , atol=1E-3 ) )
48
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def A ( UpperCamelCase_ : List[Any] ) -> Tuple: '''simple docstring''' if "img_encoder.pos_embed" in name: lowerCAmelCase__ = name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: lowerCAmelCase__ = name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: lowerCAmelCase__ = name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCAmelCase__ = name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: lowerCAmelCase__ = name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: lowerCAmelCase__ = name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: lowerCAmelCase__ = name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: lowerCAmelCase__ = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: lowerCAmelCase__ = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: lowerCAmelCase__ = name.replace("c_fc" , "fc1" ) if "c_proj" in name: lowerCAmelCase__ = name.replace("c_proj" , "fc2" ) if "text_encoder" in name: lowerCAmelCase__ = name.replace("text_encoder" , "text_model" ) if "ln_final" in name: lowerCAmelCase__ = name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: lowerCAmelCase__ = name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: lowerCAmelCase__ = name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: lowerCAmelCase__ = name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: lowerCAmelCase__ = name.replace("text_projector.linear_out" , "text_projection.3" ) return name def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> List[Any]: '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCAmelCase__ = orig_state_dict.pop(UpperCamelCase_ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ ,lowerCAmelCase__ = int(key_split[2] ), int(key_split[4] ) lowerCAmelCase__ = config.vision_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ = int(key_split[3] ) lowerCAmelCase__ = config.text_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[ dim : dim * 2, : ] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] else: lowerCAmelCase__ = rename_key(UpperCamelCase_ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCAmelCase__ = val.squeeze_() else: lowerCAmelCase__ = val return orig_state_dict def A ( ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple="groupvit-gcc-yfcc" , UpperCamelCase_ : Dict=False ) -> Any: '''simple docstring''' lowerCAmelCase__ = GroupViTConfig() lowerCAmelCase__ = GroupViTModel(UpperCamelCase_ ).eval() lowerCAmelCase__ = torch.load(UpperCamelCase_ , map_location="cpu" )["model"] lowerCAmelCase__ = convert_state_dict(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(UpperCamelCase_ ) == 0) # verify result lowerCAmelCase__ = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = processor(text=["a photo of a cat", "a photo of a dog"] , images=UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors="pt" ) with torch.no_grad(): lowerCAmelCase__ = model(**UpperCamelCase_ ) if model_name == "groupvit-gcc-yfcc": lowerCAmelCase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowerCAmelCase__ = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(F"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image , UpperCamelCase_ , atol=1E-3 ) processor.save_pretrained(UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) print("Successfully saved processor and model to" , UpperCamelCase_ ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(UpperCamelCase_ , organization="nielsr" ) model.push_to_hub(UpperCamelCase_ , organization="nielsr" ) if __name__ == "__main__": UpperCAmelCase__ : List[str] = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) UpperCAmelCase__ : Any = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ : Optional[Any] = 1_00 UpperCAmelCase__ : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def A ( UpperCamelCase_ : int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} lowerCAmelCase__ = set() lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A ( UpperCamelCase_ : int = 50_00 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , UpperCamelCase_ ): if len(partition(UpperCamelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
48
1
'''simple docstring''' from typing import Callable, List, Optional, Tuple, Union import torch from transformers import CLIPTextModel, CLIPTokenizer from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin, TransformeraDModel, VQModel from ...schedulers import VQDiffusionScheduler from ...utils import logging from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): @register_to_config def __init__( self : str , __magic_name__ : bool , __magic_name__ : Optional[int] = None , __magic_name__ : Optional[int] = None ): """simple docstring""" super().__init__() lowerCAmelCase__ = learnable if self.learnable: assert hidden_size is not None, "learnable=True requires `hidden_size` to be set" assert length is not None, "learnable=True requires `length` to be set" lowerCAmelCase__ = torch.zeros(__magic_name__ , __magic_name__ ) else: lowerCAmelCase__ = None lowerCAmelCase__ = torch.nn.Parameter(__magic_name__ ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :VQModel snake_case__ :CLIPTextModel snake_case__ :CLIPTokenizer snake_case__ :TransformeraDModel snake_case__ :LearnedClassifierFreeSamplingEmbeddings snake_case__ :VQDiffusionScheduler def __init__( self : Union[str, Any] , __magic_name__ : VQModel , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : TransformeraDModel , __magic_name__ : VQDiffusionScheduler , __magic_name__ : LearnedClassifierFreeSamplingEmbeddings , ): """simple docstring""" super().__init__() self.register_modules( vqvae=__magic_name__ , transformer=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , scheduler=__magic_name__ , learned_classifier_free_sampling_embeddings=__magic_name__ , ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else 1 # get prompt text embeddings lowerCAmelCase__ = self.tokenizer( __magic_name__ , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) lowerCAmelCase__ = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: lowerCAmelCase__ = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" f""" {self.tokenizer.model_max_length} tokens: {removed_text}""" ) lowerCAmelCase__ = text_input_ids[:, : self.tokenizer.model_max_length] lowerCAmelCase__ = self.text_encoder(text_input_ids.to(self.device ) )[0] # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion. # While CLIP does normalize the pooled output of the text transformer when combining # the image and text embeddings, CLIP does not directly normalize the last hidden state. # # CLIP normalizing the pooled output. # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053 lowerCAmelCase__ = prompt_embeds / prompt_embeds.norm(dim=-1 , keepdim=__magic_name__ ) # duplicate text embeddings for each generation per prompt lowerCAmelCase__ = prompt_embeds.repeat_interleave(__magic_name__ , dim=0 ) if do_classifier_free_guidance: if self.learned_classifier_free_sampling_embeddings.learnable: lowerCAmelCase__ = self.learned_classifier_free_sampling_embeddings.embeddings lowerCAmelCase__ = negative_prompt_embeds.unsqueeze(0 ).repeat(__magic_name__ , 1 , 1 ) else: lowerCAmelCase__ = [""] * batch_size lowerCAmelCase__ = text_input_ids.shape[-1] lowerCAmelCase__ = self.tokenizer( __magic_name__ , padding="max_length" , max_length=__magic_name__ , truncation=__magic_name__ , return_tensors="pt" , ) lowerCAmelCase__ = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # See comment for normalizing text embeddings lowerCAmelCase__ = negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1 , keepdim=__magic_name__ ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method lowerCAmelCase__ = negative_prompt_embeds.shape[1] lowerCAmelCase__ = negative_prompt_embeds.repeat(1 , __magic_name__ , 1 ) lowerCAmelCase__ = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __magic_name__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowerCAmelCase__ = torch.cat([negative_prompt_embeds, prompt_embeds] ) return prompt_embeds @torch.no_grad() def __call__( self : Any , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 100 , __magic_name__ : float = 5.0 , __magic_name__ : float = 1.0 , __magic_name__ : int = 1 , __magic_name__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = 1 elif isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = len(__magic_name__ ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__magic_name__ )}""" ) lowerCAmelCase__ = batch_size * num_images_per_prompt lowerCAmelCase__ = guidance_scale > 1.0 lowerCAmelCase__ = self._encode_prompt(__magic_name__ , __magic_name__ , __magic_name__ ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__magic_name__ , __magic_name__ ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(__magic_name__ )}.""" ) # get the initial completely masked latents unless the user supplied it lowerCAmelCase__ = (batch_size, self.transformer.num_latent_pixels) if latents is None: lowerCAmelCase__ = self.transformer.num_vector_embeds - 1 lowerCAmelCase__ = torch.full(__magic_name__ , __magic_name__ ).to(self.device ) else: if latents.shape != latents_shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any(): raise ValueError( "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0," f""" {self.transformer.num_vector_embeds - 1} (inclusive).""" ) lowerCAmelCase__ = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(__magic_name__ , device=self.device ) lowerCAmelCase__ = self.scheduler.timesteps.to(self.device ) lowerCAmelCase__ = latents for i, t in enumerate(self.progress_bar(__magic_name__ ) ): # expand the sample if we are doing classifier free guidance lowerCAmelCase__ = torch.cat([sample] * 2 ) if do_classifier_free_guidance else sample # predict the un-noised image # model_output == `log_p_x_0` lowerCAmelCase__ = self.transformer(__magic_name__ , encoder_hidden_states=__magic_name__ , timestep=__magic_name__ ).sample if do_classifier_free_guidance: lowerCAmelCase__ ,lowerCAmelCase__ = model_output.chunk(2 ) lowerCAmelCase__ = model_output_uncond + guidance_scale * (model_output_text - model_output_uncond) model_output -= torch.logsumexp(__magic_name__ , dim=1 , keepdim=__magic_name__ ) lowerCAmelCase__ = self.truncate(__magic_name__ , __magic_name__ ) # remove `log(0)`'s (`-inf`s) lowerCAmelCase__ = model_output.clamp(-70 ) # compute the previous noisy sample x_t -> x_t-1 lowerCAmelCase__ = self.scheduler.step(__magic_name__ , timestep=__magic_name__ , sample=__magic_name__ , generator=__magic_name__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(__magic_name__ , __magic_name__ , __magic_name__ ) lowerCAmelCase__ = self.vqvae.config.vq_embed_dim lowerCAmelCase__ = (batch_size, self.transformer.height, self.transformer.width, embedding_channels) lowerCAmelCase__ = self.vqvae.quantize.get_codebook_entry(__magic_name__ , shape=__magic_name__ ) lowerCAmelCase__ = self.vqvae.decode(__magic_name__ , force_not_quantize=__magic_name__ ).sample lowerCAmelCase__ = (image / 2 + 0.5).clamp(0 , 1 ) lowerCAmelCase__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": lowerCAmelCase__ = self.numpy_to_pil(__magic_name__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : torch.FloatTensor , __magic_name__ : float ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = torch.sort(__magic_name__ , 1 , descending=__magic_name__ ) lowerCAmelCase__ = torch.exp(__magic_name__ ) lowerCAmelCase__ = sorted_p_x_0.cumsum(dim=1 ) < truncation_rate # Ensure that at least the largest probability is not zeroed out lowerCAmelCase__ = torch.full_like(keep_mask[:, 0:1, :] , __magic_name__ ) lowerCAmelCase__ = torch.cat((all_true, keep_mask) , dim=1 ) lowerCAmelCase__ = keep_mask[:, :-1, :] lowerCAmelCase__ = keep_mask.gather(1 , indices.argsort(1 ) ) lowerCAmelCase__ = log_p_x_0.clone() lowerCAmelCase__ = -torch.inf # -inf = log(0) return rv
48
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "vocab.json"} UpperCAmelCase__ : Optional[Any] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } UpperCAmelCase__ : Union[str, Any] = {"mgp-str": 27} class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = VOCAB_FILES_NAMES snake_case__ :Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : int="[GO]" , __magic_name__ : Optional[Any]="[GO]" , __magic_name__ : List[str]="[s]" , __magic_name__ : str="[GO]" , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__( unk_token=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , pad_token=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding="utf-8" ) as vocab_handle: lowerCAmelCase__ = json.load(__magic_name__ ) lowerCAmelCase__ = {v: k for k, v in self.vocab.items()} @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.vocab ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = [] for s in text: char_tokens.extend(__magic_name__ ) return char_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Tuple ): """simple docstring""" return self.decoder.get(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error("Vocabulary path ({}) should be a directory".format(__magic_name__ ) ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + "\n" ) return (vocab_file,)
48
1
'''simple docstring''' # Lint as: python3 import dataclasses import re from dataclasses import dataclass from functools import total_ordering from typing import Optional, Union UpperCAmelCase__ : Optional[Any] = re.compile(R"^(?P<major>\d+)" R"\.(?P<minor>\d+)" R"\.(?P<patch>\d+)$") @total_ordering @dataclass class A : snake_case__ :str snake_case__ :Optional[str] = None snake_case__ :Optional[Union[str, int]] = None snake_case__ :Optional[Union[str, int]] = None snake_case__ :Optional[Union[str, int]] = None def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = _str_to_version_tuple(self.version_str ) def __repr__( self : Tuple ): """simple docstring""" return f"""{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}""" @property def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.major, self.minor, self.patch def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : str ): """simple docstring""" if isinstance(__magic_name__ , __magic_name__ ): return Version(__magic_name__ ) elif isinstance(__magic_name__ , __magic_name__ ): return other raise TypeError(f"""{other} (type {type(__magic_name__ )}) cannot be compared to version.""" ) def __eq__( self : List[Any] , __magic_name__ : str ): """simple docstring""" try: lowerCAmelCase__ = self._validate_operand(__magic_name__ ) except (TypeError, ValueError): return False else: return self.tuple == other.tuple def __lt__( self : str , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = self._validate_operand(__magic_name__ ) return self.tuple < other.tuple def __hash__( self : Tuple ): """simple docstring""" return hash(_version_tuple_to_str(self.tuple ) ) @classmethod def __SCREAMING_SNAKE_CASE ( cls : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = {f.name for f in dataclasses.fields(cls )} return cls(**{k: v for k, v in dic.items() if k in field_names} ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return self.version_str def A ( UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = _VERSION_REG.match(UpperCamelCase_ ) if not res: raise ValueError(F"""Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits.""" ) return tuple(int(UpperCamelCase_ ) for v in [res.group("major" ), res.group("minor" ), res.group("patch" )] ) def A ( UpperCamelCase_ : List[Any] ) -> int: '''simple docstring''' return ".".join(str(UpperCamelCase_ ) for v in version_tuple )
48
'''simple docstring''' from math import sqrt def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , int(sqrt(UpperCamelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase_ ): total += i + n // i elif i == sqrt(UpperCamelCase_ ): total += i return total - n def A ( UpperCamelCase_ : int = 1_00_00 ) -> int: '''simple docstring''' lowerCAmelCase__ = sum( i for i in range(1 , UpperCamelCase_ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase_ ) ) == i and sum_of_divisors(UpperCamelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
48
1
'''simple docstring''' import argparse import copy def A ( UpperCamelCase_ : str ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = {} with open(UpperCamelCase_ ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: lowerCAmelCase__ = [] _list.append([line.split()[1], line.split()[2]] ) lowerCAmelCase__ = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: lowerCAmelCase__ = [] _list.append([line.split()[0], line.split()[2]] ) lowerCAmelCase__ = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def A ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str ) -> List[str]: '''simple docstring''' with open(UpperCamelCase_ ) as f: lowerCAmelCase__ = f.read(1 ) lowerCAmelCase__ = start_node lowerCAmelCase__ = [] lowerCAmelCase__ = start_node lowerCAmelCase__ = 0 while visiting not in first_solution: lowerCAmelCase__ = 1_00_00 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(UpperCamelCase_ ) and k[0] not in first_solution: lowerCAmelCase__ = k[1] lowerCAmelCase__ = k[0] first_solution.append(UpperCamelCase_ ) lowerCAmelCase__ = distance_of_first_solution + int(UpperCamelCase_ ) lowerCAmelCase__ = best_node first_solution.append(UpperCamelCase_ ) lowerCAmelCase__ = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 lowerCAmelCase__ = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_00_00 ) return first_solution, distance_of_first_solution def A ( UpperCamelCase_ : str , UpperCamelCase_ : Dict ) -> Dict: '''simple docstring''' lowerCAmelCase__ = [] for n in solution[1:-1]: lowerCAmelCase__ = solution.index(UpperCamelCase_ ) for kn in solution[1:-1]: lowerCAmelCase__ = solution.index(UpperCamelCase_ ) if n == kn: continue lowerCAmelCase__ = copy.deepcopy(UpperCamelCase_ ) lowerCAmelCase__ = kn lowerCAmelCase__ = n lowerCAmelCase__ = 0 for k in _tmp[:-1]: lowerCAmelCase__ = _tmp[_tmp.index(UpperCamelCase_ ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: lowerCAmelCase__ = distance + int(i[1] ) _tmp.append(UpperCamelCase_ ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) lowerCAmelCase__ = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda UpperCamelCase_ : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 1 lowerCAmelCase__ = first_solution lowerCAmelCase__ = [] lowerCAmelCase__ = distance_of_first_solution lowerCAmelCase__ = solution while count <= iters: lowerCAmelCase__ = find_neighborhood(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = 0 lowerCAmelCase__ = neighborhood[index_of_best_solution] lowerCAmelCase__ = len(UpperCamelCase_ ) - 1 lowerCAmelCase__ = False while not found: lowerCAmelCase__ = 0 while i < len(UpperCamelCase_ ): if best_solution[i] != solution[i]: lowerCAmelCase__ = best_solution[i] lowerCAmelCase__ = solution[i] break lowerCAmelCase__ = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) lowerCAmelCase__ = True lowerCAmelCase__ = best_solution[:-1] lowerCAmelCase__ = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: lowerCAmelCase__ = cost lowerCAmelCase__ = solution else: lowerCAmelCase__ = index_of_best_solution + 1 lowerCAmelCase__ = neighborhood[index_of_best_solution] if len(UpperCamelCase_ ) >= size: tabu_list.pop(0 ) lowerCAmelCase__ = count + 1 return best_solution_ever, best_cost def A ( UpperCamelCase_ : Optional[int]=None ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = generate_neighbours(args.File ) lowerCAmelCase__ ,lowerCAmelCase__ = generate_first_solution( args.File , UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = tabu_search( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , args.Iterations , args.Size , ) print(F"""Best solution: {best_sol}, with total distance: {best_cost}.""" ) if __name__ == "__main__": UpperCAmelCase__ : Optional[Any] = argparse.ArgumentParser(description="Tabu Search") parser.add_argument( "-f", "--File", type=str, help="Path to the file containing the data", required=True, ) parser.add_argument( "-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True, ) parser.add_argument( "-s", "--Size", type=int, help="Size of the tabu list", required=True ) # Pass the arguments to main method main(parser.parse_args())
48
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
1
'''simple docstring''' import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput UpperCAmelCase__ : str = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Dict , *__magic_name__ : Optional[int] , __magic_name__ : Dict=None , __magic_name__ : Union[str, Any]=None , __magic_name__ : Any=None , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(*__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = eval_examples lowerCAmelCase__ = post_process_function lowerCAmelCase__ = quant_trainer_args lowerCAmelCase__ = 128 # default number of calibration samples def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : int=None ): """simple docstring""" if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) lowerCAmelCase__ = calib_dataset if calib_dataset is not None else self.calib_dataset lowerCAmelCase__ = self._remove_unused_columns(__magic_name__ , description="Calibration" ) return DataLoader( __magic_name__ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__magic_name__ , ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any]=None ): """simple docstring""" lowerCAmelCase__ = self.train_dataset if calib_dataset is None else calib_dataset lowerCAmelCase__ = self.get_calib_dataloader(__magic_name__ ) lowerCAmelCase__ = self.model quant_trainer.configure_model(__magic_name__ , self.quant_trainer_args , calib=__magic_name__ ) model.eval() quant_trainer.enable_calibration(__magic_name__ ) logger.info("***** Running calibration *****" ) logger.info(f""" Num examples = {self.calib_num}""" ) logger.info(f""" Batch size = {calib_dataloader.batch_size}""" ) for step, inputs in enumerate(__magic_name__ ): # Prediction step lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self.prediction_step(__magic_name__ , __magic_name__ , prediction_loss_only=__magic_name__ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(__magic_name__ , self.quant_trainer_args ) lowerCAmelCase__ = model def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Optional[Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Dict=None , __magic_name__ : str = "eval" ): """simple docstring""" lowerCAmelCase__ = self.eval_dataset if eval_dataset is None else eval_dataset lowerCAmelCase__ = self.get_eval_dataloader(__magic_name__ ) lowerCAmelCase__ = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. lowerCAmelCase__ = self.compute_metrics lowerCAmelCase__ = None lowerCAmelCase__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowerCAmelCase__ = eval_loop( __magic_name__ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__magic_name__ , ) finally: lowerCAmelCase__ = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: lowerCAmelCase__ = self.post_process_function(__magic_name__ , __magic_name__ , output.predictions ) lowerCAmelCase__ = self.compute_metrics(__magic_name__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): lowerCAmelCase__ = metrics.pop(__magic_name__ ) self.log(__magic_name__ ) else: lowerCAmelCase__ = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) lowerCAmelCase__ = self.callback_handler.on_evaluate(self.args , self.state , self.control , __magic_name__ ) return metrics def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : Any=None , __magic_name__ : str = "test" ): """simple docstring""" lowerCAmelCase__ = self.get_test_dataloader(__magic_name__ ) # Temporarily disable metric computation, we will do it in the loop here. lowerCAmelCase__ = self.compute_metrics lowerCAmelCase__ = None lowerCAmelCase__ = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: lowerCAmelCase__ = eval_loop( __magic_name__ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__magic_name__ , ) finally: lowerCAmelCase__ = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output lowerCAmelCase__ = self.post_process_function(__magic_name__ , __magic_name__ , output.predictions , "predict" ) lowerCAmelCase__ = self.compute_metrics(__magic_name__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f"""{metric_key_prefix}_""" ): lowerCAmelCase__ = metrics.pop(__magic_name__ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any]="./" ): """simple docstring""" lowerCAmelCase__ = self.eval_dataset lowerCAmelCase__ = self.get_eval_dataloader(__magic_name__ ) lowerCAmelCase__ = next(iter(__magic_name__ ) ) # saving device - to make it consistent lowerCAmelCase__ = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple lowerCAmelCase__ = tuple(v.to(__magic_name__ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer lowerCAmelCase__ = True lowerCAmelCase__ = self.model.to(__magic_name__ ) model.eval() model.float() lowerCAmelCase__ = model.module if hasattr(__magic_name__ , "module" ) else model quant_trainer.configure_model(__magic_name__ , self.quant_trainer_args ) lowerCAmelCase__ = os.path.join(__magic_name__ , "model.onnx" ) logger.info(f"""exporting model to {output_model_file}""" ) lowerCAmelCase__ = {0: "batch_size", 1: "seq_len"} torch.onnx.export( __magic_name__ , __magic_name__ , __magic_name__ , export_params=__magic_name__ , opset_version=13 , do_constant_folding=__magic_name__ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=__magic_name__ , ) logger.info("onnx export finished" )
48
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ : str = sys.version_info >= (3, 10) def A ( UpperCamelCase_ : Any=None , UpperCamelCase_ : List[Any]=None ) -> Optional[int]: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase_ ) @dataclass class A : snake_case__ :int snake_case__ :float snake_case__ :str snake_case__ :bool @dataclass class A : snake_case__ :int = 42 snake_case__ :str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :Optional[bool] = None class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'titi' snake_case__ :Optional[int] = 'toto' class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'titi' snake_case__ :str = 'toto' snake_case__ :int = 42 @dataclass class A : snake_case__ :BasicEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.foo ) @dataclass class A : snake_case__ :MixedTypeEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MixedTypeEnum(self.foo ) @dataclass class A : snake_case__ :Optional[int] = None snake_case__ :Optional[float] = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :Optional[str] = None snake_case__ :Optional[List[str]] = list_field(default=[] ) snake_case__ :Optional[List[int]] = list_field(default=[] ) @dataclass class A : snake_case__ :List[int] = list_field(default=[] ) snake_case__ :List[int] = list_field(default=[1, 2, 3] ) snake_case__ :List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) snake_case__ :List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A : snake_case__ :List[int] = field() snake_case__ :str = field() snake_case__ :BasicEnum = field() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.required_enum ) @dataclass class A : snake_case__ :int snake_case__ :"BasicEnum" = field() snake_case__ :"Optional[bool]" = None snake_case__ :"str" = field(default='toto' , metadata={'help': 'help message'} ) snake_case__ :"List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :bool | None = None @dataclass class A : snake_case__ :int | None = None snake_case__ :float | None = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :str | None = None snake_case__ :list[str] | None = list_field(default=[] ) snake_case__ :list[int] | None = list_field(default=[] ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : argparse.ArgumentParser , __magic_name__ : argparse.ArgumentParser ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , __magic_name__ ) and yy.get("choices" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](__magic_name__ ) , yy["type"](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--bar" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--baz" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--flag" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCAmelCase__) ,) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) expected.add_argument("--baz" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=__magic_name__ , dest="baz" ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) lowerCAmelCase__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" @dataclass class A : snake_case__ :Literal["titi", "toto", 42] = "toto" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) lowerCAmelCase__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--bar" , default=__magic_name__ , type=__magic_name__ , help="help message" ) expected.add_argument("--baz" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=__magic_name__ ) lowerCAmelCase__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) lowerCAmelCase__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--required_str" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCAmelCase__ = parser.parse_dict(__magic_name__ )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_json" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_yaml" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
48
1
'''simple docstring''' from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract UpperCAmelCase__ : List[str] = logging.get_logger(__name__) def A ( UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] ) -> List[Any]: '''simple docstring''' return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : Optional[str] , UpperCamelCase_ : Optional[str] = None ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = tesseract_config if tesseract_config is not None else "" # apply OCR lowerCAmelCase__ = to_pil_image(UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = pil_image.size lowerCAmelCase__ = pytesseract.image_to_data(UpperCamelCase_ , lang=UpperCamelCase_ , output_type="dict" , config=UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates lowerCAmelCase__ = [idx for idx, word in enumerate(UpperCamelCase_ ) if not word.strip()] lowerCAmelCase__ = [word for idx, word in enumerate(UpperCamelCase_ ) if idx not in irrelevant_indices] lowerCAmelCase__ = [coord for idx, coord in enumerate(UpperCamelCase_ ) if idx not in irrelevant_indices] lowerCAmelCase__ = [coord for idx, coord in enumerate(UpperCamelCase_ ) if idx not in irrelevant_indices] lowerCAmelCase__ = [coord for idx, coord in enumerate(UpperCamelCase_ ) if idx not in irrelevant_indices] lowerCAmelCase__ = [coord for idx, coord in enumerate(UpperCamelCase_ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format lowerCAmelCase__ = [] for x, y, w, h in zip(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase__ = [x, y, x + w, y + h] actual_boxes.append(UpperCamelCase_ ) # finally, normalize the bounding boxes lowerCAmelCase__ = [] for box in actual_boxes: normalized_boxes.append(normalize_box(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) assert len(UpperCamelCase_ ) == len(UpperCamelCase_ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :int = ['pixel_values'] def __init__( self : List[str] , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = PILImageResampling.BILINEAR , __magic_name__ : bool = True , __magic_name__ : Optional[str] = None , __magic_name__ : Optional[str] = "" , **__magic_name__ : Optional[int] , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = size if size is not None else {"height": 224, "width": 224} lowerCAmelCase__ = get_size_dict(__magic_name__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = apply_ocr lowerCAmelCase__ = ocr_lang lowerCAmelCase__ = tesseract_config def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : PILImageResampling = PILImageResampling.BILINEAR , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Optional[Any] , ): """simple docstring""" lowerCAmelCase__ = get_size_dict(__magic_name__ ) 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()}""" ) lowerCAmelCase__ = (size["height"], size["width"]) return resize(__magic_name__ , size=__magic_name__ , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : ImageInput , __magic_name__ : bool = None , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = None , __magic_name__ : bool = None , __magic_name__ : Optional[str] = None , __magic_name__ : Optional[str] = None , __magic_name__ : Optional[Union[str, TensorType]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(__magic_name__ ) lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = apply_ocr if apply_ocr is not None else self.apply_ocr lowerCAmelCase__ = ocr_lang if ocr_lang is not None else self.ocr_lang lowerCAmelCase__ = tesseract_config if tesseract_config is not None else self.tesseract_config lowerCAmelCase__ = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(__magic_name__ ) for image in images] if apply_ocr: requires_backends(self , "pytesseract" ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] for image in images: lowerCAmelCase__ ,lowerCAmelCase__ = apply_tesseract(__magic_name__ , __magic_name__ , __magic_name__ ) words_batch.append(__magic_name__ ) boxes_batch.append(__magic_name__ ) if do_resize: lowerCAmelCase__ = [self.resize(image=__magic_name__ , size=__magic_name__ , resample=__magic_name__ ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) lowerCAmelCase__ = [flip_channel_order(__magic_name__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] lowerCAmelCase__ = BatchFeature(data={"pixel_values": images} , tensor_type=__magic_name__ ) if apply_ocr: lowerCAmelCase__ = words_batch lowerCAmelCase__ = boxes_batch return data
48
'''simple docstring''' import sys from collections import defaultdict class A : def __init__( self : Any ): """simple docstring""" lowerCAmelCase__ = [] def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[Any] ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = pos def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase__ = 2 * start + 1 else: lowerCAmelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase__ ,lowerCAmelCase__ = heap[smallest_child], positions[smallest_child] lowerCAmelCase__ ,lowerCAmelCase__ = ( heap[start], positions[start], ) lowerCAmelCase__ ,lowerCAmelCase__ = temp, tempa lowerCAmelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = position[index] while index != 0: lowerCAmelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase__ = heap[parent] lowerCAmelCase__ = position[parent] self.set_position(position[parent] , __magic_name__ ) else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , __magic_name__ ) break lowerCAmelCase__ = parent else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , 0 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = positions[0] lowerCAmelCase__ = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def A ( UpperCamelCase_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = Heap() lowerCAmelCase__ = [0] * len(UpperCamelCase_ ) lowerCAmelCase__ = [-1] * len(UpperCamelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase__ = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase__ = [] for vertex in range(len(UpperCamelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase_ ) heap.node_position.append(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = 1 lowerCAmelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase__ = 0 lowerCAmelCase__ = distance heap.heapify(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(1 , len(UpperCamelCase_ ) ): lowerCAmelCase__ = heap.delete_minimum(UpperCamelCase_ , UpperCamelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase_ )] ): lowerCAmelCase__ = distance heap.bottom_to_top( UpperCamelCase_ , heap.get_position(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ : Optional[int] = int(input("Enter number of edges: ").strip()) UpperCAmelCase__ : str = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
48
1
'''simple docstring''' import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": UpperCAmelCase__ : Dict = argparse.ArgumentParser() parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the output model.") parser.add_argument( "--txt2img_unclip", default="kakaobrain/karlo-v1-alpha", type=str, required=False, help="The pretrained txt2img unclip.", ) UpperCAmelCase__ : str = parser.parse_args() UpperCAmelCase__ : List[Any] = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) UpperCAmelCase__ : str = CLIPImageProcessor() UpperCAmelCase__ : List[Any] = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14") UpperCAmelCase__ : List[Any] = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
48
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") if is_sentencepiece_available(): import sentencepiece as sp UpperCAmelCase__ : Tuple = 5 UpperCAmelCase__ : List[Any] = 10 @require_sentencepiece @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = SpeechaTextTokenizer snake_case__ :Dict = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().setUp() lowerCAmelCase__ = sp.SentencePieceProcessor() spm_model.Load(__magic_name__ ) lowerCAmelCase__ = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__magic_name__ ) , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [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 __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = 'valhalla/s2t_mustc_multilinguial_medium' snake_case__ :Tuple = 'C\'est trop cool' snake_case__ :List[str] = 'Esto es genial' @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) lowerCAmelCase__ = [ES_CODE, 4, 1601, 47, 7647, 2] lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = "fr" lowerCAmelCase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , __magic_name__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowerCAmelCase__ = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
48
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : int = { "microsoft/trocr-base-handwritten": ( "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :int = 'trocr' snake_case__ :Any = ['past_key_values'] snake_case__ :Tuple = { 'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model', 'num_hidden_layers': 'decoder_layers', } def __init__( self : Optional[Any] , __magic_name__ : Dict=50265 , __magic_name__ : Union[str, Any]=1024 , __magic_name__ : Optional[Any]=12 , __magic_name__ : int=16 , __magic_name__ : Optional[Any]=4096 , __magic_name__ : Union[str, Any]="gelu" , __magic_name__ : Dict=512 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : Union[str, Any]=0.0 , __magic_name__ : str=0.0 , __magic_name__ : Optional[Any]=2 , __magic_name__ : Optional[Any]=0.02 , __magic_name__ : Tuple=0.0 , __magic_name__ : Optional[int]=True , __magic_name__ : Dict=False , __magic_name__ : str=True , __magic_name__ : Any=True , __magic_name__ : Union[str, Any]=1 , __magic_name__ : Dict=0 , __magic_name__ : Optional[int]=2 , **__magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = decoder_layers lowerCAmelCase__ = decoder_attention_heads lowerCAmelCase__ = decoder_ffn_dim lowerCAmelCase__ = activation_function lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = init_std lowerCAmelCase__ = decoder_layerdrop lowerCAmelCase__ = use_cache lowerCAmelCase__ = scale_embedding lowerCAmelCase__ = use_learned_position_embeddings lowerCAmelCase__ = layernorm_embedding super().__init__( pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , )
48
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCAmelCase__ : Tuple = logging.get_logger(__name__) # General docstring UpperCAmelCase__ : int = "RegNetConfig" # Base docstring UpperCAmelCase__ : Optional[int] = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[int] = [1, 10_88, 7, 7] # Image classification docstring UpperCAmelCase__ : Tuple = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[Any] = "tabby, tabby cat" UpperCAmelCase__ : int = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A ( tf.keras.layers.Layer ): def __init__( self : str , __magic_name__ : int , __magic_name__ : int = 3 , __magic_name__ : int = 1 , __magic_name__ : int = 1 , __magic_name__ : Optional[str] = "relu" , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=__magic_name__ , strides=__magic_name__ , padding="VALID" , groups=__magic_name__ , use_bias=__magic_name__ , name="convolution" , ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else tf.identity def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convolution(self.padding(__magic_name__ ) ) lowerCAmelCase__ = self.normalization(__magic_name__ ) lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : List[Any] , __magic_name__ : RegNetConfig , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config.num_channels lowerCAmelCase__ = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = shape_list(__magic_name__ )[1] if tf.executing_eagerly() and 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." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 2, 3, 1) ) lowerCAmelCase__ = self.embedder(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Any , __magic_name__ : int , __magic_name__ : int = 2 , **__magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=1 , strides=__magic_name__ , use_bias=__magic_name__ , name="convolution" ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : bool = False ): """simple docstring""" return self.normalization(self.convolution(__magic_name__ ) , training=__magic_name__ ) class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) lowerCAmelCase__ = [ tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.pooler(__magic_name__ ) for layer_module in self.attention: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = hidden_state * pooled return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.2" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(__magic_name__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.3" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 2 , __magic_name__ : int = 2 , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer lowerCAmelCase__ = [ # downsampling is done in the first layer with stride of 2 layer(__magic_name__ , __magic_name__ , __magic_name__ , stride=__magic_name__ , name="layers.0" ), *[layer(__magic_name__ , __magic_name__ , __magic_name__ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[str] ): """simple docstring""" for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __magic_name__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__magic_name__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__magic_name__ , __magic_name__ , __magic_name__ , depth=__magic_name__ , name=f"""stages.{i+1}""" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : tf.Tensor , __magic_name__ : bool = False , __magic_name__ : bool = True ): """simple docstring""" lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__magic_name__ ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__magic_name__ , hidden_states=__magic_name__ ) @keras_serializable class A ( tf.keras.layers.Layer ): snake_case__ :List[Any] = RegNetConfig def __init__( self : str , __magic_name__ : Union[str, Any] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config lowerCAmelCase__ = TFRegNetEmbeddings(__magic_name__ , name="embedder" ) lowerCAmelCase__ = TFRegNetEncoder(__magic_name__ , name="encoder" ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) @unpack_inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = self.encoder( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__magic_name__ ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ = tuple([tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__magic_name__ , pooler_output=__magic_name__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = RegNetConfig snake_case__ :Optional[Any] = 'regnet' snake_case__ :Tuple = 'pixel_values' @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} UpperCAmelCase__ : List[str] = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ : Tuple = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~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__ , ) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : RegNetConfig , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : int=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( pixel_values=__magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=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__ , ) class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , *__magic_name__ : Tuple , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) # classification head lowerCAmelCase__ = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : tf.Tensor = None , __magic_name__ : tf.Tensor = None , __magic_name__ : bool = None , __magic_name__ : bool = None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier[0](__magic_name__ ) lowerCAmelCase__ = self.classifier[1](__magic_name__ ) lowerCAmelCase__ = None if labels is None else self.hf_compute_loss(labels=__magic_name__ , logits=__magic_name__ ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__magic_name__ , logits=__magic_name__ , hidden_states=outputs.hidden_states )
48
1
'''simple docstring''' import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py UpperCAmelCase__ : Optional[int] = "." if __name__ == "__main__": UpperCAmelCase__ : Optional[int] = os.path.join(REPO_PATH, "utils/documentation_tests.txt") UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : Dict = [] with open(doctest_file_path) as fp: for line in fp: UpperCAmelCase__ : Tuple = line.strip() UpperCAmelCase__ : Optional[int] = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: UpperCAmelCase__ : Tuple = "\n".join(non_existent_paths) raise ValueError(F"`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}") if all_paths != sorted(all_paths): raise ValueError("Files in `utils/documentation_tests.txt` are not in alphabetical order.")
48
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def A ( UpperCamelCase_ : Tuple ) -> int: '''simple docstring''' for param in module.parameters(): lowerCAmelCase__ = False def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = datetime.now() lowerCAmelCase__ = current_time.strftime("%H:%M:%S" ) return timestamp
48
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, 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, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class A : snake_case__ :str = BlenderbotConfig snake_case__ :Optional[int] = {} snake_case__ :int = 'gelu' def __init__( self : Any , __magic_name__ : List[str] , __magic_name__ : Optional[int]=13 , __magic_name__ : Tuple=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Optional[int]=False , __magic_name__ : Any=99 , __magic_name__ : List[str]=32 , __magic_name__ : List[str]=2 , __magic_name__ : Dict=4 , __magic_name__ : List[Any]=37 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : Any=0.1 , __magic_name__ : Optional[Any]=20 , __magic_name__ : Tuple=2 , __magic_name__ : Any=1 , __magic_name__ : Union[str, Any]=0 , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = pad_token_id lowerCAmelCase__ = bos_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCAmelCase__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCAmelCase__ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = prepare_blenderbot_inputs_dict(__magic_name__ , __magic_name__ , __magic_name__ ) return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = TFBlenderbotModel(config=__magic_name__ ).get_decoder() lowerCAmelCase__ = inputs_dict["input_ids"] lowerCAmelCase__ = input_ids[:1, :] lowerCAmelCase__ = inputs_dict["attention_mask"][:1, :] lowerCAmelCase__ = inputs_dict["head_mask"] lowerCAmelCase__ = 1 # first forward pass lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , head_mask=__magic_name__ , use_cache=__magic_name__ ) lowerCAmelCase__ ,lowerCAmelCase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCAmelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCAmelCase__ = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCAmelCase__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ )[0] lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCAmelCase__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCAmelCase__ = output_from_no_past[:, -3:, random_slice_idx] lowerCAmelCase__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__magic_name__ , __magic_name__ , rtol=1E-3 ) def A ( UpperCamelCase_ : int , UpperCamelCase_ : str , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Optional[Any]=None , UpperCamelCase_ : Optional[Any]=None , UpperCamelCase_ : List[str]=None , ) -> Dict: '''simple docstring''' if attention_mask is None: lowerCAmelCase__ = tf.cast(tf.math.not_equal(UpperCamelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCAmelCase__ = 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: lowerCAmelCase__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase__ = 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 ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () snake_case__ :Optional[Any] = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () snake_case__ :List[Any] = ( { 'conversational': TFBlenderbotForConditionalGeneration, 'feature-extraction': TFBlenderbotModel, 'summarization': TFBlenderbotForConditionalGeneration, 'text2text-generation': TFBlenderbotForConditionalGeneration, 'translation': TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) snake_case__ :int = True snake_case__ :Optional[Any] = False snake_case__ :Tuple = False def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = TFBlenderbotModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__magic_name__ ) @require_tokenizers @require_tf class A ( unittest.TestCase ): snake_case__ :Any = ['My friends are cool but they eat too many carbs.'] snake_case__ :Optional[int] = 'facebook/blenderbot-400M-distill' @cached_property def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.tokenizer(self.src_text , return_tensors="tf" ) lowerCAmelCase__ = self.model.generate( model_inputs.input_ids , ) lowerCAmelCase__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__magic_name__ )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ : List[Any] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__) UpperCAmelCase__ : Tuple = { "facebook/dpr-ctx_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json" ), "facebook/dpr-question_encoder-single-nq-base": ( "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json" ), "facebook/dpr-reader-single-nq-base": ( "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json" ), "facebook/dpr-ctx_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json" ), "facebook/dpr-question_encoder-multiset-base": ( "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json" ), "facebook/dpr-reader-multiset-base": ( "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json" ), } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Dict = 'dpr' def __init__( self : List[str] , __magic_name__ : List[Any]=30522 , __magic_name__ : Optional[Any]=768 , __magic_name__ : str=12 , __magic_name__ : Optional[int]=12 , __magic_name__ : List[str]=3072 , __magic_name__ : Union[str, Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : Tuple=0.1 , __magic_name__ : Tuple=512 , __magic_name__ : int=2 , __magic_name__ : Dict=0.02 , __magic_name__ : Any=1E-12 , __magic_name__ : Tuple=0 , __magic_name__ : Union[str, Any]="absolute" , __magic_name__ : int = 0 , **__magic_name__ : List[str] , ): """simple docstring""" super().__init__(pad_token_id=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = hidden_act lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = projection_dim lowerCAmelCase__ = position_embedding_type
48
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
1
'''simple docstring''' 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 A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = ['image_processor', 'tokenizer'] snake_case__ :List[str] = 'BlipImageProcessor' snake_case__ :Any = 'AutoTokenizer' def __init__( self : Any , __magic_name__ : str , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = False super().__init__(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = self.image_processor def __call__( self : Any , __magic_name__ : ImageInput = None , __magic_name__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __magic_name__ : bool = True , __magic_name__ : Union[bool, str, PaddingStrategy] = False , __magic_name__ : Union[bool, str, TruncationStrategy] = None , __magic_name__ : Optional[int] = None , __magic_name__ : int = 0 , __magic_name__ : Optional[int] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = True , __magic_name__ : Optional[Union[str, TensorType]] = None , **__magic_name__ : str , ): """simple docstring""" 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: lowerCAmelCase__ = self.tokenizer lowerCAmelCase__ = self.tokenizer( text=__magic_name__ , add_special_tokens=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , max_length=__magic_name__ , stride=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=__magic_name__ , return_overflowing_tokens=__magic_name__ , return_special_tokens_mask=__magic_name__ , return_offsets_mapping=__magic_name__ , return_token_type_ids=__magic_name__ , return_length=__magic_name__ , verbose=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ , ) return text_encoding # add pixel_values lowerCAmelCase__ = self.image_processor(__magic_name__ , return_tensors=__magic_name__ ) if text is not None: lowerCAmelCase__ = self.tokenizer( text=__magic_name__ , add_special_tokens=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , max_length=__magic_name__ , stride=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=__magic_name__ , return_overflowing_tokens=__magic_name__ , return_special_tokens_mask=__magic_name__ , return_offsets_mapping=__magic_name__ , return_token_type_ids=__magic_name__ , return_length=__magic_name__ , verbose=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ , ) else: lowerCAmelCase__ = None if text_encoding is not None: encoding_image_processor.update(__magic_name__ ) return encoding_image_processor def __SCREAMING_SNAKE_CASE ( self : List[str] , *__magic_name__ : Optional[int] , **__magic_name__ : Optional[int] ): """simple docstring""" return self.tokenizer.batch_decode(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , *__magic_name__ : Any , **__magic_name__ : List[Any] ): """simple docstring""" return self.tokenizer.decode(*__magic_name__ , **__magic_name__ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.tokenizer.model_input_names lowerCAmelCase__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
48
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A : def __init__( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : str=13 , __magic_name__ : List[str]=7 , __magic_name__ : Tuple=True , __magic_name__ : Tuple=True , __magic_name__ : str=True , __magic_name__ : int=True , __magic_name__ : int=99 , __magic_name__ : List[str]=[1, 1, 2] , __magic_name__ : Dict=1 , __magic_name__ : Tuple=32 , __magic_name__ : Any=4 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : List[str]=0.1 , __magic_name__ : Tuple=0.0 , __magic_name__ : int=512 , __magic_name__ : Optional[int]=3 , __magic_name__ : List[str]=0.02 , __magic_name__ : Dict=3 , __magic_name__ : List[Any]=4 , __magic_name__ : Any=None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = block_sizes lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = d_model lowerCAmelCase__ = n_head lowerCAmelCase__ = d_head lowerCAmelCase__ = d_inner lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = 2 lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope lowerCAmelCase__ = initializer_std # Used in the tests to check the size of the first attention layer lowerCAmelCase__ = n_head # Used in the tests to check the size of the first hidden state lowerCAmelCase__ = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCAmelCase__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCAmelCase__ = self.num_hidden_layers + 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForPreTraining(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForMaskedLM(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForSequenceClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : List[str] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = TFFunnelForMultipleChoice(config=__magic_name__ ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForTokenClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForQuestionAnswering(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) snake_case__ :Any = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) snake_case__ :str = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @require_tf class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) snake_case__ :int = False snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self , base=__magic_name__ ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__magic_name__ )
48
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :str = IFInpaintingPipeline snake_case__ :List[str] = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} snake_case__ :Optional[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS snake_case__ :int = PipelineTesterMixin.required_optional_params - {'latents'} def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._get_dummy_components() def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple=0 ): """simple docstring""" if str(__magic_name__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(__magic_name__ ) else: lowerCAmelCase__ = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) lowerCAmelCase__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) lowerCAmelCase__ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self._test_save_load_local() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
48
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Any = { "configuration_time_series_transformer": [ "TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimeSeriesTransformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = [ "TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimeSeriesTransformerForPrediction", "TimeSeriesTransformerModel", "TimeSeriesTransformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : str , __magic_name__ : float ): """simple docstring""" if nodea not in self.connections: self.add_node(__magic_name__ ) if nodea not in self.connections: self.add_node(__magic_name__ ) lowerCAmelCase__ = probability def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return list(self.connections ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[tuple[str, str, float]] , UpperCamelCase_ : int ) -> dict[str, int]: '''simple docstring''' lowerCAmelCase__ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = Counter(graph.get_nodes() ) lowerCAmelCase__ = start for _ in range(UpperCamelCase_ ): lowerCAmelCase__ = graph.transition(UpperCamelCase_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' def A ( UpperCamelCase_ : int ) -> str: '''simple docstring''' lowerCAmelCase__ = int(UpperCamelCase_ ) if decimal in (0, 1): # Exit cases for the recursion return str(UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = divmod(UpperCamelCase_ , 2 ) return binary_recursive(UpperCamelCase_ ) + str(UpperCamelCase_ ) def A ( UpperCamelCase_ : str ) -> str: '''simple docstring''' lowerCAmelCase__ = str(UpperCamelCase_ ).strip() if not number: raise ValueError("No input value was provided" ) lowerCAmelCase__ = "-" if number.startswith("-" ) else "" lowerCAmelCase__ = number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return F"""{negative}0b{binary_recursive(int(UpperCamelCase_ ) )}""" if __name__ == "__main__": from doctest import testmod testmod()
48
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
1
'''simple docstring''' import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model UpperCAmelCase__ : str = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int]=None ) -> Optional[int]: '''simple docstring''' if rng is None: lowerCAmelCase__ = random.Random() lowerCAmelCase__ = 1 for dim in shape: total_dims *= dim lowerCAmelCase__ = [] for _ in range(UpperCamelCase_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) lowerCAmelCase__ = np.array(UpperCamelCase_ , dtype=jnp.intaa ).reshape(UpperCamelCase_ ) return output def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str]=None ) -> int: '''simple docstring''' lowerCAmelCase__ = ids_tensor(UpperCamelCase_ , vocab_size=2 , rng=UpperCamelCase_ ) # make sure that at least one token is attended to for each batch lowerCAmelCase__ = 1 return attn_mask @require_flax class A : snake_case__ :Dict = None snake_case__ :Optional[Any] = () def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 lowerCAmelCase__ = 2 lowerCAmelCase__ = inputs["input_ids"].shape[-1] // 2 lowerCAmelCase__ = inputs["input_ids"][:max_batch_size, :sequence_length] lowerCAmelCase__ = jnp.ones_like(__magic_name__ ) lowerCAmelCase__ = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens lowerCAmelCase__ = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` lowerCAmelCase__ = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 0 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model_class.__name__[4:] # Skip the "Flax" at the beginning lowerCAmelCase__ = getattr(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = pt_model_class(__magic_name__ ).eval() lowerCAmelCase__ = load_flax_weights_in_pytorch_model(__magic_name__ , flax_model.params ) lowerCAmelCase__ = flax_model.generate(__magic_name__ ).sequences lowerCAmelCase__ = pt_model.generate(torch.tensor(__magic_name__ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: lowerCAmelCase__ = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = True lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = False lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = True lowerCAmelCase__ = max_length lowerCAmelCase__ = 0.8 lowerCAmelCase__ = 10 lowerCAmelCase__ = 0.3 lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = max_length lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() lowerCAmelCase__ = max_length lowerCAmelCase__ = 2 lowerCAmelCase__ = 1 lowerCAmelCase__ = 8 lowerCAmelCase__ = 9 for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = False lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = True lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = self._get_input_ids_and_config() # pad attention mask on the left lowerCAmelCase__ = attention_mask.at[(0, 0)].set(0 ) lowerCAmelCase__ = 2 lowerCAmelCase__ = max_length for model_class in self.all_generative_model_classes: lowerCAmelCase__ = model_class(__magic_name__ ) lowerCAmelCase__ = model.generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertEqual(generation_outputs.shape[-1] , __magic_name__ ) lowerCAmelCase__ = jit(model.generate ) lowerCAmelCase__ = jit_generate(__magic_name__ , attention_mask=__magic_name__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert" ) lowerCAmelCase__ = FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) lowerCAmelCase__ = "Hello world" lowerCAmelCase__ = tokenizer(__magic_name__ , return_tensors="np" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(__magic_name__ , "do_samples" ): model.generate(__magic_name__ , do_samples=__magic_name__ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(__magic_name__ , "foo" ): lowerCAmelCase__ = {"foo": "bar"} model.generate(__magic_name__ , **__magic_name__ )
48
'''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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase__ : int = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'facebook/nllb-200-distilled-600M' snake_case__ :Optional[Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) snake_case__ :List[Any] = 'translator' snake_case__ :List[Any] = AutoTokenizer snake_case__ :Optional[Any] = AutoModelForSeqaSeqLM snake_case__ :List[str] = LANGUAGE_CODES snake_case__ :List[Any] = ['text', 'text', 'text'] snake_case__ :List[Any] = ['text'] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ): """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __magic_name__ , return_tensors="pt" , src_lang=__magic_name__ , tgt_lang=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__magic_name__ )
48
1
'''simple docstring''' import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> List[Any]: '''simple docstring''' lowerCAmelCase__ = torch.load(UpperCamelCase_ , map_location="cpu" ) lowerCAmelCase__ = chkpt["model"] # We have the base model one level deeper than the original XLM repository lowerCAmelCase__ = {} for k, v in state_dict.items(): if "pred_layer" in k: lowerCAmelCase__ = v else: lowerCAmelCase__ = v lowerCAmelCase__ = chkpt["params"] lowerCAmelCase__ = {n: v for n, v in config.items() if not isinstance(UpperCamelCase_ , (torch.FloatTensor, numpy.ndarray) )} lowerCAmelCase__ = chkpt["dico_word2id"] lowerCAmelCase__ = {s + "</w>" if s.find("@@" ) == -1 and i > 13 else s.replace("@@" , "" ): i for s, i in vocab.items()} # Save pytorch-model lowerCAmelCase__ = pytorch_dump_folder_path + "/" + WEIGHTS_NAME lowerCAmelCase__ = pytorch_dump_folder_path + "/" + CONFIG_NAME lowerCAmelCase__ = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(F"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(UpperCamelCase_ , UpperCamelCase_ ) print(F"""Save configuration file to {pytorch_config_dump_path}""" ) with open(UpperCamelCase_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(UpperCamelCase_ , indent=2 ) + "\n" ) print(F"""Save vocab file to {pytorch_config_dump_path}""" ) with open(UpperCamelCase_ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(UpperCamelCase_ , indent=2 ) + "\n" ) if __name__ == "__main__": UpperCAmelCase__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--xlm_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) UpperCAmelCase__ : Any = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
48
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'timm_backbone' def __init__( self : Tuple , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=3 , __magic_name__ : Dict=True , __magic_name__ : str=True , __magic_name__ : List[Any]=None , **__magic_name__ : Tuple , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = backbone lowerCAmelCase__ = num_channels lowerCAmelCase__ = features_only lowerCAmelCase__ = use_pretrained_backbone lowerCAmelCase__ = True lowerCAmelCase__ = out_indices if out_indices is not None else (-1,)
48
1
'''simple docstring''' import argparse import math import traceback import dateutil.parser as date_parser import requests def A ( UpperCamelCase_ : Any ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = {} lowerCAmelCase__ = job["started_at"] lowerCAmelCase__ = job["completed_at"] lowerCAmelCase__ = date_parser.parse(UpperCamelCase_ ) lowerCAmelCase__ = date_parser.parse(UpperCamelCase_ ) lowerCAmelCase__ = round((end_datetime - start_datetime).total_seconds() / 60.0 ) lowerCAmelCase__ = start lowerCAmelCase__ = end lowerCAmelCase__ = duration_in_min return job_info def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[str]=None ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = None if token is not None: lowerCAmelCase__ = {"Accept": "application/vnd.github+json", "Authorization": F"""Bearer {token}"""} lowerCAmelCase__ = F"""https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100""" lowerCAmelCase__ = requests.get(UpperCamelCase_ , headers=UpperCamelCase_ ).json() lowerCAmelCase__ = {} try: job_time.update({job["name"]: extract_time_from_single_job(UpperCamelCase_ ) for job in result["jobs"]} ) lowerCAmelCase__ = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(UpperCamelCase_ ): lowerCAmelCase__ = requests.get(url + F"""&page={i + 2}""" , headers=UpperCamelCase_ ).json() job_time.update({job["name"]: extract_time_from_single_job(UpperCamelCase_ ) for job in result["jobs"]} ) return job_time except Exception: print(F"""Unknown error, could not fetch links:\n{traceback.format_exc()}""" ) return {} if __name__ == "__main__": UpperCAmelCase__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") UpperCAmelCase__ : Dict = parser.parse_args() UpperCAmelCase__ : List[Any] = get_job_time(args.workflow_run_id) UpperCAmelCase__ : Tuple = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(F"{k}: {v['duration']}")
48
'''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. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'Salesforce/blip-image-captioning-base' snake_case__ :List[Any] = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case__ :List[Any] = 'image_captioner' snake_case__ :Optional[int] = AutoModelForVisionaSeq snake_case__ :Optional[int] = ['image'] snake_case__ :Any = ['text'] def __init__( self : str , *__magic_name__ : List[str] , **__magic_name__ : Tuple ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : "Image" ): """simple docstring""" return self.pre_processor(images=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Optional[int] ): """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0].strip()
48
1
'''simple docstring''' import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller UpperCAmelCase__ : int = 3 def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' print("Generating primitive root of p" ) while True: lowerCAmelCase__ = random.randrange(3 , UpperCamelCase_ ) if pow(UpperCamelCase_ , 2 , UpperCamelCase_ ) == 1: continue if pow(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) == 1: continue return g def A ( UpperCamelCase_ : int ) -> tuple[tuple[int, int, int, int], tuple[int, int]]: '''simple docstring''' print("Generating prime p..." ) lowerCAmelCase__ = rabin_miller.generate_large_prime(UpperCamelCase_ ) # select large prime number. lowerCAmelCase__ = primitive_root(UpperCamelCase_ ) # one primitive root on modulo p. lowerCAmelCase__ = random.randrange(3 , UpperCamelCase_ ) # private_key -> have to be greater than 2 for safety. lowerCAmelCase__ = cryptomath.find_mod_inverse(pow(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , UpperCamelCase_ ) lowerCAmelCase__ = (key_size, e_a, e_a, p) lowerCAmelCase__ = (key_size, d) return public_key, private_key def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> None: '''simple docstring''' if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ): print("\nWARNING:" ) print( F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" "Use a different name or delete these files and re-run this program." ) sys.exit() lowerCAmelCase__ ,lowerCAmelCase__ = generate_key(UpperCamelCase_ ) print(F"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(F"""{name}_pubkey.txt""" , "w" ) as fo: fo.write(F"""{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}""" ) print(F"""Writing private key to file {name}_privkey.txt...""" ) with open(F"""{name}_privkey.txt""" , "w" ) as fo: fo.write(F"""{private_key[0]},{private_key[1]}""" ) def A ( ) -> None: '''simple docstring''' print("Making key files..." ) make_key_files("elgamal" , 20_48 ) print("Key files generation successful" ) if __name__ == "__main__": main()
48
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = "▁" UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model"} UpperCAmelCase__ : Union[str, Any] = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } UpperCAmelCase__ : Optional[Any] = { "facebook/mbart-large-50-one-to-many-mmt": 10_24, } # fmt: off UpperCAmelCase__ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Any = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : int , __magic_name__ : int , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]="</s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : List[Any]="<s>" , __magic_name__ : Tuple="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : List[Any]="<mask>" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__magic_name__ , tgt_lang=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__magic_name__ ) ) lowerCAmelCase__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__magic_name__ ) } lowerCAmelCase__ = {v: k for k, v in self.lang_code_to_id.items()} lowerCAmelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowerCAmelCase__ = src_lang if src_lang is not None else "en_XX" lowerCAmelCase__ = self.lang_code_to_id[self._src_lang] lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : List[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str ): """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(__magic_name__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = 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(__magic_name__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(__magic_name__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) lowerCAmelCase__ = [1] * len(self.prefix_tokens ) lowerCAmelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__magic_name__ )) + suffix_ones return prefix_ones + ([0] * len(__magic_name__ )) + ([0] * len(__magic_name__ )) + suffix_ones def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str = "en_XX" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "ro_RO" , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[src_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[tgt_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id]
48
1
'''simple docstring''' import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import BatchEncoding, MarianTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available if is_sentencepiece_available(): from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : List[str] = get_tests_dir("fixtures/test_sentencepiece.model") UpperCAmelCase__ : List[str] = {"target_lang": "fi", "source_lang": "en"} UpperCAmelCase__ : str = ">>zh<<" UpperCAmelCase__ : List[Any] = "Helsinki-NLP/" if is_torch_available(): UpperCAmelCase__ : Tuple = "pt" elif is_tf_available(): UpperCAmelCase__ : Union[str, Any] = "tf" else: UpperCAmelCase__ : Optional[Any] = "jax" @require_sentencepiece class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = MarianTokenizer snake_case__ :Any = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" super().setUp() lowerCAmelCase__ = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab"] ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["tokenizer_config_file"] ) if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["source_spm"] ) copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["target_spm"] ) lowerCAmelCase__ = MarianTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str , **__magic_name__ : Optional[int] ): """simple docstring""" return MarianTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] ): """simple docstring""" return ( "This is a test", "This is a test", ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = "</s>" lowerCAmelCase__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = 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(__magic_name__ ) , 9 ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 9 ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MarianTokenizer.from_pretrained(f"""{ORG_NAME}opus-mt-en-de""" ) lowerCAmelCase__ = en_de_tokenizer(["I am a small frog"] , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = [38, 121, 14, 697, 38848, 0] self.assertListEqual(__magic_name__ , batch.input_ids[0] ) lowerCAmelCase__ = tempfile.mkdtemp() en_de_tokenizer.save_pretrained(__magic_name__ ) lowerCAmelCase__ = [x.name for x in Path(__magic_name__ ).glob("*" )] self.assertIn("source.spm" , __magic_name__ ) MarianTokenizer.from_pretrained(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = tok( ["I am a small frog" * 1000, "I am a small frog"] , padding=__magic_name__ , truncation=__magic_name__ , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) self.assertEqual(batch.input_ids.shape , (2, 512) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = tok(["I am a tiny frog", "I am a small frog"] , padding=__magic_name__ , return_tensors=__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) self.assertEqual(batch_smaller.input_ids.shape , (2, 10) ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = {"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=__magic_name__ , model_name="Helsinki-NLP/opus-mt-en-de" , revision="1a8c2263da11e68e50938f97e10cd57820bd504c" , decode_kwargs={"use_source_tokenizer": True} , ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs" ) lowerCAmelCase__ = "Tämä on testi" lowerCAmelCase__ = "This is a test" lowerCAmelCase__ = [76, 7, 2047, 2] lowerCAmelCase__ = [69, 12, 11, 940, 2] lowerCAmelCase__ = tokenizer(__magic_name__ ).input_ids self.assertListEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = tokenizer(text_target=__magic_name__ ).input_ids self.assertListEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ )
48
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _in_place_partition(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) count += _in_place_quick_sort(UpperCamelCase_ , UpperCamelCase_ , p - 1 ) count += _in_place_quick_sort(UpperCamelCase_ , p + 1 , UpperCamelCase_ ) return count def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = start - 1 for index in range(UpperCamelCase_ , UpperCamelCase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
1
'''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. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'Salesforce/blip-image-captioning-base' snake_case__ :List[Any] = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case__ :List[Any] = 'image_captioner' snake_case__ :Optional[int] = AutoModelForVisionaSeq snake_case__ :Optional[int] = ['image'] snake_case__ :Any = ['text'] def __init__( self : str , *__magic_name__ : List[str] , **__magic_name__ : Tuple ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : "Image" ): """simple docstring""" return self.pre_processor(images=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Optional[int] ): """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0].strip()
48
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def A ( UpperCamelCase_ : List[Any] ) -> Tuple: '''simple docstring''' if "img_encoder.pos_embed" in name: lowerCAmelCase__ = name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: lowerCAmelCase__ = name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: lowerCAmelCase__ = name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCAmelCase__ = name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: lowerCAmelCase__ = name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: lowerCAmelCase__ = name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: lowerCAmelCase__ = name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: lowerCAmelCase__ = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: lowerCAmelCase__ = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: lowerCAmelCase__ = name.replace("c_fc" , "fc1" ) if "c_proj" in name: lowerCAmelCase__ = name.replace("c_proj" , "fc2" ) if "text_encoder" in name: lowerCAmelCase__ = name.replace("text_encoder" , "text_model" ) if "ln_final" in name: lowerCAmelCase__ = name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: lowerCAmelCase__ = name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: lowerCAmelCase__ = name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: lowerCAmelCase__ = name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: lowerCAmelCase__ = name.replace("text_projector.linear_out" , "text_projection.3" ) return name def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> List[Any]: '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCAmelCase__ = orig_state_dict.pop(UpperCamelCase_ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ ,lowerCAmelCase__ = int(key_split[2] ), int(key_split[4] ) lowerCAmelCase__ = config.vision_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ = int(key_split[3] ) lowerCAmelCase__ = config.text_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[ dim : dim * 2, : ] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] else: lowerCAmelCase__ = rename_key(UpperCamelCase_ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCAmelCase__ = val.squeeze_() else: lowerCAmelCase__ = val return orig_state_dict def A ( ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple="groupvit-gcc-yfcc" , UpperCamelCase_ : Dict=False ) -> Any: '''simple docstring''' lowerCAmelCase__ = GroupViTConfig() lowerCAmelCase__ = GroupViTModel(UpperCamelCase_ ).eval() lowerCAmelCase__ = torch.load(UpperCamelCase_ , map_location="cpu" )["model"] lowerCAmelCase__ = convert_state_dict(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(UpperCamelCase_ ) == 0) # verify result lowerCAmelCase__ = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = processor(text=["a photo of a cat", "a photo of a dog"] , images=UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors="pt" ) with torch.no_grad(): lowerCAmelCase__ = model(**UpperCamelCase_ ) if model_name == "groupvit-gcc-yfcc": lowerCAmelCase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowerCAmelCase__ = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(F"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image , UpperCamelCase_ , atol=1E-3 ) processor.save_pretrained(UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) print("Successfully saved processor and model to" , UpperCamelCase_ ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(UpperCamelCase_ , organization="nielsr" ) model.push_to_hub(UpperCamelCase_ , organization="nielsr" ) if __name__ == "__main__": UpperCAmelCase__ : List[str] = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) UpperCAmelCase__ : Any = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
48
1
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _in_place_partition(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) count += _in_place_quick_sort(UpperCamelCase_ , UpperCamelCase_ , p - 1 ) count += _in_place_quick_sort(UpperCamelCase_ , p + 1 , UpperCamelCase_ ) return count def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = start - 1 for index in range(UpperCamelCase_ , UpperCamelCase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ : Optional[Any] = 1_00 UpperCAmelCase__ : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def A ( UpperCamelCase_ : int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} lowerCAmelCase__ = set() lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A ( UpperCamelCase_ : int = 50_00 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , UpperCamelCase_ ): if len(partition(UpperCamelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
48
1
'''simple docstring''' from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
48
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "vocab.json"} UpperCAmelCase__ : Optional[Any] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } UpperCAmelCase__ : Union[str, Any] = {"mgp-str": 27} class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = VOCAB_FILES_NAMES snake_case__ :Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : int="[GO]" , __magic_name__ : Optional[Any]="[GO]" , __magic_name__ : List[str]="[s]" , __magic_name__ : str="[GO]" , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__( unk_token=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , pad_token=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding="utf-8" ) as vocab_handle: lowerCAmelCase__ = json.load(__magic_name__ ) lowerCAmelCase__ = {v: k for k, v in self.vocab.items()} @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.vocab ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = [] for s in text: char_tokens.extend(__magic_name__ ) return char_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Tuple ): """simple docstring""" return self.decoder.get(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error("Vocabulary path ({}) should be a directory".format(__magic_name__ ) ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + "\n" ) return (vocab_file,)
48
1
'''simple docstring''' import colorsys from PIL import Image # type: ignore def A ( UpperCamelCase_ : float , UpperCamelCase_ : float , UpperCamelCase_ : int ) -> float: '''simple docstring''' lowerCAmelCase__ = x lowerCAmelCase__ = y for step in range(UpperCamelCase_ ): # noqa: B007 lowerCAmelCase__ = a * a - b * b + x lowerCAmelCase__ = 2 * a * b + y lowerCAmelCase__ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def A ( UpperCamelCase_ : float ) -> tuple: '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (2_55, 2_55, 2_55) def A ( UpperCamelCase_ : float ) -> tuple: '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 2_55 ) for i in colorsys.hsv_to_rgb(UpperCamelCase_ , 1 , 1 ) ) def A ( UpperCamelCase_ : int = 8_00 , UpperCamelCase_ : int = 6_00 , UpperCamelCase_ : float = -0.6 , UpperCamelCase_ : float = 0 , UpperCamelCase_ : float = 3.2 , UpperCamelCase_ : int = 50 , UpperCamelCase_ : bool = True , ) -> Image.Image: '''simple docstring''' lowerCAmelCase__ = Image.new("RGB" , (image_width, image_height) ) lowerCAmelCase__ = img.load() # loop through the image-coordinates for image_x in range(UpperCamelCase_ ): for image_y in range(UpperCamelCase_ ): # determine the figure-coordinates based on the image-coordinates lowerCAmelCase__ = figure_width / image_width * image_height lowerCAmelCase__ = figure_center_x + (image_x / image_width - 0.5) * figure_width lowerCAmelCase__ = figure_center_y + (image_y / image_height - 0.5) * figure_height lowerCAmelCase__ = get_distance(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: lowerCAmelCase__ = get_color_coded_rgb(UpperCamelCase_ ) else: lowerCAmelCase__ = get_black_and_white_rgb(UpperCamelCase_ ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure UpperCAmelCase__ : List[str] = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
48
'''simple docstring''' from math import sqrt def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , int(sqrt(UpperCamelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase_ ): total += i + n // i elif i == sqrt(UpperCamelCase_ ): total += i return total - n def A ( UpperCamelCase_ : int = 1_00_00 ) -> int: '''simple docstring''' lowerCAmelCase__ = sum( i for i in range(1 , UpperCamelCase_ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase_ ) ) == i and sum_of_divisors(UpperCamelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
48
1
'''simple docstring''' from manim import * class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = Rectangle(height=0.5 , width=0.5 ) lowerCAmelCase__ = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = VGroup(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("CPU" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(4 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("GPU" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) gpu.move_to([-1, -1, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("Model" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , buff=0.5 , aligned_edge=__magic_name__ ) model.move_to([3, -1.0, 0] ) self.add(__magic_name__ ) lowerCAmelCase__ = [] for i, rect in enumerate(__magic_name__ ): rect.set_stroke(__magic_name__ ) # target = fill.copy().set_fill(YELLOW, opacity=0.7) # target.move_to(rect) # self.add(target) lowerCAmelCase__ = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__magic_name__ , opacity=0.7 ) if i == 0: cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__magic_name__ ) cpu_target.set_x(cpu_target.get_x() + 0.1 ) elif i == 3: cpu_target.next_to(cpu_targs[0] , direction=__magic_name__ , buff=0.0 ) else: cpu_target.next_to(cpu_targs[i - 1] , direction=__magic_name__ , buff=0.0 ) self.add(__magic_name__ ) cpu_targs.append(__magic_name__ ) lowerCAmelCase__ = [mem.copy() for i in range(6 )] lowerCAmelCase__ = VGroup(*__magic_name__ ).arrange(__magic_name__ , buff=0 ) lowerCAmelCase__ = Text("Loaded Checkpoint" , font_size=24 ) lowerCAmelCase__ = Group(__magic_name__ , __magic_name__ ).arrange(__magic_name__ , aligned_edge=__magic_name__ , buff=0.4 ) checkpoint.move_to([3, 0.5, 0] ) lowerCAmelCase__ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCAmelCase__ = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(__magic_name__ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) lowerCAmelCase__ = MarkupText( f"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(__magic_name__ ) , Write(__magic_name__ ) ) self.play(Write(__magic_name__ , run_time=1 ) , Create(__magic_name__ , run_time=1 ) ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] for i, rect in enumerate(__magic_name__ ): lowerCAmelCase__ = fill.copy().set_fill(__magic_name__ , opacity=0.7 ) target.move_to(__magic_name__ ) first_animations.append(GrowFromCenter(__magic_name__ , run_time=1 ) ) lowerCAmelCase__ = target.copy() cpu_target.generate_target() if i < 5: cpu_target.target.move_to(cpu_left_col_base[i + 1] ) else: cpu_target.target.move_to(cpu_right_col_base[i - 5] ) second_animations.append(MoveToTarget(__magic_name__ , run_time=1.5 ) ) self.play(*__magic_name__ ) self.play(*__magic_name__ ) self.wait()
48
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' import heapq import sys import numpy as np UpperCAmelCase__ : Union[str, Any] = tuple[int, int] class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = set() def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" if not self.empty(): return self.elements[0][0] else: return float("inf" ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.elements ) == 0 def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , __magic_name__ : List[str] ): """simple docstring""" if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(__magic_name__ ) else: # update # print("update", item) lowerCAmelCase__ = [] ((lowerCAmelCase__) ,(lowerCAmelCase__)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((lowerCAmelCase__) ,(lowerCAmelCase__)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Dict ): """simple docstring""" if item in self.set: self.set.remove(__magic_name__ ) lowerCAmelCase__ = [] ((lowerCAmelCase__) ,(lowerCAmelCase__)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((lowerCAmelCase__) ,(lowerCAmelCase__)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.elements[0][1] def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" ((lowerCAmelCase__) ,(lowerCAmelCase__)) = heapq.heappop(self.elements ) self.set.remove(__magic_name__ ) return (priority, item) def A ( UpperCamelCase_ : TPos , UpperCamelCase_ : TPos ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = np.array(UpperCamelCase_ ) lowerCAmelCase__ = np.array(UpperCamelCase_ ) return np.linalg.norm(a - b ) def A ( UpperCamelCase_ : TPos , UpperCamelCase_ : TPos ) -> str: '''simple docstring''' return consistent_heuristic(UpperCamelCase_ , UpperCamelCase_ ) // t def A ( UpperCamelCase_ : TPos , UpperCamelCase_ : TPos ) -> List[Any]: '''simple docstring''' return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def A ( UpperCamelCase_ : TPos , UpperCamelCase_ : int , UpperCamelCase_ : TPos , UpperCamelCase_ : dict[TPos, float] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = g_function[start] + Wa * heuristics[i](UpperCamelCase_ , UpperCamelCase_ ) return ans def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : List[str] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = np.chararray((n, n) ) for i in range(UpperCamelCase_ ): for j in range(UpperCamelCase_ ): lowerCAmelCase__ = "*" for i in range(UpperCamelCase_ ): for j in range(UpperCamelCase_ ): if (j, (n - 1) - i) in blocks: lowerCAmelCase__ = "#" lowerCAmelCase__ = "-" lowerCAmelCase__ = back_pointer[goal] while x != start: ((lowerCAmelCase__) ,(lowerCAmelCase__)) = x # print(x) lowerCAmelCase__ = "-" lowerCAmelCase__ = back_pointer[x] lowerCAmelCase__ = "-" for i in range(UpperCamelCase_ ): for j in range(UpperCamelCase_ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) lowerCAmelCase__ = back_pointer[goal] while x != start: print(UpperCamelCase_ , end=" " ) lowerCAmelCase__ = back_pointer[x] print(UpperCamelCase_ ) sys.exit() def A ( UpperCamelCase_ : TPos ) -> Union[str, Any]: '''simple docstring''' if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def A ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Any , UpperCamelCase_ : List[str] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Any , ) -> int: '''simple docstring''' for itera in range(UpperCamelCase_ ): open_list[itera].remove_element(UpperCamelCase_ ) # print("s", s) # print("j", j) ((lowerCAmelCase__) ,(lowerCAmelCase__)) = s lowerCAmelCase__ = (x - 1, y) lowerCAmelCase__ = (x + 1, y) lowerCAmelCase__ = (x, y + 1) lowerCAmelCase__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(UpperCamelCase_ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(UpperCamelCase_ ) lowerCAmelCase__ = -1 lowerCAmelCase__ = float("inf" ) if valid(UpperCamelCase_ ) and g_function[neighbours] > g_function[s] + 1: lowerCAmelCase__ = g_function[s] + 1 lowerCAmelCase__ = s if neighbours not in close_list_anchor: open_list[0].put(UpperCamelCase_ , key(UpperCamelCase_ , 0 , UpperCamelCase_ , UpperCamelCase_ ) ) if neighbours not in close_list_inad: for var in range(1 , UpperCamelCase_ ): if key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) <= Wa * key( UpperCamelCase_ , 0 , UpperCamelCase_ , UpperCamelCase_ ): open_list[j].put( UpperCamelCase_ , key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) def A ( ) -> str: '''simple docstring''' lowerCAmelCase__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list UpperCAmelCase__ : Union[str, Any] = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} UpperCAmelCase__ : str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] UpperCAmelCase__ : List[Any] = make_common_ground() UpperCAmelCase__ : Optional[int] = blocks_blk # hyper parameters UpperCAmelCase__ : Tuple = 1 UpperCAmelCase__ : Tuple = 1 UpperCAmelCase__ : Optional[int] = 20 UpperCAmelCase__ : List[Any] = 3 # one consistent and two other inconsistent # start and end destination UpperCAmelCase__ : Optional[int] = (0, 0) UpperCAmelCase__ : Union[str, Any] = (n - 1, n - 1) UpperCAmelCase__ : Dict = 1 def A ( UpperCamelCase_ : TPos , UpperCamelCase_ : TPos , UpperCamelCase_ : int ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = {start: 0, goal: float("inf" )} lowerCAmelCase__ = {start: -1, goal: -1} lowerCAmelCase__ = [] lowerCAmelCase__ = set() for i in range(UpperCamelCase_ ): open_list.append(PriorityQueue() ) open_list[i].put(UpperCamelCase_ , key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , UpperCamelCase_ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) else: lowerCAmelCase__ ,lowerCAmelCase__ = open_list[i].top_show() visited.add(UpperCamelCase_ ) expand_state( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ) close_list_inad.append(UpperCamelCase_ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) else: lowerCAmelCase__ = open_list[0].top_show() visited.add(UpperCamelCase_ ) expand_state( UpperCamelCase_ , 0 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ) close_list_anchor.append(UpperCamelCase_ ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(UpperCamelCase_ ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
48
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
1
'''simple docstring''' def A ( UpperCamelCase_ : int , UpperCamelCase_ : int ) -> bool: '''simple docstring''' return numa ^ numa < 0 if __name__ == "__main__": import doctest doctest.testmod()
48
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ : str = sys.version_info >= (3, 10) def A ( UpperCamelCase_ : Any=None , UpperCamelCase_ : List[Any]=None ) -> Optional[int]: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase_ ) @dataclass class A : snake_case__ :int snake_case__ :float snake_case__ :str snake_case__ :bool @dataclass class A : snake_case__ :int = 42 snake_case__ :str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :Optional[bool] = None class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'titi' snake_case__ :Optional[int] = 'toto' class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'titi' snake_case__ :str = 'toto' snake_case__ :int = 42 @dataclass class A : snake_case__ :BasicEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.foo ) @dataclass class A : snake_case__ :MixedTypeEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MixedTypeEnum(self.foo ) @dataclass class A : snake_case__ :Optional[int] = None snake_case__ :Optional[float] = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :Optional[str] = None snake_case__ :Optional[List[str]] = list_field(default=[] ) snake_case__ :Optional[List[int]] = list_field(default=[] ) @dataclass class A : snake_case__ :List[int] = list_field(default=[] ) snake_case__ :List[int] = list_field(default=[1, 2, 3] ) snake_case__ :List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) snake_case__ :List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A : snake_case__ :List[int] = field() snake_case__ :str = field() snake_case__ :BasicEnum = field() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.required_enum ) @dataclass class A : snake_case__ :int snake_case__ :"BasicEnum" = field() snake_case__ :"Optional[bool]" = None snake_case__ :"str" = field(default='toto' , metadata={'help': 'help message'} ) snake_case__ :"List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :bool | None = None @dataclass class A : snake_case__ :int | None = None snake_case__ :float | None = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :str | None = None snake_case__ :list[str] | None = list_field(default=[] ) snake_case__ :list[int] | None = list_field(default=[] ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : argparse.ArgumentParser , __magic_name__ : argparse.ArgumentParser ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , __magic_name__ ) and yy.get("choices" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](__magic_name__ ) , yy["type"](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--bar" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--baz" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--flag" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCAmelCase__) ,) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) expected.add_argument("--baz" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=__magic_name__ , dest="baz" ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) lowerCAmelCase__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" @dataclass class A : snake_case__ :Literal["titi", "toto", 42] = "toto" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) lowerCAmelCase__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--bar" , default=__magic_name__ , type=__magic_name__ , help="help message" ) expected.add_argument("--baz" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=__magic_name__ ) lowerCAmelCase__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) lowerCAmelCase__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--required_str" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCAmelCase__ = parser.parse_dict(__magic_name__ )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_json" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_yaml" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase__ : Optional[int] = { "configuration_rembert": ["REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "RemBertConfig", "RemBertOnnxConfig"] } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Dict = ["RemBertTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : str = ["RemBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ "REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "RemBertForCausalLM", "RemBertForMaskedLM", "RemBertForMultipleChoice", "RemBertForQuestionAnswering", "RemBertForSequenceClassification", "RemBertForTokenClassification", "RemBertLayer", "RemBertModel", "RemBertPreTrainedModel", "load_tf_weights_in_rembert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Dict = [ "TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRemBertForCausalLM", "TFRemBertForMaskedLM", "TFRemBertForMultipleChoice", "TFRemBertForQuestionAnswering", "TFRemBertForSequenceClassification", "TFRemBertForTokenClassification", "TFRemBertLayer", "TFRemBertModel", "TFRemBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_rembert import REMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RemBertConfig, RemBertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert import RemBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_rembert_fast import RemBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rembert import ( REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, RemBertForCausalLM, RemBertForMaskedLM, RemBertForMultipleChoice, RemBertForQuestionAnswering, RemBertForSequenceClassification, RemBertForTokenClassification, RemBertLayer, RemBertModel, RemBertPreTrainedModel, load_tf_weights_in_rembert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rembert import ( TF_REMBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFRemBertForCausalLM, TFRemBertForMaskedLM, TFRemBertForMultipleChoice, TFRemBertForQuestionAnswering, TFRemBertForSequenceClassification, TFRemBertForTokenClassification, TFRemBertLayer, TFRemBertModel, TFRemBertPreTrainedModel, ) else: import sys UpperCAmelCase__ : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' import sys from collections import defaultdict class A : def __init__( self : Any ): """simple docstring""" lowerCAmelCase__ = [] def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[Any] ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = pos def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase__ = 2 * start + 1 else: lowerCAmelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase__ ,lowerCAmelCase__ = heap[smallest_child], positions[smallest_child] lowerCAmelCase__ ,lowerCAmelCase__ = ( heap[start], positions[start], ) lowerCAmelCase__ ,lowerCAmelCase__ = temp, tempa lowerCAmelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = position[index] while index != 0: lowerCAmelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase__ = heap[parent] lowerCAmelCase__ = position[parent] self.set_position(position[parent] , __magic_name__ ) else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , __magic_name__ ) break lowerCAmelCase__ = parent else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , 0 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = positions[0] lowerCAmelCase__ = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def A ( UpperCamelCase_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = Heap() lowerCAmelCase__ = [0] * len(UpperCamelCase_ ) lowerCAmelCase__ = [-1] * len(UpperCamelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase__ = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase__ = [] for vertex in range(len(UpperCamelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase_ ) heap.node_position.append(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = 1 lowerCAmelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase__ = 0 lowerCAmelCase__ = distance heap.heapify(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(1 , len(UpperCamelCase_ ) ): lowerCAmelCase__ = heap.delete_minimum(UpperCamelCase_ , UpperCamelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase_ )] ): lowerCAmelCase__ = distance heap.bottom_to_top( UpperCamelCase_ , heap.get_position(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ : Optional[int] = int(input("Enter number of edges: ").strip()) UpperCAmelCase__ : str = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
48
1
'''simple docstring''' from __future__ import annotations import math def A ( UpperCamelCase_ : int ) -> list[int]: '''simple docstring''' if num <= 0: lowerCAmelCase__ = F"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(UpperCamelCase_ ) lowerCAmelCase__ = [True] * (num + 1) lowerCAmelCase__ = [] lowerCAmelCase__ = 2 lowerCAmelCase__ = int(math.sqrt(UpperCamelCase_ ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(UpperCamelCase_ ) # Set multiples of start be False for i in range(start * start , num + 1 , UpperCamelCase_ ): if sieve[i] is True: lowerCAmelCase__ = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(UpperCamelCase_ ) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
48
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") if is_sentencepiece_available(): import sentencepiece as sp UpperCAmelCase__ : Tuple = 5 UpperCAmelCase__ : List[Any] = 10 @require_sentencepiece @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = SpeechaTextTokenizer snake_case__ :Dict = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().setUp() lowerCAmelCase__ = sp.SentencePieceProcessor() spm_model.Load(__magic_name__ ) lowerCAmelCase__ = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__magic_name__ ) , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [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 __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = 'valhalla/s2t_mustc_multilinguial_medium' snake_case__ :Tuple = 'C\'est trop cool' snake_case__ :List[str] = 'Esto es genial' @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) lowerCAmelCase__ = [ES_CODE, 4, 1601, 47, 7647, 2] lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = "fr" lowerCAmelCase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , __magic_name__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowerCAmelCase__ = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
48
1
'''simple docstring''' import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = field(default='automatic-speech-recognition' , metadata={'include_in_asdict_even_if_is_default': True} ) snake_case__ :ClassVar[Features] = Features({'audio': Audio()} ) snake_case__ :ClassVar[Features] = Features({'transcription': Value('string' )} ) snake_case__ :str = "audio" snake_case__ :str = "transcription" def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Union[str, Any] ): """simple docstring""" if self.audio_column not in features: raise ValueError(f"""Column {self.audio_column} is not present in features.""" ) if not isinstance(features[self.audio_column] , __magic_name__ ): raise ValueError(f"""Column {self.audio_column} is not an Audio type.""" ) lowerCAmelCase__ = copy.deepcopy(self ) lowerCAmelCase__ = self.input_schema.copy() lowerCAmelCase__ = features[self.audio_column] lowerCAmelCase__ = input_schema return task_template @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return {self.audio_column: "audio", self.transcription_column: "transcription"}
48
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCAmelCase__ : Tuple = logging.get_logger(__name__) # General docstring UpperCAmelCase__ : int = "RegNetConfig" # Base docstring UpperCAmelCase__ : Optional[int] = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[int] = [1, 10_88, 7, 7] # Image classification docstring UpperCAmelCase__ : Tuple = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[Any] = "tabby, tabby cat" UpperCAmelCase__ : int = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A ( tf.keras.layers.Layer ): def __init__( self : str , __magic_name__ : int , __magic_name__ : int = 3 , __magic_name__ : int = 1 , __magic_name__ : int = 1 , __magic_name__ : Optional[str] = "relu" , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=__magic_name__ , strides=__magic_name__ , padding="VALID" , groups=__magic_name__ , use_bias=__magic_name__ , name="convolution" , ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else tf.identity def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convolution(self.padding(__magic_name__ ) ) lowerCAmelCase__ = self.normalization(__magic_name__ ) lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : List[Any] , __magic_name__ : RegNetConfig , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config.num_channels lowerCAmelCase__ = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = shape_list(__magic_name__ )[1] if tf.executing_eagerly() and 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." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 2, 3, 1) ) lowerCAmelCase__ = self.embedder(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Any , __magic_name__ : int , __magic_name__ : int = 2 , **__magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=1 , strides=__magic_name__ , use_bias=__magic_name__ , name="convolution" ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : bool = False ): """simple docstring""" return self.normalization(self.convolution(__magic_name__ ) , training=__magic_name__ ) class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) lowerCAmelCase__ = [ tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.pooler(__magic_name__ ) for layer_module in self.attention: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = hidden_state * pooled return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.2" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(__magic_name__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.3" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 2 , __magic_name__ : int = 2 , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer lowerCAmelCase__ = [ # downsampling is done in the first layer with stride of 2 layer(__magic_name__ , __magic_name__ , __magic_name__ , stride=__magic_name__ , name="layers.0" ), *[layer(__magic_name__ , __magic_name__ , __magic_name__ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[str] ): """simple docstring""" for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __magic_name__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__magic_name__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__magic_name__ , __magic_name__ , __magic_name__ , depth=__magic_name__ , name=f"""stages.{i+1}""" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : tf.Tensor , __magic_name__ : bool = False , __magic_name__ : bool = True ): """simple docstring""" lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__magic_name__ ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__magic_name__ , hidden_states=__magic_name__ ) @keras_serializable class A ( tf.keras.layers.Layer ): snake_case__ :List[Any] = RegNetConfig def __init__( self : str , __magic_name__ : Union[str, Any] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config lowerCAmelCase__ = TFRegNetEmbeddings(__magic_name__ , name="embedder" ) lowerCAmelCase__ = TFRegNetEncoder(__magic_name__ , name="encoder" ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) @unpack_inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = self.encoder( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__magic_name__ ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ = tuple([tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__magic_name__ , pooler_output=__magic_name__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = RegNetConfig snake_case__ :Optional[Any] = 'regnet' snake_case__ :Tuple = 'pixel_values' @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} UpperCAmelCase__ : List[str] = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ : Tuple = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~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__ , ) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : RegNetConfig , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : int=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( pixel_values=__magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=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__ , ) class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , *__magic_name__ : Tuple , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) # classification head lowerCAmelCase__ = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : tf.Tensor = None , __magic_name__ : tf.Tensor = None , __magic_name__ : bool = None , __magic_name__ : bool = None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier[0](__magic_name__ ) lowerCAmelCase__ = self.classifier[1](__magic_name__ ) lowerCAmelCase__ = None if labels is None else self.hf_compute_loss(labels=__magic_name__ , logits=__magic_name__ ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__magic_name__ , logits=__magic_name__ , hidden_states=outputs.hidden_states )
48
1
'''simple docstring''' from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
48
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def A ( UpperCamelCase_ : Tuple ) -> int: '''simple docstring''' for param in module.parameters(): lowerCAmelCase__ = False def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = datetime.now() lowerCAmelCase__ = current_time.strftime("%H:%M:%S" ) return timestamp
48
1
'''simple docstring''' # Imports import numpy as np class A : def __init__( self : Optional[int] , __magic_name__ : List[str]=None , __magic_name__ : List[Any]=None , __magic_name__ : Any=None , __magic_name__ : Union[str, Any]=None , __magic_name__ : List[Any]=None ): """simple docstring""" self.set_matricies(red=__magic_name__ , green=__magic_name__ , blue=__magic_name__ , red_edge=__magic_name__ , nir=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Dict=None , __magic_name__ : Dict=None ): """simple docstring""" if red is not None: lowerCAmelCase__ = red if green is not None: lowerCAmelCase__ = green if blue is not None: lowerCAmelCase__ = blue if red_edge is not None: lowerCAmelCase__ = red_edge if nir is not None: lowerCAmelCase__ = nir return True def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[Any]="" , __magic_name__ : Any=None , __magic_name__ : List[Any]=None , __magic_name__ : Union[str, Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]=None ): """simple docstring""" self.set_matricies(red=__magic_name__ , green=__magic_name__ , blue=__magic_name__ , red_edge=__magic_name__ , nir=__magic_name__ ) lowerCAmelCase__ = { "ARVI2": self.arvaa, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!" ) return False def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.nir * (self.red / (self.green**2)) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return (self.nir - self.red) / (self.nir + self.red) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return (self.nir - self.blue) / (self.nir + self.blue) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.redEdge - self.red) / (self.redEdge + self.red) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return (self.nir - self.green) / (self.nir + self.green) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : int=0.08 , __magic_name__ : Optional[Any]=1.22 , __magic_name__ : Union[str, Any]=0.03 ): """simple docstring""" return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return (self.nir / self.green) - 1 def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return (self.nir / self.redEdge) - 1 def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.red - self.blue) / self.red def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.nir - self.green def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Any=0.16 ): """simple docstring""" return (self.nir - self.green) / (self.nir + self.green + y) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Any=0.5 ): """simple docstring""" return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple=None , __magic_name__ : Union[str, Any]=None ): """simple docstring""" return (self.nir - b) / (a * self.red) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.red + self.green + self.blue) / 30.5 def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.nir / self.red def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return (self.rvi() - 1) / (self.rvi() + 1) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.green / (self.nir + self.red + self.green) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return self.nir / (self.nir + self.red + self.green) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return self.red / (self.nir + self.red + self.green) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.green - self.red) / (self.green + self.red) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return (self.red - self.green) / (self.red + self.green) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) lowerCAmelCase__ = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return self.nir / self.red def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return (self.ndvi() + 0.5) ** (1 / 2) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return (self.nir - self.redEdge) / (self.nir + self.redEdge)
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ : List[Any] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
1
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def A ( UpperCamelCase_ : Dict ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = fname.split(os.path.sep )[-1] return re.search(r"^(.*)_\d+\.jpg$" , UpperCamelCase_ ).groups()[0] class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : List[Any] , __magic_name__ : Dict , __magic_name__ : Any=None , __magic_name__ : List[Any]=None ): """simple docstring""" lowerCAmelCase__ = file_names lowerCAmelCase__ = image_transform lowerCAmelCase__ = label_to_id def __len__( self : Any ): """simple docstring""" return len(self.file_names ) def __getitem__( self : List[Any] , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = self.file_names[idx] lowerCAmelCase__ = PIL.Image.open(__magic_name__ ) lowerCAmelCase__ = raw_image.convert("RGB" ) if self.image_transform is not None: lowerCAmelCase__ = self.image_transform(__magic_name__ ) lowerCAmelCase__ = extract_label(__magic_name__ ) if self.label_to_id is not None: lowerCAmelCase__ = self.label_to_id[label] return {"image": image, "label": label} def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] ) -> List[str]: '''simple docstring''' if args.with_tracking: lowerCAmelCase__ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: lowerCAmelCase__ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase__ = config["lr"] lowerCAmelCase__ = int(config["num_epochs"] ) lowerCAmelCase__ = int(config["seed"] ) lowerCAmelCase__ = int(config["batch_size"] ) lowerCAmelCase__ = config["image_size"] if not isinstance(UpperCamelCase_ , (list, tuple) ): lowerCAmelCase__ = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , "isdigit" ): if args.checkpointing_steps == "epoch": lowerCAmelCase__ = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): lowerCAmelCase__ = int(args.checkpointing_steps ) else: raise ValueError( F"""Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.""" ) else: lowerCAmelCase__ = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: lowerCAmelCase__ = os.path.split(UpperCamelCase_ )[-1].split("." )[0] accelerator.init_trackers(UpperCamelCase_ , UpperCamelCase_ ) # Grab all the image filenames lowerCAmelCase__ = [os.path.join(args.data_dir , UpperCamelCase_ ) for fname in os.listdir(args.data_dir ) if fname.endswith(".jpg" )] # Build the label correspondences lowerCAmelCase__ = [extract_label(UpperCamelCase_ ) for fname in file_names] lowerCAmelCase__ = list(set(UpperCamelCase_ ) ) id_to_label.sort() lowerCAmelCase__ = {lbl: i for i, lbl in enumerate(UpperCamelCase_ )} # Set the seed before splitting the data. np.random.seed(UpperCamelCase_ ) torch.manual_seed(UpperCamelCase_ ) torch.cuda.manual_seed_all(UpperCamelCase_ ) # Split our filenames between train and validation lowerCAmelCase__ = np.random.permutation(len(UpperCamelCase_ ) ) lowerCAmelCase__ = int(0.8 * len(UpperCamelCase_ ) ) lowerCAmelCase__ = random_perm[:cut] lowerCAmelCase__ = random_perm[cut:] # For training we use a simple RandomResizedCrop lowerCAmelCase__ = Compose([RandomResizedCrop(UpperCamelCase_ , scale=(0.5, 1.0) ), ToTensor()] ) lowerCAmelCase__ = PetsDataset( [file_names[i] for i in train_split] , image_transform=UpperCamelCase_ , label_to_id=UpperCamelCase_ ) # For evaluation, we use a deterministic Resize lowerCAmelCase__ = Compose([Resize(UpperCamelCase_ ), ToTensor()] ) lowerCAmelCase__ = PetsDataset([file_names[i] for i in eval_split] , image_transform=UpperCamelCase_ , label_to_id=UpperCamelCase_ ) # Instantiate dataloaders. lowerCAmelCase__ = DataLoader(UpperCamelCase_ , shuffle=UpperCamelCase_ , batch_size=UpperCamelCase_ , num_workers=4 ) lowerCAmelCase__ = DataLoader(UpperCamelCase_ , shuffle=UpperCamelCase_ , batch_size=UpperCamelCase_ , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase__ = create_model("resnet50d" , pretrained=UpperCamelCase_ , num_classes=len(UpperCamelCase_ ) ) # 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). lowerCAmelCase__ = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): lowerCAmelCase__ = False for param in model.get_classifier().parameters(): lowerCAmelCase__ = True # We normalize the batches of images to be a bit faster. lowerCAmelCase__ = torch.tensor(model.default_cfg["mean"] )[None, :, None, None].to(accelerator.device ) lowerCAmelCase__ = torch.tensor(model.default_cfg["std"] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer lowerCAmelCase__ = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler lowerCAmelCase__ = OneCycleLR(optimizer=UpperCamelCase_ , max_lr=UpperCamelCase_ , epochs=UpperCamelCase_ , steps_per_epoch=len(UpperCamelCase_ ) ) # 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. lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # We need to keep track of how many total steps we have iterated over lowerCAmelCase__ = 0 # We also need to keep track of the starting epoch so files are named properly lowerCAmelCase__ = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""" ) accelerator.load_state(args.resume_from_checkpoint ) lowerCAmelCase__ = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint lowerCAmelCase__ = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) lowerCAmelCase__ = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` lowerCAmelCase__ = os.path.splitext(UpperCamelCase_ )[0] if "epoch" in training_difference: lowerCAmelCase__ = int(training_difference.replace("epoch_" , "" ) ) + 1 lowerCAmelCase__ = None else: lowerCAmelCase__ = int(training_difference.replace("step_" , "" ) ) lowerCAmelCase__ = resume_step // len(UpperCamelCase_ ) resume_step -= starting_epoch * len(UpperCamelCase_ ) # Now we train the model for epoch in range(UpperCamelCase_ , UpperCamelCase_ ): model.train() if args.with_tracking: lowerCAmelCase__ = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step lowerCAmelCase__ = accelerator.skip_first_batches(UpperCamelCase_ , UpperCamelCase_ ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader lowerCAmelCase__ = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. lowerCAmelCase__ = {k: v.to(accelerator.device ) for k, v in batch.items()} lowerCAmelCase__ = (batch["image"] - mean) / std lowerCAmelCase__ = model(UpperCamelCase_ ) lowerCAmelCase__ = torch.nn.functional.cross_entropy(UpperCamelCase_ , batch["label"] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(UpperCamelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase__ = F"""step_{overall_step}""" if overall_step % checkpointing_steps == 0: if args.output_dir is not None: lowerCAmelCase__ = os.path.join(args.output_dir , UpperCamelCase_ ) accelerator.save_state(UpperCamelCase_ ) model.eval() lowerCAmelCase__ = 0 lowerCAmelCase__ = 0 for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. lowerCAmelCase__ = {k: v.to(accelerator.device ) for k, v in batch.items()} lowerCAmelCase__ = (batch["image"] - mean) / std with torch.no_grad(): lowerCAmelCase__ = model(UpperCamelCase_ ) lowerCAmelCase__ = outputs.argmax(dim=-1 ) lowerCAmelCase__ ,lowerCAmelCase__ = accelerator.gather_for_metrics((predictions, batch["label"]) ) lowerCAmelCase__ = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() lowerCAmelCase__ = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F"""epoch {epoch}: {1_00 * eval_metric:.2f}""" ) if args.with_tracking: accelerator.log( { "accuracy": 1_00 * eval_metric, "train_loss": total_loss.item() / len(UpperCamelCase_ ), "epoch": epoch, } , step=UpperCamelCase_ , ) if checkpointing_steps == "epoch": lowerCAmelCase__ = F"""epoch_{epoch}""" if args.output_dir is not None: lowerCAmelCase__ = os.path.join(args.output_dir , UpperCamelCase_ ) accelerator.save_state(UpperCamelCase_ ) if args.with_tracking: accelerator.end_training() def A ( ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument("--data_dir" , required=UpperCamelCase_ , help="The data folder on disk." ) parser.add_argument("--fp16" , action="store_true" , help="If passed, will use FP16 training." ) parser.add_argument( "--mixed_precision" , type=UpperCamelCase_ , default=UpperCamelCase_ , 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." ) parser.add_argument( "--checkpointing_steps" , type=UpperCamelCase_ , default=UpperCamelCase_ , help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch." , ) parser.add_argument( "--output_dir" , type=UpperCamelCase_ , default="." , help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory." , ) parser.add_argument( "--resume_from_checkpoint" , type=UpperCamelCase_ , default=UpperCamelCase_ , help="If the training should continue from a checkpoint folder." , ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=UpperCamelCase_ , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = {"lr": 3E-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 2_24} training_function(UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
48
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
1
'''simple docstring''' 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 ): def __init__( self : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : int=7 , __magic_name__ : List[str]=3 , __magic_name__ : Optional[Any]=18 , __magic_name__ : Optional[Any]=30 , __magic_name__ : Any=400 , __magic_name__ : List[Any]=True , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=True , ): """simple docstring""" lowerCAmelCase__ = size if size is not None else {"height": 18, "width": 18} lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = image_size lowerCAmelCase__ = min_resolution lowerCAmelCase__ = max_resolution lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = apply_ocr def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Union[str, Any] = LayoutLMvaImageProcessor if is_pytesseract_available() else None def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = LayoutLMvaImageProcessingTester(self ) @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__magic_name__ , "do_resize" ) ) self.assertTrue(hasattr(__magic_name__ , "size" ) ) self.assertTrue(hasattr(__magic_name__ , "apply_ocr" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) lowerCAmelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" pass def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , Image.Image ) # Test not batched input lowerCAmelCase__ = 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 , __magic_name__ ) self.assertIsInstance(encoding.boxes , __magic_name__ ) # Test batched lowerCAmelCase__ = image_processing(__magic_name__ , 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 __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , numpify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , np.ndarray ) # Test not batched input lowerCAmelCase__ = 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 lowerCAmelCase__ = image_processing(__magic_name__ , 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 __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowerCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__magic_name__ , torchify=__magic_name__ ) for image in image_inputs: self.assertIsInstance(__magic_name__ , torch.Tensor ) # Test not batched input lowerCAmelCase__ = 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 lowerCAmelCase__ = image_processing(__magic_name__ , 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 __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = LayoutLMvaImageProcessor() from datasets import load_dataset lowerCAmelCase__ = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) lowerCAmelCase__ = Image.open(ds[0]["file"] ).convert("RGB" ) lowerCAmelCase__ = image_processing(__magic_name__ , 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 lowerCAmelCase__ = [["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 lowerCAmelCase__ = [[[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 , __magic_name__ ) self.assertListEqual(encoding.boxes , __magic_name__ ) # with apply_OCR = False lowerCAmelCase__ = LayoutLMvaImageProcessor(apply_ocr=__magic_name__ ) lowerCAmelCase__ = image_processing(__magic_name__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 224, 224) )
48
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A : def __init__( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : str=13 , __magic_name__ : List[str]=7 , __magic_name__ : Tuple=True , __magic_name__ : Tuple=True , __magic_name__ : str=True , __magic_name__ : int=True , __magic_name__ : int=99 , __magic_name__ : List[str]=[1, 1, 2] , __magic_name__ : Dict=1 , __magic_name__ : Tuple=32 , __magic_name__ : Any=4 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : List[str]=0.1 , __magic_name__ : Tuple=0.0 , __magic_name__ : int=512 , __magic_name__ : Optional[int]=3 , __magic_name__ : List[str]=0.02 , __magic_name__ : Dict=3 , __magic_name__ : List[Any]=4 , __magic_name__ : Any=None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = block_sizes lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = d_model lowerCAmelCase__ = n_head lowerCAmelCase__ = d_head lowerCAmelCase__ = d_inner lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = 2 lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope lowerCAmelCase__ = initializer_std # Used in the tests to check the size of the first attention layer lowerCAmelCase__ = n_head # Used in the tests to check the size of the first hidden state lowerCAmelCase__ = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCAmelCase__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCAmelCase__ = self.num_hidden_layers + 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForPreTraining(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForMaskedLM(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForSequenceClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : List[str] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = TFFunnelForMultipleChoice(config=__magic_name__ ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForTokenClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForQuestionAnswering(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) snake_case__ :Any = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) snake_case__ :str = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @require_tf class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) snake_case__ :int = False snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self , base=__magic_name__ ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__magic_name__ )
48
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : int = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ : List[Any] = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ : List[str] = { "facebook/nllb-large-en-ro": 10_24, "facebook/nllb-200-distilled-600M": 10_24, } # fmt: off UpperCAmelCase__ : Union[str, Any] = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = VOCAB_FILES_NAMES snake_case__ :Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :List[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :str = NllbTokenizer snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : str , __magic_name__ : Dict=None , __magic_name__ : List[str]=None , __magic_name__ : List[Any]="<s>" , __magic_name__ : Any="</s>" , __magic_name__ : Tuple="</s>" , __magic_name__ : str="<s>" , __magic_name__ : Optional[int]="<unk>" , __magic_name__ : str="<pad>" , __magic_name__ : int="<mask>" , __magic_name__ : List[Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Any=None , __magic_name__ : Optional[Any]=False , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = legacy_behaviour super().__init__( vocab_file=__magic_name__ , tokenizer_file=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , src_lang=__magic_name__ , tgt_lang=__magic_name__ , additional_special_tokens=__magic_name__ , legacy_behaviour=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = False if not self.vocab_file else True lowerCAmelCase__ = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} ) lowerCAmelCase__ = { lang_code: self.convert_tokens_to_ids(__magic_name__ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } lowerCAmelCase__ = src_lang if src_lang is not None else "eng_Latn" lowerCAmelCase__ = self.convert_tokens_to_ids(self._src_lang ) lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : int ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : str = "eng_Latn" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "fra_Latn" , **__magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) if self.legacy_behaviour: lowerCAmelCase__ = [] lowerCAmelCase__ = [self.eos_token_id, self.cur_lang_code] else: lowerCAmelCase__ = [self.cur_lang_code] lowerCAmelCase__ = [self.eos_token_id] lowerCAmelCase__ = self.convert_ids_to_tokens(self.prefix_tokens ) lowerCAmelCase__ = self.convert_ids_to_tokens(self.suffix_tokens ) lowerCAmelCase__ = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) if self.legacy_behaviour: lowerCAmelCase__ = [] lowerCAmelCase__ = [self.eos_token_id, self.cur_lang_code] else: lowerCAmelCase__ = [self.cur_lang_code] lowerCAmelCase__ = [self.eos_token_id] lowerCAmelCase__ = self.convert_ids_to_tokens(self.prefix_tokens ) lowerCAmelCase__ = self.convert_ids_to_tokens(self.suffix_tokens ) lowerCAmelCase__ = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory.""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ): copyfile(self.vocab_file , __magic_name__ ) return (out_vocab_file,)
48
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
1
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black UpperCAmelCase__ : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. UpperCAmelCase__ : List[str] = " def __init__(self, config):\n super().__init__()\n self.transform = BertPredictionHeadTransform(config)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n self.decoder.bias = self.bias\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n" class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = tempfile.mkdtemp() os.makedirs(os.path.join(self.transformer_dir , "models/bert/" ) ) lowerCAmelCase__ = self.transformer_dir shutil.copy( os.path.join(__magic_name__ , "src/transformers/models/bert/modeling_bert.py" ) , os.path.join(self.transformer_dir , "models/bert/modeling_bert.py" ) , ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = "src/transformers" shutil.rmtree(self.transformer_dir ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : int , __magic_name__ : Tuple=None ): """simple docstring""" lowerCAmelCase__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: lowerCAmelCase__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + overwrite_result lowerCAmelCase__ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 ) lowerCAmelCase__ = black.format_str(__magic_name__ , mode=__magic_name__ ) lowerCAmelCase__ = os.path.join(self.transformer_dir , "new_code.py" ) with open(__magic_name__ , "w" , newline="\n" ) as f: f.write(__magic_name__ ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__magic_name__ ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__magic_name__ ) with open(__magic_name__ , "r" ) as f: self.assertTrue(f.read() , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = check_copies.find_code_in_transformers("models.bert.modeling_bert.BertLMPredictionHead" ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , REFERENCE_CODE + "\n" , ) # With no empty line at the end self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead" , "BertLMPredictionHead" , __magic_name__ , ) # Copy consistency with rename self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , re.sub("Bert" , "TestModel" , __magic_name__ ) , ) # Copy consistency with a really long name lowerCAmelCase__ = "TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason" self.check_copy_consistency( f"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , f"""{long_class_name}LMPredictionHead""" , re.sub("Bert" , __magic_name__ , __magic_name__ ) , ) # Copy consistency with overwrite self.check_copy_consistency( "# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel" , "TestModelLMPredictionHead" , __magic_name__ , overwrite_result=re.sub("Bert" , "TestModel" , __magic_name__ ) , ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = check_copies.LOCALIZED_READMES["README_zh-hans.md"] lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace)," " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**" " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders" " as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang" " Luong, Quoc V. Le, Christopher D. Manning." ) lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文" " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自" " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather" " than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le," " Christopher D. Manning 发布。\n" ) lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md( __magic_name__ , __magic_name__ , localized_readme["format_model_list"] ) self.assertFalse(__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md( __magic_name__ , __magic_name__ , localized_readme["format_model_list"] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(__magic_name__ ) lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut." ) lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and" " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) lowerCAmelCase__ = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) lowerCAmelCase__ ,lowerCAmelCase__ = check_copies.convert_to_localized_md( __magic_name__ , __magic_name__ , localized_readme["format_model_list"] ) # Check if the model link is synchronized. self.assertEqual(__magic_name__ , __magic_name__ )
48
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : str , __magic_name__ : float ): """simple docstring""" if nodea not in self.connections: self.add_node(__magic_name__ ) if nodea not in self.connections: self.add_node(__magic_name__ ) lowerCAmelCase__ = probability def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return list(self.connections ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[tuple[str, str, float]] , UpperCamelCase_ : int ) -> dict[str, int]: '''simple docstring''' lowerCAmelCase__ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = Counter(graph.get_nodes() ) lowerCAmelCase__ = start for _ in range(UpperCamelCase_ ): lowerCAmelCase__ = graph.transition(UpperCamelCase_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = ['pixel_values'] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = PILImageResampling.BILINEAR , __magic_name__ : bool = True , __magic_name__ : Union[int, float] = 1 / 255 , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : bool = True , **__magic_name__ : Union[str, Any] , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 224} lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) lowerCAmelCase__ = crop_size if crop_size is not None else {"height": 256, "width": 256} lowerCAmelCase__ = get_size_dict(__magic_name__ , param_name="crop_size" ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_center_crop lowerCAmelCase__ = crop_size lowerCAmelCase__ = do_flip_channel_order def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : PILImageResampling = PIL.Image.BILINEAR , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) if "shortest_edge" not in size: raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}""" ) lowerCAmelCase__ = get_resize_output_image_size(__magic_name__ , size=size["shortest_edge"] , default_to_square=__magic_name__ ) return resize(__magic_name__ , size=__magic_name__ , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = get_size_dict(__magic_name__ ) 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()}""" ) return center_crop(__magic_name__ , size=(size["height"], size["width"]) , data_format=__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : np.ndarray , __magic_name__ : Union[int, float] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Optional[int] , ): """simple docstring""" return rescale(__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : np.ndarray , __magic_name__ : Optional[Union[str, ChannelDimension]] = None ): """simple docstring""" return flip_channel_order(__magic_name__ , data_format=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : ImageInput , __magic_name__ : bool = None , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = None , __magic_name__ : bool = None , __magic_name__ : float = None , __magic_name__ : bool = None , __magic_name__ : Dict[str, int] = None , __magic_name__ : bool = None , __magic_name__ : Optional[Union[str, TensorType]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCAmelCase__ = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) lowerCAmelCase__ = crop_size if crop_size is not None else self.crop_size lowerCAmelCase__ = get_size_dict(__magic_name__ , param_name="crop_size" ) lowerCAmelCase__ = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(__magic_name__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=__magic_name__ , size=__magic_name__ , resample=__magic_name__ ) for image in images] if do_center_crop: lowerCAmelCase__ = [self.center_crop(image=__magic_name__ , size=__magic_name__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=__magic_name__ , scale=__magic_name__ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: lowerCAmelCase__ = [self.flip_channel_order(image=__magic_name__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Tuple] = None ): """simple docstring""" lowerCAmelCase__ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(__magic_name__ ): lowerCAmelCase__ = target_sizes.numpy() lowerCAmelCase__ = [] for idx in range(len(__magic_name__ ) ): lowerCAmelCase__ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=__magic_name__ ) lowerCAmelCase__ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__magic_name__ ) else: lowerCAmelCase__ = logits.argmax(dim=1 ) lowerCAmelCase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
48
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
1
'''simple docstring''' import os import unittest from transformers.models.cpmant.tokenization_cpmant import VOCAB_FILES_NAMES, CpmAntTokenizer from transformers.testing_utils import require_jieba, tooslow from ...test_tokenization_common import TokenizerTesterMixin @require_jieba class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :List[Any] = CpmAntTokenizer snake_case__ :str = False def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" super().setUp() lowerCAmelCase__ = [ "<d>", "</d>", "<s>", "</s>", "</_>", "<unk>", "<pad>", "</n>", "我", "是", "C", "P", "M", "A", "n", "t", ] lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) @tooslow def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = CpmAntTokenizer.from_pretrained("openbmb/cpm-ant-10b" ) lowerCAmelCase__ = "今天天气真好!" lowerCAmelCase__ = ["今天", "天气", "真", "好", "!"] lowerCAmelCase__ = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = "今天天气真好!" lowerCAmelCase__ = [tokenizer.bos_token] + tokens lowerCAmelCase__ = [6, 9802, 14962, 2082, 831, 244] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) lowerCAmelCase__ = tokenizer.decode(__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ )
48
'''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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase__ : int = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'facebook/nllb-200-distilled-600M' snake_case__ :Optional[Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) snake_case__ :List[Any] = 'translator' snake_case__ :List[Any] = AutoTokenizer snake_case__ :Optional[Any] = AutoModelForSeqaSeqLM snake_case__ :List[str] = LANGUAGE_CODES snake_case__ :List[Any] = ['text', 'text', 'text'] snake_case__ :List[Any] = ['text'] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ): """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __magic_name__ , return_tensors="pt" , src_lang=__magic_name__ , tgt_lang=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__magic_name__ )
48
1
'''simple docstring''' from ...processing_utils import ProcessorMixin class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :List[Any] = ['image_processor', 'feature_extractor'] snake_case__ :Tuple = 'TvltImageProcessor' snake_case__ :List[str] = 'TvltFeatureExtractor' def __init__( self : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : Tuple ): """simple docstring""" super().__init__(image_processor=__magic_name__ , feature_extractor=__magic_name__ ) lowerCAmelCase__ = image_processor lowerCAmelCase__ = feature_extractor def __call__( self : Optional[Any] , __magic_name__ : Optional[Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]=None , __magic_name__ : Any=None , __magic_name__ : List[Any]=False , __magic_name__ : Union[str, Any]=False , *__magic_name__ : Optional[int] , **__magic_name__ : Optional[Any] , ): """simple docstring""" if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) lowerCAmelCase__ = None if images is not None: lowerCAmelCase__ = self.image_processor(__magic_name__ , mask_pixel=__magic_name__ , *__magic_name__ , **__magic_name__ ) if images_mixed is not None: lowerCAmelCase__ = self.image_processor(__magic_name__ , is_mixed=__magic_name__ , *__magic_name__ , **__magic_name__ ) if audio is not None: lowerCAmelCase__ = self.feature_extractor( __magic_name__ , *__magic_name__ , sampling_rate=__magic_name__ , mask_audio=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = {} if audio is not None: output_dict.update(__magic_name__ ) if images is not None: output_dict.update(__magic_name__ ) if images_mixed_dict is not None: output_dict.update(__magic_name__ ) return output_dict @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = self.image_processor.model_input_names lowerCAmelCase__ = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
48
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'timm_backbone' def __init__( self : Tuple , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=3 , __magic_name__ : Dict=True , __magic_name__ : str=True , __magic_name__ : List[Any]=None , **__magic_name__ : Tuple , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = backbone lowerCAmelCase__ = num_channels lowerCAmelCase__ = features_only lowerCAmelCase__ = use_pretrained_backbone lowerCAmelCase__ = True lowerCAmelCase__ = out_indices if out_indices is not None else (-1,)
48
1
'''simple docstring''' import importlib.util import os import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import ( is_accelerate_available, is_flax_available, is_safetensors_available, is_tf_available, is_torch_available, ) from . import BaseTransformersCLICommand def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' return EnvironmentCommand() def A ( UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' return EnvironmentCommand(args.accelerate_config_file ) class A ( SCREAMING_SNAKE_CASE__ ): @staticmethod def __SCREAMING_SNAKE_CASE ( __magic_name__ : ArgumentParser ): """simple docstring""" lowerCAmelCase__ = parser.add_parser("env" ) download_parser.set_defaults(func=__magic_name__ ) download_parser.add_argument( "--accelerate-config_file" , default=__magic_name__ , help="The accelerate config file to use for the default values in the launching script." , ) download_parser.set_defaults(func=__magic_name__ ) def __init__( self : List[Any] , __magic_name__ : Union[str, Any] , *__magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = accelerate_config_file def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "not installed" if is_safetensors_available(): import safetensors lowerCAmelCase__ = safetensors.__version__ elif importlib.util.find_spec("safetensors" ) is not None: import safetensors lowerCAmelCase__ = f"""{safetensors.__version__} but is ignored because of PyTorch version too old.""" lowerCAmelCase__ = "not installed" lowerCAmelCase__ = lowerCAmelCase__ = "not found" if is_accelerate_available(): import accelerate from accelerate.commands.config import default_config_file, load_config_from_file lowerCAmelCase__ = accelerate.__version__ # Get the default from the config file. if self._accelerate_config_file is not None or os.path.isfile(__magic_name__ ): lowerCAmelCase__ = load_config_from_file(self._accelerate_config_file ).to_dict() lowerCAmelCase__ = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(__magic_name__ , __magic_name__ ) else f"""\t{accelerate_config}""" ) lowerCAmelCase__ = "not installed" lowerCAmelCase__ = "NA" if is_torch_available(): import torch lowerCAmelCase__ = torch.__version__ lowerCAmelCase__ = torch.cuda.is_available() lowerCAmelCase__ = "not installed" lowerCAmelCase__ = "NA" if is_tf_available(): import tensorflow as tf lowerCAmelCase__ = tf.__version__ try: # deprecated in v2.1 lowerCAmelCase__ = tf.test.is_gpu_available() except AttributeError: # returns list of devices, convert to bool lowerCAmelCase__ = bool(tf.config.list_physical_devices("GPU" ) ) lowerCAmelCase__ = "not installed" lowerCAmelCase__ = "not installed" lowerCAmelCase__ = "not installed" lowerCAmelCase__ = "NA" if is_flax_available(): import flax import jax import jaxlib lowerCAmelCase__ = flax.__version__ lowerCAmelCase__ = jax.__version__ lowerCAmelCase__ = jaxlib.__version__ lowerCAmelCase__ = jax.lib.xla_bridge.get_backend().platform lowerCAmelCase__ = { "`transformers` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Huggingface_hub version": huggingface_hub.__version__, "Safetensors version": f"""{safetensors_version}""", "Accelerate version": f"""{accelerate_version}""", "Accelerate config": f"""{accelerate_config_str}""", "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "Tensorflow version (GPU?)": f"""{tf_version} ({tf_cuda_available})""", "Flax version (CPU?/GPU?/TPU?)": f"""{flax_version} ({jax_backend})""", "Jax version": f"""{jax_version}""", "JaxLib version": f"""{jaxlib_version}""", "Using GPU in script?": "<fill in>", "Using distributed or parallel set-up in script?": "<fill in>", } print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" ) print(self.format_dict(__magic_name__ ) ) return info @staticmethod def __SCREAMING_SNAKE_CASE ( __magic_name__ : List[Any] ): """simple docstring""" return "\n".join([f"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
48
'''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. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'Salesforce/blip-image-captioning-base' snake_case__ :List[Any] = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case__ :List[Any] = 'image_captioner' snake_case__ :Optional[int] = AutoModelForVisionaSeq snake_case__ :Optional[int] = ['image'] snake_case__ :Any = ['text'] def __init__( self : str , *__magic_name__ : List[str] , **__magic_name__ : Tuple ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : "Image" ): """simple docstring""" return self.pre_processor(images=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Optional[int] ): """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0].strip()
48
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class A : def __init__( self : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int=13 , __magic_name__ : List[Any]=7 , __magic_name__ : Any=True , __magic_name__ : Optional[int]=True , __magic_name__ : Tuple=False , __magic_name__ : List[Any]=True , __magic_name__ : List[Any]=99 , __magic_name__ : List[Any]=32 , __magic_name__ : str=5 , __magic_name__ : int=4 , __magic_name__ : Dict=37 , __magic_name__ : Tuple="gelu" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : Optional[int]=0.1 , __magic_name__ : List[str]=512 , __magic_name__ : Dict=16 , __magic_name__ : Any=2 , __magic_name__ : Any=0.02 , __magic_name__ : Tuple=3 , __magic_name__ : List[str]=4 , __magic_name__ : Union[str, Any]=None , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__magic_name__ , initializer_range=self.initializer_range , use_stable_embedding=__magic_name__ , ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = OpenLlamaModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any] , ): """simple docstring""" lowerCAmelCase__ = True lowerCAmelCase__ = OpenLlamaModel(__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model( __magic_name__ , attention_mask=__magic_name__ , encoder_hidden_states=__magic_name__ , encoder_attention_mask=__magic_name__ , ) lowerCAmelCase__ = model( __magic_name__ , attention_mask=__magic_name__ , encoder_hidden_states=__magic_name__ , ) lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , ): """simple docstring""" lowerCAmelCase__ = OpenLlamaForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : int , __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : Dict , __magic_name__ : Union[str, Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = OpenLlamaForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # first forward pass lowerCAmelCase__ = model( __magic_name__ , attention_mask=__magic_name__ , encoder_hidden_states=__magic_name__ , encoder_attention_mask=__magic_name__ , use_cache=__magic_name__ , ) lowerCAmelCase__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCAmelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase__ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCAmelCase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCAmelCase__ = torch.cat([input_mask, next_mask] , dim=-1 ) lowerCAmelCase__ = model( __magic_name__ , attention_mask=__magic_name__ , encoder_hidden_states=__magic_name__ , encoder_attention_mask=__magic_name__ , output_hidden_states=__magic_name__ , )["hidden_states"][0] lowerCAmelCase__ = model( __magic_name__ , attention_mask=__magic_name__ , encoder_hidden_states=__magic_name__ , encoder_attention_mask=__magic_name__ , past_key_values=__magic_name__ , output_hidden_states=__magic_name__ , )["hidden_states"][0] # select random slice lowerCAmelCase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCAmelCase__ = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCAmelCase__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Dict = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) snake_case__ :Tuple = (OpenLlamaForCausalLM,) if is_torch_available() else () snake_case__ :List[str] = ( { 'feature-extraction': OpenLlamaModel, 'text-classification': OpenLlamaForSequenceClassification, 'text-generation': OpenLlamaForCausalLM, 'zero-shot': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ :List[str] = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = OpenLlamaModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCAmelCase__ = type self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = 3 lowerCAmelCase__ = input_dict["input_ids"] lowerCAmelCase__ = input_ids.ne(1 ).to(__magic_name__ ) lowerCAmelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase__ = OpenLlamaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = 3 lowerCAmelCase__ = "single_label_classification" lowerCAmelCase__ = input_dict["input_ids"] lowerCAmelCase__ = input_ids.ne(1 ).to(__magic_name__ ) lowerCAmelCase__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase__ = OpenLlamaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = 3 lowerCAmelCase__ = "multi_label_classification" lowerCAmelCase__ = input_dict["input_ids"] lowerCAmelCase__ = input_ids.ne(1 ).to(__magic_name__ ) lowerCAmelCase__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCAmelCase__ = OpenLlamaForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("Open-Llama buffers include complex numbers, which breaks this test" ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" pass @parameterized.expand([("linear",), ("dynamic",)] ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] ): """simple docstring""" lowerCAmelCase__ ,lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = ids_tensor([1, 10] , config.vocab_size ) lowerCAmelCase__ = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase__ = OpenLlamaModel(__magic_name__ ) original_model.to(__magic_name__ ) original_model.eval() lowerCAmelCase__ = original_model(__magic_name__ ).last_hidden_state lowerCAmelCase__ = original_model(__magic_name__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase__ = {"type": scaling_type, "factor": 10.0} lowerCAmelCase__ = OpenLlamaModel(__magic_name__ ) scaled_model.to(__magic_name__ ) scaled_model.eval() lowerCAmelCase__ = scaled_model(__magic_name__ ).last_hidden_state lowerCAmelCase__ = scaled_model(__magic_name__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-5 ) )
48
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = "▁" UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model"} UpperCAmelCase__ : Union[str, Any] = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } UpperCAmelCase__ : Optional[Any] = { "facebook/mbart-large-50-one-to-many-mmt": 10_24, } # fmt: off UpperCAmelCase__ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Any = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : int , __magic_name__ : int , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]="</s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : List[Any]="<s>" , __magic_name__ : Tuple="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : List[Any]="<mask>" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__magic_name__ , tgt_lang=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__magic_name__ ) ) lowerCAmelCase__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__magic_name__ ) } lowerCAmelCase__ = {v: k for k, v in self.lang_code_to_id.items()} lowerCAmelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowerCAmelCase__ = src_lang if src_lang is not None else "en_XX" lowerCAmelCase__ = self.lang_code_to_id[self._src_lang] lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : List[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str ): """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(__magic_name__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = 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(__magic_name__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(__magic_name__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) lowerCAmelCase__ = [1] * len(self.prefix_tokens ) lowerCAmelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__magic_name__ )) + suffix_ones return prefix_ones + ([0] * len(__magic_name__ )) + ([0] * len(__magic_name__ )) + suffix_ones def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str = "en_XX" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "ro_RO" , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[src_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[tgt_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id]
48
1
'''simple docstring''' from copy import deepcopy class A : def __init__( self : List[str] , __magic_name__ : list[int] | None = None , __magic_name__ : int | None = None ): """simple docstring""" if arr is None and size is not None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size elif arr is not None: self.init(__magic_name__ ) else: raise ValueError("Either arr or size must be specified" ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : list[int] ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) lowerCAmelCase__ = deepcopy(__magic_name__ ) for i in range(1 , self.size ): lowerCAmelCase__ = self.next_(__magic_name__ ) if j < self.size: self.tree[j] += self.tree[i] def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): lowerCAmelCase__ = self.next_(__magic_name__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def __SCREAMING_SNAKE_CASE ( __magic_name__ : int ): """simple docstring""" return index + (index & (-index)) @staticmethod def __SCREAMING_SNAKE_CASE ( __magic_name__ : int ): """simple docstring""" return index - (index & (-index)) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value lowerCAmelCase__ = self.next_(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" self.add(__magic_name__ , value - self.get(__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : int ): """simple docstring""" if right == 0: return 0 lowerCAmelCase__ = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] lowerCAmelCase__ = self.prev(__magic_name__ ) return result def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : int , __magic_name__ : int ): """simple docstring""" return self.prefix(__magic_name__ ) - self.prefix(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int ): """simple docstring""" return self.query(__magic_name__ , index + 1 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : int ): """simple docstring""" value -= self.tree[0] if value < 0: return -1 lowerCAmelCase__ = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 lowerCAmelCase__ = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
48
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _in_place_partition(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) count += _in_place_quick_sort(UpperCamelCase_ , UpperCamelCase_ , p - 1 ) count += _in_place_quick_sort(UpperCamelCase_ , p + 1 , UpperCamelCase_ ) return count def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = start - 1 for index in range(UpperCamelCase_ , UpperCamelCase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class A : snake_case__ :str = BlenderbotSmallConfig snake_case__ :Dict = {} snake_case__ :Union[str, Any] = 'gelu' def __init__( self : Any , __magic_name__ : int , __magic_name__ : int=13 , __magic_name__ : int=7 , __magic_name__ : Any=True , __magic_name__ : Tuple=False , __magic_name__ : Union[str, Any]=99 , __magic_name__ : Union[str, Any]=32 , __magic_name__ : Tuple=2 , __magic_name__ : List[str]=4 , __magic_name__ : List[Any]=37 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : Union[str, Any]=20 , __magic_name__ : Tuple=2 , __magic_name__ : List[str]=1 , __magic_name__ : Union[str, Any]=0 , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = pad_token_id lowerCAmelCase__ = bos_token_id def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCAmelCase__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCAmelCase__ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = prepare_blenderbot_small_inputs_dict(__magic_name__ , __magic_name__ , __magic_name__ ) return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Dict , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = TFBlenderbotSmallModel(config=__magic_name__ ).get_decoder() lowerCAmelCase__ = inputs_dict["input_ids"] lowerCAmelCase__ = input_ids[:1, :] lowerCAmelCase__ = inputs_dict["attention_mask"][:1, :] lowerCAmelCase__ = inputs_dict["head_mask"] lowerCAmelCase__ = 1 # first forward pass lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , head_mask=__magic_name__ , use_cache=__magic_name__ ) lowerCAmelCase__ ,lowerCAmelCase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCAmelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCAmelCase__ = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCAmelCase__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ )[0] lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCAmelCase__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCAmelCase__ = output_from_no_past[:, -3:, random_slice_idx] lowerCAmelCase__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__magic_name__ , __magic_name__ , rtol=1E-3 ) def A ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : str=None , UpperCamelCase_ : List[str]=None , UpperCamelCase_ : Dict=None , UpperCamelCase_ : List[str]=None , UpperCamelCase_ : List[str]=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: lowerCAmelCase__ = tf.cast(tf.math.not_equal(UpperCamelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCAmelCase__ = 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: lowerCAmelCase__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase__ = 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 ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :List[Any] = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) snake_case__ :Dict = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () snake_case__ :int = ( { 'conversational': TFBlenderbotSmallForConditionalGeneration, 'feature-extraction': TFBlenderbotSmallModel, 'summarization': TFBlenderbotSmallForConditionalGeneration, 'text2text-generation': TFBlenderbotSmallForConditionalGeneration, 'translation': TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) snake_case__ :Optional[Any] = True snake_case__ :Any = False snake_case__ :int = False def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = TFBlenderbotSmallModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__magic_name__ ) @require_tokenizers @require_tf class A ( unittest.TestCase ): snake_case__ :Any = [ '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?' ] snake_case__ :Dict = 'facebook/blenderbot_small-90M' @cached_property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) @cached_property def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.tokenizer(self.src_text , return_tensors="tf" ) lowerCAmelCase__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__magic_name__ , ) lowerCAmelCase__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__magic_name__ )[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.", )
48
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def A ( UpperCamelCase_ : List[Any] ) -> Tuple: '''simple docstring''' if "img_encoder.pos_embed" in name: lowerCAmelCase__ = name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: lowerCAmelCase__ = name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: lowerCAmelCase__ = name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCAmelCase__ = name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: lowerCAmelCase__ = name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: lowerCAmelCase__ = name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: lowerCAmelCase__ = name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: lowerCAmelCase__ = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: lowerCAmelCase__ = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: lowerCAmelCase__ = name.replace("c_fc" , "fc1" ) if "c_proj" in name: lowerCAmelCase__ = name.replace("c_proj" , "fc2" ) if "text_encoder" in name: lowerCAmelCase__ = name.replace("text_encoder" , "text_model" ) if "ln_final" in name: lowerCAmelCase__ = name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: lowerCAmelCase__ = name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: lowerCAmelCase__ = name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: lowerCAmelCase__ = name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: lowerCAmelCase__ = name.replace("text_projector.linear_out" , "text_projection.3" ) return name def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> List[Any]: '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCAmelCase__ = orig_state_dict.pop(UpperCamelCase_ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ ,lowerCAmelCase__ = int(key_split[2] ), int(key_split[4] ) lowerCAmelCase__ = config.vision_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ = int(key_split[3] ) lowerCAmelCase__ = config.text_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[ dim : dim * 2, : ] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] else: lowerCAmelCase__ = rename_key(UpperCamelCase_ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCAmelCase__ = val.squeeze_() else: lowerCAmelCase__ = val return orig_state_dict def A ( ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple="groupvit-gcc-yfcc" , UpperCamelCase_ : Dict=False ) -> Any: '''simple docstring''' lowerCAmelCase__ = GroupViTConfig() lowerCAmelCase__ = GroupViTModel(UpperCamelCase_ ).eval() lowerCAmelCase__ = torch.load(UpperCamelCase_ , map_location="cpu" )["model"] lowerCAmelCase__ = convert_state_dict(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(UpperCamelCase_ ) == 0) # verify result lowerCAmelCase__ = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = processor(text=["a photo of a cat", "a photo of a dog"] , images=UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors="pt" ) with torch.no_grad(): lowerCAmelCase__ = model(**UpperCamelCase_ ) if model_name == "groupvit-gcc-yfcc": lowerCAmelCase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowerCAmelCase__ = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(F"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image , UpperCamelCase_ , atol=1E-3 ) processor.save_pretrained(UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) print("Successfully saved processor and model to" , UpperCamelCase_ ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(UpperCamelCase_ , organization="nielsr" ) model.push_to_hub(UpperCamelCase_ , organization="nielsr" ) if __name__ == "__main__": UpperCAmelCase__ : List[str] = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) UpperCAmelCase__ : Any = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
48
1
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ : Optional[Any] = 1_00 UpperCAmelCase__ : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def A ( UpperCamelCase_ : int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} lowerCAmelCase__ = set() lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A ( UpperCamelCase_ : int = 50_00 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , UpperCamelCase_ ): if len(partition(UpperCamelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
48
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Optional[int] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} UpperCAmelCase__ : List[Any] = { "vocab_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/vocab.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/vocab.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/vocab.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json" ), }, "merges_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/merges.txt", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/merges.txt", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/merges.txt", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt", "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt" ), }, "tokenizer_file": { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/tokenizer.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/tokenizer.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json", "roberta-base-openai-detector": ( "https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json" ), "roberta-large-openai-detector": ( "https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json" ), }, } UpperCAmelCase__ : Tuple = { "roberta-base": 5_12, "roberta-large": 5_12, "roberta-large-mnli": 5_12, "distilroberta-base": 5_12, "roberta-base-openai-detector": 5_12, "roberta-large-openai-detector": 5_12, } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Dict = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Optional[Any] = ['input_ids', 'attention_mask'] snake_case__ :Optional[int] = RobertaTokenizer def __init__( self : Union[str, Any] , __magic_name__ : Any=None , __magic_name__ : Union[str, Any]=None , __magic_name__ : Tuple=None , __magic_name__ : int="replace" , __magic_name__ : Optional[int]="<s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : Tuple="</s>" , __magic_name__ : int="<s>" , __magic_name__ : Optional[int]="<unk>" , __magic_name__ : Tuple="<pad>" , __magic_name__ : List[str]="<mask>" , __magic_name__ : Dict=False , __magic_name__ : Union[str, Any]=True , **__magic_name__ : int , ): """simple docstring""" super().__init__( __magic_name__ , __magic_name__ , tokenizer_file=__magic_name__ , errors=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , add_prefix_space=__magic_name__ , trim_offsets=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , __magic_name__ ) != add_prefix_space: lowerCAmelCase__ = getattr(__magic_name__ , pre_tok_state.pop("type" ) ) lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = pre_tok_class(**__magic_name__ ) lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = "post_processor" lowerCAmelCase__ = getattr(self.backend_tokenizer , __magic_name__ , __magic_name__ ) if tokenizer_component_instance: lowerCAmelCase__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: lowerCAmelCase__ = tuple(state["sep"] ) if "cls" in state: lowerCAmelCase__ = tuple(state["cls"] ) lowerCAmelCase__ = False if state.get("add_prefix_space" , __magic_name__ ) != add_prefix_space: lowerCAmelCase__ = add_prefix_space lowerCAmelCase__ = True if state.get("trim_offsets" , __magic_name__ ) != trim_offsets: lowerCAmelCase__ = trim_offsets lowerCAmelCase__ = True if changes_to_apply: lowerCAmelCase__ = getattr(__magic_name__ , state.pop("type" ) ) lowerCAmelCase__ = component_class(**__magic_name__ ) setattr(self.backend_tokenizer , __magic_name__ , __magic_name__ ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else value lowerCAmelCase__ = value def __SCREAMING_SNAKE_CASE ( self : int , *__magic_name__ : Union[str, Any] , **__magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = kwargs.get("is_split_into_words" , __magic_name__ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any , *__magic_name__ : Any , **__magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = kwargs.get("is_split_into_words" , __magic_name__ ) assert self.add_prefix_space or not is_split_into_words, ( f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" lowerCAmelCase__ = self._tokenizer.model.save(__magic_name__ , name=__magic_name__ ) return tuple(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[int] , __magic_name__ : Optional[int]=None ): """simple docstring""" lowerCAmelCase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
48
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "vocab.json"} UpperCAmelCase__ : Optional[Any] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } UpperCAmelCase__ : Union[str, Any] = {"mgp-str": 27} class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = VOCAB_FILES_NAMES snake_case__ :Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : int="[GO]" , __magic_name__ : Optional[Any]="[GO]" , __magic_name__ : List[str]="[s]" , __magic_name__ : str="[GO]" , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__( unk_token=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , pad_token=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding="utf-8" ) as vocab_handle: lowerCAmelCase__ = json.load(__magic_name__ ) lowerCAmelCase__ = {v: k for k, v in self.vocab.items()} @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.vocab ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = [] for s in text: char_tokens.extend(__magic_name__ ) return char_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Tuple ): """simple docstring""" return self.decoder.get(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error("Vocabulary path ({}) should be a directory".format(__magic_name__ ) ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + "\n" ) return (vocab_file,)
48
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class A : snake_case__ :Dict = PegasusConfig snake_case__ :str = {} snake_case__ :Tuple = 'gelu' def __init__( self : Union[str, Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=13 , __magic_name__ : str=7 , __magic_name__ : int=True , __magic_name__ : int=False , __magic_name__ : str=99 , __magic_name__ : Dict=32 , __magic_name__ : Tuple=2 , __magic_name__ : str=4 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : List[Any]=0.1 , __magic_name__ : Any=0.1 , __magic_name__ : Union[str, Any]=40 , __magic_name__ : Tuple=2 , __magic_name__ : Any=1 , __magic_name__ : str=0 , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = eos_token_id lowerCAmelCase__ = pad_token_id lowerCAmelCase__ = bos_token_id def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowerCAmelCase__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowerCAmelCase__ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = 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 , ) lowerCAmelCase__ = prepare_pegasus_inputs_dict(__magic_name__ , __magic_name__ , __magic_name__ ) return config, inputs_dict def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = TFPegasusModel(config=__magic_name__ ).get_decoder() lowerCAmelCase__ = inputs_dict["input_ids"] lowerCAmelCase__ = input_ids[:1, :] lowerCAmelCase__ = inputs_dict["attention_mask"][:1, :] lowerCAmelCase__ = inputs_dict["head_mask"] lowerCAmelCase__ = 1 # first forward pass lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , head_mask=__magic_name__ , use_cache=__magic_name__ ) lowerCAmelCase__ ,lowerCAmelCase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowerCAmelCase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowerCAmelCase__ = tf.concat([input_ids, next_tokens] , axis=-1 ) lowerCAmelCase__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ )[0] lowerCAmelCase__ = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowerCAmelCase__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowerCAmelCase__ = output_from_no_past[:, -3:, random_slice_idx] lowerCAmelCase__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__magic_name__ , __magic_name__ , rtol=1E-3 ) def A ( UpperCamelCase_ : str , UpperCamelCase_ : Any , UpperCamelCase_ : str , UpperCamelCase_ : int=None , UpperCamelCase_ : Optional[Any]=None , UpperCamelCase_ : Union[str, Any]=None , UpperCamelCase_ : Union[str, Any]=None , UpperCamelCase_ : List[str]=None , ) -> Any: '''simple docstring''' if attention_mask is None: lowerCAmelCase__ = tf.cast(tf.math.not_equal(UpperCamelCase_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowerCAmelCase__ = 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: lowerCAmelCase__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase__ = 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 ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Dict = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () snake_case__ :Optional[Any] = (TFPegasusForConditionalGeneration,) if is_tf_available() else () snake_case__ :List[str] = ( { 'conversational': TFPegasusForConditionalGeneration, 'feature-extraction': TFPegasusModel, 'summarization': TFPegasusForConditionalGeneration, 'text2text-generation': TFPegasusForConditionalGeneration, 'translation': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) snake_case__ :Tuple = True snake_case__ :Any = False snake_case__ :Union[str, Any] = False def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = TFPegasusModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__magic_name__ ) @require_sentencepiece @require_tokenizers @require_tf class A ( unittest.TestCase ): snake_case__ :Any = [ ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.', ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ', ] snake_case__ :str = [ 'California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to' ' reduce the risk of wildfires.', 'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.', ] # differs slightly from pytorch, likely due to numerical differences in linear layers snake_case__ :Optional[int] = 'google/pegasus-xsum' @cached_property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def __SCREAMING_SNAKE_CASE ( self : int , **__magic_name__ : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.translate_src_text(**__magic_name__ ) assert self.expected_text == generated_words def __SCREAMING_SNAKE_CASE ( self : List[Any] , **__magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = self.tokenizer(self.src_text , **__magic_name__ , padding=__magic_name__ , return_tensors="tf" ) lowerCAmelCase__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__magic_name__ , ) lowerCAmelCase__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__magic_name__ ) return generated_words @slow def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" self._assert_generated_batch_equal_expected()
48
'''simple docstring''' from math import sqrt def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , int(sqrt(UpperCamelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase_ ): total += i + n // i elif i == sqrt(UpperCamelCase_ ): total += i return total - n def A ( UpperCamelCase_ : int = 1_00_00 ) -> int: '''simple docstring''' lowerCAmelCase__ = sum( i for i in range(1 , UpperCamelCase_ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase_ ) ) == i and sum_of_divisors(UpperCamelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
48
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "laion/clap-htsat-unfused" lowerCAmelCase__ = tempfile.mkdtemp() def __SCREAMING_SNAKE_CASE ( self : List[str] , **__magic_name__ : Any ): """simple docstring""" return RobertaTokenizer.from_pretrained(self.checkpoint , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any , **__magic_name__ : Any ): """simple docstring""" return ClapFeatureExtractor.from_pretrained(self.checkpoint , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = ClapProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) lowerCAmelCase__ = self.get_feature_extractor(do_normalize=__magic_name__ , padding_value=1.0 ) lowerCAmelCase__ = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=__magic_name__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __magic_name__ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = ClapProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) lowerCAmelCase__ = floats_list((3, 1000) ) lowerCAmelCase__ = feature_extractor(__magic_name__ , return_tensors="np" ) lowerCAmelCase__ = processor(audios=__magic_name__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = ClapProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) lowerCAmelCase__ = "This is a test string" lowerCAmelCase__ = processor(text=__magic_name__ ) lowerCAmelCase__ = tokenizer(__magic_name__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = ClapProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) lowerCAmelCase__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase__ = processor.batch_decode(__magic_name__ ) lowerCAmelCase__ = tokenizer.batch_decode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = ClapProcessor(tokenizer=__magic_name__ , feature_extractor=__magic_name__ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
48
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance UpperCAmelCase__ : Optional[int] = 6_3_7_8_1_3_7.0 UpperCAmelCase__ : Any = 6_3_5_6_7_5_2.3_1_4_2_4_5 UpperCAmelCase__ : List[str] = 6_37_81_37 def A ( UpperCamelCase_ : float , UpperCamelCase_ : float , UpperCamelCase_ : float , UpperCamelCase_ : float ) -> float: '''simple docstring''' lowerCAmelCase__ = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude lowerCAmelCase__ = atan((1 - flattening) * tan(radians(UpperCamelCase_ ) ) ) lowerCAmelCase__ = atan((1 - flattening) * tan(radians(UpperCamelCase_ ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius lowerCAmelCase__ = haversine_distance(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) / EQUATORIAL_RADIUS # Intermediate P and Q values lowerCAmelCase__ = (b_lata + b_lata) / 2 lowerCAmelCase__ = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) lowerCAmelCase__ = (sin(UpperCamelCase_ ) ** 2) * (cos(UpperCamelCase_ ) ** 2) lowerCAmelCase__ = cos(sigma / 2 ) ** 2 lowerCAmelCase__ = (sigma - sin(UpperCamelCase_ )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) lowerCAmelCase__ = (cos(UpperCamelCase_ ) ** 2) * (sin(UpperCamelCase_ ) ** 2) lowerCAmelCase__ = sin(sigma / 2 ) ** 2 lowerCAmelCase__ = (sigma + sin(UpperCamelCase_ )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
48
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
1
'''simple docstring''' from __future__ import annotations def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[str] | None = None ) -> list[list[str]]: '''simple docstring''' lowerCAmelCase__ = word_bank or [] # create a table lowerCAmelCase__ = len(UpperCamelCase_ ) + 1 lowerCAmelCase__ = [] for _ in range(UpperCamelCase_ ): table.append([] ) # seed value lowerCAmelCase__ = [[]] # because empty string has empty combination # iterate through the indices for i in range(UpperCamelCase_ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(UpperCamelCase_ )] == word: lowerCAmelCase__ = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(UpperCamelCase_ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(UpperCamelCase_ )]: combination.reverse() return table[len(UpperCamelCase_ )] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
48
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ : str = sys.version_info >= (3, 10) def A ( UpperCamelCase_ : Any=None , UpperCamelCase_ : List[Any]=None ) -> Optional[int]: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase_ ) @dataclass class A : snake_case__ :int snake_case__ :float snake_case__ :str snake_case__ :bool @dataclass class A : snake_case__ :int = 42 snake_case__ :str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :Optional[bool] = None class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'titi' snake_case__ :Optional[int] = 'toto' class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'titi' snake_case__ :str = 'toto' snake_case__ :int = 42 @dataclass class A : snake_case__ :BasicEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.foo ) @dataclass class A : snake_case__ :MixedTypeEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MixedTypeEnum(self.foo ) @dataclass class A : snake_case__ :Optional[int] = None snake_case__ :Optional[float] = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :Optional[str] = None snake_case__ :Optional[List[str]] = list_field(default=[] ) snake_case__ :Optional[List[int]] = list_field(default=[] ) @dataclass class A : snake_case__ :List[int] = list_field(default=[] ) snake_case__ :List[int] = list_field(default=[1, 2, 3] ) snake_case__ :List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) snake_case__ :List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A : snake_case__ :List[int] = field() snake_case__ :str = field() snake_case__ :BasicEnum = field() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.required_enum ) @dataclass class A : snake_case__ :int snake_case__ :"BasicEnum" = field() snake_case__ :"Optional[bool]" = None snake_case__ :"str" = field(default='toto' , metadata={'help': 'help message'} ) snake_case__ :"List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :bool | None = None @dataclass class A : snake_case__ :int | None = None snake_case__ :float | None = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :str | None = None snake_case__ :list[str] | None = list_field(default=[] ) snake_case__ :list[int] | None = list_field(default=[] ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : argparse.ArgumentParser , __magic_name__ : argparse.ArgumentParser ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , __magic_name__ ) and yy.get("choices" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](__magic_name__ ) , yy["type"](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--bar" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--baz" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--flag" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCAmelCase__) ,) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) expected.add_argument("--baz" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=__magic_name__ , dest="baz" ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) lowerCAmelCase__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" @dataclass class A : snake_case__ :Literal["titi", "toto", 42] = "toto" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) lowerCAmelCase__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--bar" , default=__magic_name__ , type=__magic_name__ , help="help message" ) expected.add_argument("--baz" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=__magic_name__ ) lowerCAmelCase__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) lowerCAmelCase__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--required_str" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCAmelCase__ = parser.parse_dict(__magic_name__ )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_json" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_yaml" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
48
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=SCREAMING_SNAKE_CASE__ ) class A ( SCREAMING_SNAKE_CASE__ ): # `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization snake_case__ :str = field(default='question-answering-extractive' , metadata={'include_in_asdict_even_if_is_default': True} ) snake_case__ :ClassVar[Features] = Features({'question': Value('string' ), 'context': Value('string' )} ) snake_case__ :ClassVar[Features] = Features( { 'answers': Sequence( { 'text': Value('string' ), 'answer_start': Value('int32' ), } ) } ) snake_case__ :str = "question" snake_case__ :str = "context" snake_case__ :str = "answers" @property def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
48
'''simple docstring''' import sys from collections import defaultdict class A : def __init__( self : Any ): """simple docstring""" lowerCAmelCase__ = [] def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[Any] ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = pos def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase__ = 2 * start + 1 else: lowerCAmelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase__ ,lowerCAmelCase__ = heap[smallest_child], positions[smallest_child] lowerCAmelCase__ ,lowerCAmelCase__ = ( heap[start], positions[start], ) lowerCAmelCase__ ,lowerCAmelCase__ = temp, tempa lowerCAmelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = position[index] while index != 0: lowerCAmelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase__ = heap[parent] lowerCAmelCase__ = position[parent] self.set_position(position[parent] , __magic_name__ ) else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , __magic_name__ ) break lowerCAmelCase__ = parent else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , 0 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = positions[0] lowerCAmelCase__ = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def A ( UpperCamelCase_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = Heap() lowerCAmelCase__ = [0] * len(UpperCamelCase_ ) lowerCAmelCase__ = [-1] * len(UpperCamelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase__ = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase__ = [] for vertex in range(len(UpperCamelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase_ ) heap.node_position.append(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = 1 lowerCAmelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase__ = 0 lowerCAmelCase__ = distance heap.heapify(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(1 , len(UpperCamelCase_ ) ): lowerCAmelCase__ = heap.delete_minimum(UpperCamelCase_ , UpperCamelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase_ )] ): lowerCAmelCase__ = distance heap.bottom_to_top( UpperCamelCase_ , heap.get_position(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ : Optional[int] = int(input("Enter number of edges: ").strip()) UpperCAmelCase__ : str = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
48
1
'''simple docstring''' 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 UpperCAmelCase__ : str = logging.get_logger(__name__) UpperCAmelCase__ : Optional[Any] = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = 'data2vec-vision' def __init__( self : Optional[Any] , __magic_name__ : Optional[int]=768 , __magic_name__ : Any=12 , __magic_name__ : int=12 , __magic_name__ : str=3072 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Optional[int]=0.0 , __magic_name__ : Optional[int]=0.0 , __magic_name__ : List[Any]=0.02 , __magic_name__ : Any=1E-12 , __magic_name__ : Dict=224 , __magic_name__ : Dict=16 , __magic_name__ : List[Any]=3 , __magic_name__ : Tuple=False , __magic_name__ : Optional[int]=False , __magic_name__ : Any=False , __magic_name__ : Optional[Any]=False , __magic_name__ : List[Any]=0.1 , __magic_name__ : int=0.1 , __magic_name__ : Tuple=True , __magic_name__ : Dict=[3, 5, 7, 11] , __magic_name__ : int=[1, 2, 3, 6] , __magic_name__ : Union[str, Any]=True , __magic_name__ : int=0.4 , __magic_name__ : int=256 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : Union[str, Any]=False , __magic_name__ : Optional[int]=255 , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = use_mask_token lowerCAmelCase__ = use_absolute_position_embeddings lowerCAmelCase__ = use_relative_position_bias lowerCAmelCase__ = use_shared_relative_position_bias lowerCAmelCase__ = layer_scale_init_value lowerCAmelCase__ = drop_path_rate lowerCAmelCase__ = use_mean_pooling # decode head attributes (semantic segmentation) lowerCAmelCase__ = out_indices lowerCAmelCase__ = pool_scales # auxiliary head attributes (semantic segmentation) lowerCAmelCase__ = use_auxiliary_head lowerCAmelCase__ = auxiliary_loss_weight lowerCAmelCase__ = auxiliary_channels lowerCAmelCase__ = auxiliary_num_convs lowerCAmelCase__ = auxiliary_concat_input lowerCAmelCase__ = semantic_loss_ignore_index class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = version.parse('1.11' ) @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return 1E-4
48
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") if is_sentencepiece_available(): import sentencepiece as sp UpperCAmelCase__ : Tuple = 5 UpperCAmelCase__ : List[Any] = 10 @require_sentencepiece @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = SpeechaTextTokenizer snake_case__ :Dict = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().setUp() lowerCAmelCase__ = sp.SentencePieceProcessor() spm_model.Load(__magic_name__ ) lowerCAmelCase__ = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__magic_name__ ) , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [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 __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = 'valhalla/s2t_mustc_multilinguial_medium' snake_case__ :Tuple = 'C\'est trop cool' snake_case__ :List[str] = 'Esto es genial' @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) lowerCAmelCase__ = [ES_CODE, 4, 1601, 47, 7647, 2] lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = "fr" lowerCAmelCase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , __magic_name__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowerCAmelCase__ = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
48
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : Union[str, Any] = logging.get_logger(__name__) def A ( UpperCamelCase_ : int , UpperCamelCase_ : Optional[Any]=False , UpperCamelCase_ : List[Any]=False ) -> Dict: '''simple docstring''' lowerCAmelCase__ = "backbone." if is_semantic else "" lowerCAmelCase__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""{prefix}blocks.{i}.norm1.weight""", F"""beit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm1.bias""", F"""beit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""{prefix}blocks.{i}.attn.proj.weight""", F"""beit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""{prefix}blocks.{i}.attn.proj.bias""", F"""beit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm2.weight""", F"""beit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.norm2.bias""", F"""beit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.weight""", F"""beit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc1.bias""", F"""beit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.weight""", F"""beit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""{prefix}blocks.{i}.mlp.fc2.bias""", F"""beit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ (F"""{prefix}cls_token""", "beit.embeddings.cls_token"), (F"""{prefix}patch_embed.proj.weight""", "beit.embeddings.patch_embeddings.projection.weight"), (F"""{prefix}patch_embed.proj.bias""", "beit.embeddings.patch_embeddings.projection.bias"), (F"""{prefix}pos_embed""", "beit.embeddings.position_embeddings"), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ("mask_token", "beit.embeddings.mask_token"), ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ] ) else: # layernorm + classification head rename_keys.extend( [ ("fc_norm.weight", "beit.pooler.layernorm.weight"), ("fc_norm.bias", "beit.pooler.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Any=False , UpperCamelCase_ : Any=False ) -> int: '''simple docstring''' for i in range(config.num_hidden_layers ): lowerCAmelCase__ = "backbone." if is_semantic else "" # queries, keys and values lowerCAmelCase__ = state_dict.pop(F"""{prefix}blocks.{i}.attn.qkv.weight""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}blocks.{i}.attn.q_bias""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}blocks.{i}.attn.v_bias""" ) lowerCAmelCase__ = in_proj_weight[ : config.hidden_size, : ] lowerCAmelCase__ = q_bias lowerCAmelCase__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowerCAmelCase__ = in_proj_weight[ -config.hidden_size :, : ] lowerCAmelCase__ = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained lowerCAmelCase__ = state_dict.pop(F"""{prefix}blocks.{i}.gamma_1""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}blocks.{i}.gamma_2""" ) lowerCAmelCase__ = gamma_a lowerCAmelCase__ = gamma_a def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[Any] ) -> List[str]: '''simple docstring''' lowerCAmelCase__ = dct.pop(UpperCamelCase_ ) lowerCAmelCase__ = val def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : Any , UpperCamelCase_ : int , UpperCamelCase_ : int=False ) -> int: '''simple docstring''' lowerCAmelCase__ = False if "rvlcdip" in checkpoint_url else True lowerCAmelCase__ = BeitConfig(use_absolute_position_embeddings=UpperCamelCase_ , use_mask_token=UpperCamelCase_ ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: lowerCAmelCase__ = 10_24 lowerCAmelCase__ = 40_96 lowerCAmelCase__ = 24 lowerCAmelCase__ = 16 # labels if "rvlcdip" in checkpoint_url: lowerCAmelCase__ = 16 lowerCAmelCase__ = "huggingface/label-files" lowerCAmelCase__ = "rvlcdip-id2label.json" lowerCAmelCase__ = json.load(open(hf_hub_download(UpperCamelCase_ , UpperCamelCase_ , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ = {int(UpperCamelCase_ ): v for k, v in idalabel.items()} lowerCAmelCase__ = idalabel lowerCAmelCase__ = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys lowerCAmelCase__ = torch.hub.load_state_dict_from_url(UpperCamelCase_ , map_location="cpu" )["model"] lowerCAmelCase__ = create_rename_keys(UpperCamelCase_ , has_lm_head=UpperCamelCase_ ) for src, dest in rename_keys: rename_key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) read_in_q_k_v(UpperCamelCase_ , UpperCamelCase_ , has_lm_head=UpperCamelCase_ ) # load HuggingFace model lowerCAmelCase__ = BeitForMaskedImageModeling(UpperCamelCase_ ) if has_lm_head else BeitForImageClassification(UpperCamelCase_ ) model.eval() model.load_state_dict(UpperCamelCase_ ) # Check outputs on an image lowerCAmelCase__ = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=UpperCamelCase_ ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = image_processor(images=UpperCamelCase_ , return_tensors="pt" ) lowerCAmelCase__ = encoding["pixel_values"] lowerCAmelCase__ = model(UpperCamelCase_ ) lowerCAmelCase__ = outputs.logits # verify logits lowerCAmelCase__ = [1, 16] if "rvlcdip" in checkpoint_url else [1, 1_96, 81_92] assert logits.shape == torch.Size(UpperCamelCase_ ), "Shape of logits not as expected" Path(UpperCamelCase_ ).mkdir(exist_ok=UpperCamelCase_ ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(UpperCamelCase_ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(UpperCamelCase_ ) if push_to_hub: if has_lm_head: lowerCAmelCase__ = "dit-base" if "base" in checkpoint_url else "dit-large" else: lowerCAmelCase__ = "dit-base-finetuned-rvlcdip" if "dit-b" in checkpoint_url else "dit-large-finetuned-rvlcdip" image_processor.push_to_hub( repo_path_or_name=Path(UpperCamelCase_ , UpperCamelCase_ ) , organization="nielsr" , commit_message="Add image processor" , use_temp_dir=UpperCamelCase_ , ) model.push_to_hub( repo_path_or_name=Path(UpperCamelCase_ , UpperCamelCase_ ) , organization="nielsr" , commit_message="Add model" , use_temp_dir=UpperCamelCase_ , ) if __name__ == "__main__": UpperCAmelCase__ : Any = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", ) UpperCAmelCase__ : List[Any] = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
48
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCAmelCase__ : Tuple = logging.get_logger(__name__) # General docstring UpperCAmelCase__ : int = "RegNetConfig" # Base docstring UpperCAmelCase__ : Optional[int] = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[int] = [1, 10_88, 7, 7] # Image classification docstring UpperCAmelCase__ : Tuple = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[Any] = "tabby, tabby cat" UpperCAmelCase__ : int = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A ( tf.keras.layers.Layer ): def __init__( self : str , __magic_name__ : int , __magic_name__ : int = 3 , __magic_name__ : int = 1 , __magic_name__ : int = 1 , __magic_name__ : Optional[str] = "relu" , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=__magic_name__ , strides=__magic_name__ , padding="VALID" , groups=__magic_name__ , use_bias=__magic_name__ , name="convolution" , ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else tf.identity def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convolution(self.padding(__magic_name__ ) ) lowerCAmelCase__ = self.normalization(__magic_name__ ) lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : List[Any] , __magic_name__ : RegNetConfig , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config.num_channels lowerCAmelCase__ = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = shape_list(__magic_name__ )[1] if tf.executing_eagerly() and 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." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 2, 3, 1) ) lowerCAmelCase__ = self.embedder(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Any , __magic_name__ : int , __magic_name__ : int = 2 , **__magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=1 , strides=__magic_name__ , use_bias=__magic_name__ , name="convolution" ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : bool = False ): """simple docstring""" return self.normalization(self.convolution(__magic_name__ ) , training=__magic_name__ ) class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) lowerCAmelCase__ = [ tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.pooler(__magic_name__ ) for layer_module in self.attention: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = hidden_state * pooled return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.2" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(__magic_name__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.3" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 2 , __magic_name__ : int = 2 , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer lowerCAmelCase__ = [ # downsampling is done in the first layer with stride of 2 layer(__magic_name__ , __magic_name__ , __magic_name__ , stride=__magic_name__ , name="layers.0" ), *[layer(__magic_name__ , __magic_name__ , __magic_name__ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[str] ): """simple docstring""" for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __magic_name__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__magic_name__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__magic_name__ , __magic_name__ , __magic_name__ , depth=__magic_name__ , name=f"""stages.{i+1}""" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : tf.Tensor , __magic_name__ : bool = False , __magic_name__ : bool = True ): """simple docstring""" lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__magic_name__ ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__magic_name__ , hidden_states=__magic_name__ ) @keras_serializable class A ( tf.keras.layers.Layer ): snake_case__ :List[Any] = RegNetConfig def __init__( self : str , __magic_name__ : Union[str, Any] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config lowerCAmelCase__ = TFRegNetEmbeddings(__magic_name__ , name="embedder" ) lowerCAmelCase__ = TFRegNetEncoder(__magic_name__ , name="encoder" ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) @unpack_inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = self.encoder( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__magic_name__ ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ = tuple([tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__magic_name__ , pooler_output=__magic_name__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = RegNetConfig snake_case__ :Optional[Any] = 'regnet' snake_case__ :Tuple = 'pixel_values' @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} UpperCAmelCase__ : List[str] = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ : Tuple = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~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__ , ) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : RegNetConfig , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : int=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( pixel_values=__magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=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__ , ) class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , *__magic_name__ : Tuple , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) # classification head lowerCAmelCase__ = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : tf.Tensor = None , __magic_name__ : tf.Tensor = None , __magic_name__ : bool = None , __magic_name__ : bool = None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier[0](__magic_name__ ) lowerCAmelCase__ = self.classifier[1](__magic_name__ ) lowerCAmelCase__ = None if labels is None else self.hf_compute_loss(labels=__magic_name__ , logits=__magic_name__ ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__magic_name__ , logits=__magic_name__ , hidden_states=outputs.hidden_states )
48
1
'''simple docstring''' from __future__ import annotations def A ( UpperCamelCase_ : list[int | str] ) -> None: '''simple docstring''' create_state_space_tree(UpperCamelCase_ , [] , 0 , [0 for i in range(len(UpperCamelCase_ ) )] ) def A ( UpperCamelCase_ : list[int | str] , UpperCamelCase_ : list[int | str] , UpperCamelCase_ : int , UpperCamelCase_ : list[int] , ) -> None: '''simple docstring''' if index == len(UpperCamelCase_ ): print(UpperCamelCase_ ) return for i in range(len(UpperCamelCase_ ) ): if not index_used[i]: current_sequence.append(sequence[i] ) lowerCAmelCase__ = True create_state_space_tree(UpperCamelCase_ , UpperCamelCase_ , index + 1 , UpperCamelCase_ ) current_sequence.pop() lowerCAmelCase__ = False UpperCAmelCase__ : list[int | str] = [3, 1, 2, 4] generate_all_permutations(sequence) UpperCAmelCase__ : list[int | str] = ["A", "B", "C"] generate_all_permutations(sequence_a)
48
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def A ( UpperCamelCase_ : Tuple ) -> int: '''simple docstring''' for param in module.parameters(): lowerCAmelCase__ = False def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = datetime.now() lowerCAmelCase__ = current_time.strftime("%H:%M:%S" ) return timestamp
48
1
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : str , __magic_name__ : float ): """simple docstring""" if nodea not in self.connections: self.add_node(__magic_name__ ) if nodea not in self.connections: self.add_node(__magic_name__ ) lowerCAmelCase__ = probability def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return list(self.connections ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[tuple[str, str, float]] , UpperCamelCase_ : int ) -> dict[str, int]: '''simple docstring''' lowerCAmelCase__ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = Counter(graph.get_nodes() ) lowerCAmelCase__ = start for _ in range(UpperCamelCase_ ): lowerCAmelCase__ = graph.transition(UpperCamelCase_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ : List[Any] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__) def A ( UpperCamelCase_ : str ) -> int: '''simple docstring''' if "resnet-50" in model_name: lowerCAmelCase__ = ResNetConfig.from_pretrained("microsoft/resnet-50" ) elif "resnet-101" in model_name: lowerCAmelCase__ = ResNetConfig.from_pretrained("microsoft/resnet-101" ) else: raise ValueError("Model name should include either resnet50 or resnet101" ) lowerCAmelCase__ = DetrConfig(use_timm_backbone=UpperCamelCase_ , backbone_config=UpperCamelCase_ ) # set label attributes lowerCAmelCase__ = "panoptic" in model_name if is_panoptic: lowerCAmelCase__ = 2_50 else: lowerCAmelCase__ = 91 lowerCAmelCase__ = "huggingface/label-files" lowerCAmelCase__ = "coco-detection-id2label.json" lowerCAmelCase__ = json.load(open(hf_hub_download(UpperCamelCase_ , UpperCamelCase_ , repo_type="dataset" ) , "r" ) ) lowerCAmelCase__ = {int(UpperCamelCase_ ): v for k, v in idalabel.items()} lowerCAmelCase__ = idalabel lowerCAmelCase__ = {v: k for k, v in idalabel.items()} return config, is_panoptic def A ( UpperCamelCase_ : Tuple ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight") ) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight") ) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias") ) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean") ) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var""", ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean""", ) ) rename_keys.append( ( F"""backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var""", F"""backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var""", ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F"""transformer.encoder.layers.{i}.self_attn.out_proj.weight""", F"""encoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (F"""transformer.encoder.layers.{i}.self_attn.out_proj.bias""", F"""encoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""encoder.layers.{i}.fc1.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""encoder.layers.{i}.fc1.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""encoder.layers.{i}.fc2.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""encoder.layers.{i}.fc2.bias""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm1.weight""", F"""encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm1.bias""", F"""encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (F"""transformer.encoder.layers.{i}.norm2.weight""", F"""encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""encoder.layers.{i}.final_layer_norm.bias""") ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""decoder.layers.{i}.self_attn.out_proj.weight""", ) ) rename_keys.append( (F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.weight""", F"""decoder.layers.{i}.encoder_attn.out_proj.weight""", ) ) rename_keys.append( ( F"""transformer.decoder.layers.{i}.multihead_attn.out_proj.bias""", F"""decoder.layers.{i}.encoder_attn.out_proj.bias""", ) ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""decoder.layers.{i}.fc1.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""decoder.layers.{i}.fc1.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""decoder.layers.{i}.fc2.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""decoder.layers.{i}.fc2.bias""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm1.weight""", F"""decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm1.bias""", F"""decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.weight""", F"""decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm2.bias""", F"""decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append( (F"""transformer.decoder.layers.{i}.norm3.weight""", F"""decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""decoder.layers.{i}.final_layer_norm.bias""") ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) return rename_keys def A ( UpperCamelCase_ : Any , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' lowerCAmelCase__ = state_dict.pop(UpperCamelCase_ ) lowerCAmelCase__ = val def A ( UpperCamelCase_ : List[str] , UpperCamelCase_ : Any=False ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = "" if is_panoptic: lowerCAmelCase__ = "detr." # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) lowerCAmelCase__ = state_dict.pop(F"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ = in_proj_weight[:2_56, :] lowerCAmelCase__ = in_proj_bias[:2_56] lowerCAmelCase__ = in_proj_weight[2_56:5_12, :] lowerCAmelCase__ = in_proj_bias[2_56:5_12] lowerCAmelCase__ = in_proj_weight[-2_56:, :] lowerCAmelCase__ = in_proj_bias[-2_56:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention lowerCAmelCase__ = state_dict.pop(F"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict lowerCAmelCase__ = in_proj_weight[:2_56, :] lowerCAmelCase__ = in_proj_bias[:2_56] lowerCAmelCase__ = in_proj_weight[2_56:5_12, :] lowerCAmelCase__ = in_proj_bias[2_56:5_12] lowerCAmelCase__ = in_proj_weight[-2_56:, :] lowerCAmelCase__ = in_proj_bias[-2_56:] # read in weights + bias of input projection layer of cross-attention lowerCAmelCase__ = state_dict.pop( F"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight""" ) lowerCAmelCase__ = state_dict.pop(F"""{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) of cross-attention to the state dict lowerCAmelCase__ = in_proj_weight_cross_attn[:2_56, :] lowerCAmelCase__ = in_proj_bias_cross_attn[:2_56] lowerCAmelCase__ = in_proj_weight_cross_attn[2_56:5_12, :] lowerCAmelCase__ = in_proj_bias_cross_attn[2_56:5_12] lowerCAmelCase__ = in_proj_weight_cross_attn[-2_56:, :] lowerCAmelCase__ = in_proj_bias_cross_attn[-2_56:] def A ( ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : Union[str, Any]=False ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ ,lowerCAmelCase__ = get_detr_config(UpperCamelCase_ ) # load original model from torch hub lowerCAmelCase__ = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(F"""Converting model {model_name}...""" ) lowerCAmelCase__ = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=UpperCamelCase_ ).eval() lowerCAmelCase__ = detr.state_dict() # rename keys for src, dest in create_rename_keys(UpperCamelCase_ ): if is_panoptic: lowerCAmelCase__ = "detr." + src rename_key(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # query, key and value matrices need special treatment read_in_q_k_v(UpperCamelCase_ , is_panoptic=UpperCamelCase_ ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them lowerCAmelCase__ = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr" ) and not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ) ): lowerCAmelCase__ = state_dict.pop(UpperCamelCase_ ) lowerCAmelCase__ = val elif "class_labels_classifier" in key or "bbox_predictor" in key: lowerCAmelCase__ = state_dict.pop(UpperCamelCase_ ) lowerCAmelCase__ = val elif key.startswith("bbox_attention" ) or key.startswith("mask_head" ): continue else: lowerCAmelCase__ = state_dict.pop(UpperCamelCase_ ) lowerCAmelCase__ = val else: if not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ): lowerCAmelCase__ = state_dict.pop(UpperCamelCase_ ) lowerCAmelCase__ = val # finally, create HuggingFace model and load state dict lowerCAmelCase__ = DetrForSegmentation(UpperCamelCase_ ) if is_panoptic else DetrForObjectDetection(UpperCamelCase_ ) model.load_state_dict(UpperCamelCase_ ) model.eval() # verify our conversion on an image lowerCAmelCase__ = "coco_panoptic" if is_panoptic else "coco_detection" lowerCAmelCase__ = DetrImageProcessor(format=UpperCamelCase_ ) lowerCAmelCase__ = processor(images=prepare_img() , return_tensors="pt" ) lowerCAmelCase__ = encoding["pixel_values"] lowerCAmelCase__ = detr(UpperCamelCase_ ) lowerCAmelCase__ = model(UpperCamelCase_ ) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(UpperCamelCase_ ).mkdir(exist_ok=UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) processor.save_pretrained(UpperCamelCase_ ) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub..." ) model.push_to_hub(F"""nielsr/{model_name}""" ) processor.push_to_hub(F"""nielsr/{model_name}""" ) if __name__ == "__main__": UpperCAmelCase__ : str = argparse.ArgumentParser() parser.add_argument( "--model_name", default="detr-resnet-50", type=str, choices=["detr-resnet-50", "detr-resnet-101"], help="Name of the DETR model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to the hub or not.") UpperCAmelCase__ : Tuple = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
48
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
1
'''simple docstring''' import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : str = logging.get_logger(__name__) def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = RobertaPreLayerNormConfig.from_pretrained( UpperCamelCase_ , architectures=["RobertaPreLayerNormForMaskedLM"] ) # convert state_dict lowerCAmelCase__ = torch.load(hf_hub_download(repo_id=UpperCamelCase_ , filename="pytorch_model.bin" ) ) lowerCAmelCase__ = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith("roberta." ): lowerCAmelCase__ = "roberta_prelayernorm." + tensor_key[len("roberta." ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith(".self.LayerNorm.weight" ) or tensor_key.endswith(".self.LayerNorm.bias" ): continue lowerCAmelCase__ = tensor_value lowerCAmelCase__ = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=UpperCamelCase_ , config=UpperCamelCase_ , state_dict=UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) # convert tokenizer lowerCAmelCase__ = AutoTokenizer.from_pretrained(UpperCamelCase_ ) tokenizer.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint-repo", default=None, type=str, required=True, help="Path the official PyTorch dump, e.g. 'andreasmadsen/efficient_mlm_m0.40'.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) UpperCAmelCase__ : Tuple = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
48
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A : def __init__( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : str=13 , __magic_name__ : List[str]=7 , __magic_name__ : Tuple=True , __magic_name__ : Tuple=True , __magic_name__ : str=True , __magic_name__ : int=True , __magic_name__ : int=99 , __magic_name__ : List[str]=[1, 1, 2] , __magic_name__ : Dict=1 , __magic_name__ : Tuple=32 , __magic_name__ : Any=4 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : List[str]=0.1 , __magic_name__ : Tuple=0.0 , __magic_name__ : int=512 , __magic_name__ : Optional[int]=3 , __magic_name__ : List[str]=0.02 , __magic_name__ : Dict=3 , __magic_name__ : List[Any]=4 , __magic_name__ : Any=None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = block_sizes lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = d_model lowerCAmelCase__ = n_head lowerCAmelCase__ = d_head lowerCAmelCase__ = d_inner lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = 2 lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope lowerCAmelCase__ = initializer_std # Used in the tests to check the size of the first attention layer lowerCAmelCase__ = n_head # Used in the tests to check the size of the first hidden state lowerCAmelCase__ = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCAmelCase__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCAmelCase__ = self.num_hidden_layers + 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForPreTraining(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForMaskedLM(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForSequenceClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : List[str] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = TFFunnelForMultipleChoice(config=__magic_name__ ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForTokenClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForQuestionAnswering(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) snake_case__ :Any = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) snake_case__ :str = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @require_tf class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) snake_case__ :int = False snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self , base=__magic_name__ ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__magic_name__ )
48
1
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
1
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. UpperCAmelCase__ : str = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def A ( UpperCamelCase_ : Any ) -> List[str]: '''simple docstring''' config.addinivalue_line( "markers" , "is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested" ) config.addinivalue_line( "markers" , "is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested" ) config.addinivalue_line("markers" , "is_pipeline_test: mark test to run only when pipelines are tested" ) config.addinivalue_line("markers" , "is_staging_test: mark test to run only in the staging environment" ) config.addinivalue_line("markers" , "accelerate_tests: mark test that require accelerate" ) config.addinivalue_line("markers" , "tool_tests: mark the tool tests that are run on their specific schedule" ) def A ( UpperCamelCase_ : List[str] ) -> Any: '''simple docstring''' from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(UpperCamelCase_ ) def A ( UpperCamelCase_ : int ) -> Union[str, Any]: '''simple docstring''' from transformers.testing_utils import pytest_terminal_summary_main lowerCAmelCase__ = terminalreporter.config.getoption("--make-reports" ) if make_reports: pytest_terminal_summary_main(UpperCamelCase_ , id=UpperCamelCase_ ) def A ( UpperCamelCase_ : int , UpperCamelCase_ : Any ) -> Optional[int]: '''simple docstring''' if exitstatus == 5: lowerCAmelCase__ = 0 # Doctest custom flag to ignore output. UpperCAmelCase__ : List[str] = doctest.register_optionflag("IGNORE_RESULT") UpperCAmelCase__ : Optional[Any] = doctest.OutputChecker class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Tuple ): """simple docstring""" if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , __magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase__ : Any = CustomOutputChecker UpperCAmelCase__ : str = HfDoctestModule UpperCAmelCase__ : Optional[int] = HfDocTestParser
48
'''simple docstring''' from __future__ import annotations from collections import Counter from random import random class A : def __init__( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = {} def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : str , __magic_name__ : float ): """simple docstring""" if nodea not in self.connections: self.add_node(__magic_name__ ) if nodea not in self.connections: self.add_node(__magic_name__ ) lowerCAmelCase__ = probability def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" return list(self.connections ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = 0 lowerCAmelCase__ = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def A ( UpperCamelCase_ : str , UpperCamelCase_ : list[tuple[str, str, float]] , UpperCamelCase_ : int ) -> dict[str, int]: '''simple docstring''' lowerCAmelCase__ = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = Counter(graph.get_nodes() ) lowerCAmelCase__ = start for _ in range(UpperCamelCase_ ): lowerCAmelCase__ = graph.transition(UpperCamelCase_ ) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "microsoft/xprophetnet-large-wiki100-cased": ( "https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json" ), } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :int = 'xlm-prophetnet' snake_case__ :int = ['past_key_values'] snake_case__ :Tuple = { 'num_attention_heads': 'num_encoder_attention_heads', } def __init__( self : Tuple , __magic_name__ : Optional[float] = 0.1 , __magic_name__ : Optional[Union[str, Callable]] = "gelu" , __magic_name__ : Optional[int] = 30522 , __magic_name__ : Optional[int] = 1024 , __magic_name__ : Optional[int] = 4096 , __magic_name__ : Optional[int] = 12 , __magic_name__ : Optional[int] = 16 , __magic_name__ : Optional[int] = 4096 , __magic_name__ : Optional[int] = 12 , __magic_name__ : Optional[int] = 16 , __magic_name__ : Optional[float] = 0.1 , __magic_name__ : Optional[float] = 0.1 , __magic_name__ : Optional[int] = 512 , __magic_name__ : Optional[float] = 0.02 , __magic_name__ : Optional[bool] = True , __magic_name__ : Optional[bool] = True , __magic_name__ : Optional[int] = 0 , __magic_name__ : Optional[int] = 2 , __magic_name__ : Optional[int] = 32 , __magic_name__ : Optional[int] = 128 , __magic_name__ : Optional[bool] = False , __magic_name__ : Optional[float] = 0.0 , __magic_name__ : Optional[bool] = True , __magic_name__ : Optional[int] = 0 , __magic_name__ : Optional[int] = 1 , __magic_name__ : Optional[int] = 2 , **__magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = encoder_ffn_dim lowerCAmelCase__ = num_encoder_layers lowerCAmelCase__ = num_encoder_attention_heads lowerCAmelCase__ = decoder_ffn_dim lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = num_decoder_attention_heads lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = init_std # Normal(0, this parameter) lowerCAmelCase__ = activation_function # parameters for xlmprophetnet lowerCAmelCase__ = ngram lowerCAmelCase__ = num_buckets lowerCAmelCase__ = relative_max_distance lowerCAmelCase__ = disable_ngram_loss lowerCAmelCase__ = eps # 3 Types of Dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = dropout lowerCAmelCase__ = use_cache super().__init__( pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , is_encoder_decoder=__magic_name__ , add_cross_attention=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) @property def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" raise NotImplementedError( "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and" " `num_decoder_layers`." )
48
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available UpperCAmelCase__ : Optional[Any] = { "configuration_audio_spectrogram_transformer": [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ASTConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Tuple = [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ASTForAudioClassification", "ASTModel", "ASTPreTrainedModel", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Any = ["ASTFeatureExtractor"] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys UpperCAmelCase__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''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. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCAmelCase__ : int = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'facebook/nllb-200-distilled-600M' snake_case__ :Optional[Any] = ( 'This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ' 'be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ' 'which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ' 'plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.' ) snake_case__ :List[Any] = 'translator' snake_case__ :List[Any] = AutoTokenizer snake_case__ :Optional[Any] = AutoModelForSeqaSeqLM snake_case__ :List[str] = LANGUAGE_CODES snake_case__ :List[Any] = ['text', 'text', 'text'] snake_case__ :List[Any] = ['text'] def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ): """simple docstring""" if src_lang not in self.lang_to_code: raise ValueError(f"""{src_lang} is not a supported language.""" ) if tgt_lang not in self.lang_to_code: raise ValueError(f"""{tgt_lang} is not a supported language.""" ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( __magic_name__ , return_tensors="pt" , src_lang=__magic_name__ , tgt_lang=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=__magic_name__ )
48
1
'''simple docstring''' import tempfile import unittest import numpy as np from diffusers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionPipeline, PNDMScheduler, ) from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :str = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline' def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Optional[int]=0 ): """simple docstring""" lowerCAmelCase__ = np.random.RandomState(__magic_name__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCAmelCase__ = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCAmelCase__ = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCAmelCase__ = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCAmelCase__ = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) lowerCAmelCase__ = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = pipe(**__magic_name__ ).images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) lowerCAmelCase__ = np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = 3 * [inputs["prompt"]] # forward lowerCAmelCase__ = pipe(**__magic_name__ ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = 3 * [inputs.pop("prompt" )] lowerCAmelCase__ = pipe.tokenizer( __magic_name__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=__magic_name__ , return_tensors="np" , ) lowerCAmelCase__ = text_inputs["input_ids"] lowerCAmelCase__ = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] lowerCAmelCase__ = prompt_embeds # forward lowerCAmelCase__ = pipe(**__magic_name__ ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = 3 * ["this is a negative prompt"] lowerCAmelCase__ = negative_prompt lowerCAmelCase__ = 3 * [inputs["prompt"]] # forward lowerCAmelCase__ = pipe(**__magic_name__ ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] lowerCAmelCase__ = self.get_dummy_inputs() lowerCAmelCase__ = 3 * [inputs.pop("prompt" )] lowerCAmelCase__ = [] for p in [prompt, negative_prompt]: lowerCAmelCase__ = pipe.tokenizer( __magic_name__ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=__magic_name__ , return_tensors="np" , ) lowerCAmelCase__ = text_inputs["input_ids"] embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] ) lowerCAmelCase__ ,lowerCAmelCase__ = embeds # forward lowerCAmelCase__ = pipe(**__magic_name__ ) lowerCAmelCase__ = output.images[0, -3:, -3:, -1] assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @nightly @require_onnxruntime @require_torch_gpu class A ( unittest.TestCase ): @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = ort.SessionOptions() lowerCAmelCase__ = False return options def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = "A painting of a squirrel eating a burger" np.random.seed(0 ) lowerCAmelCase__ = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = DDIMScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = "open neural network exchange" lowerCAmelCase__ = np.random.RandomState(0 ) lowerCAmelCase__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=__magic_name__ , output_type="np" ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = LMSDiscreteScheduler.from_pretrained( "runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" ) lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = "open neural network exchange" lowerCAmelCase__ = np.random.RandomState(0 ) lowerCAmelCase__ = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=__magic_name__ , output_type="np" ) lowerCAmelCase__ = output.images lowerCAmelCase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase__ = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = 0 def test_callback_fn(__magic_name__ : int , __magic_name__ : int , __magic_name__ : np.ndarray ) -> None: lowerCAmelCase__ = True nonlocal number_of_steps number_of_steps += 1 if step == 0: assert latents.shape == (1, 4, 64, 64) lowerCAmelCase__ = latents[0, -3:, -3:, -1] lowerCAmelCase__ = np.array( [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 elif step == 5: assert latents.shape == (1, 4, 64, 64) lowerCAmelCase__ = latents[0, -3:, -3:, -1] lowerCAmelCase__ = np.array( [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3 lowerCAmelCase__ = False lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) lowerCAmelCase__ = "Andromeda galaxy in a bottle" lowerCAmelCase__ = np.random.RandomState(0 ) pipe( prompt=__magic_name__ , num_inference_steps=5 , guidance_scale=7.5 , generator=__magic_name__ , callback=__magic_name__ , callback_steps=1 , ) assert test_callback_fn.has_been_called assert number_of_steps == 6 def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) assert isinstance(__magic_name__ , __magic_name__ ) assert pipe.safety_checker is None lowerCAmelCase__ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) lowerCAmelCase__ = OnnxStableDiffusionPipeline.from_pretrained(__magic_name__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None lowerCAmelCase__ = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None
48
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : int = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'timm_backbone' def __init__( self : Tuple , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=3 , __magic_name__ : Dict=True , __magic_name__ : str=True , __magic_name__ : List[Any]=None , **__magic_name__ : Tuple , ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = backbone lowerCAmelCase__ = num_channels lowerCAmelCase__ = features_only lowerCAmelCase__ = use_pretrained_backbone lowerCAmelCase__ = True lowerCAmelCase__ = out_indices if out_indices is not None else (-1,)
48
1
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "vocab.json"} UpperCAmelCase__ : Optional[Any] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } UpperCAmelCase__ : Union[str, Any] = {"mgp-str": 27} class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = VOCAB_FILES_NAMES snake_case__ :Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : int="[GO]" , __magic_name__ : Optional[Any]="[GO]" , __magic_name__ : List[str]="[s]" , __magic_name__ : str="[GO]" , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__( unk_token=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , pad_token=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding="utf-8" ) as vocab_handle: lowerCAmelCase__ = json.load(__magic_name__ ) lowerCAmelCase__ = {v: k for k, v in self.vocab.items()} @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.vocab ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = [] for s in text: char_tokens.extend(__magic_name__ ) return char_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Tuple ): """simple docstring""" return self.decoder.get(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error("Vocabulary path ({}) should be a directory".format(__magic_name__ ) ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + "\n" ) return (vocab_file,)
48
'''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. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Tuple = 'Salesforce/blip-image-captioning-base' snake_case__ :List[Any] = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) snake_case__ :List[Any] = 'image_captioner' snake_case__ :Optional[int] = AutoModelForVisionaSeq snake_case__ :Optional[int] = ['image'] snake_case__ :Any = ['text'] def __init__( self : str , *__magic_name__ : List[str] , **__magic_name__ : Tuple ): """simple docstring""" requires_backends(self , ["vision"] ) super().__init__(*__magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : "Image" ): """simple docstring""" return self.pre_processor(images=__magic_name__ , return_tensors="pt" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Tuple ): """simple docstring""" return self.model.generate(**__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Optional[int] ): """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0].strip()
48
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. UpperCAmelCase__ : Optional[int] = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING snake_case__ :Optional[Any] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: snake_case__ :List[str] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: snake_case__ :Dict = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="pt" ) lowerCAmelCase__ = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}] ) lowerCAmelCase__ = text_classifier("This is great !" , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}] ) lowerCAmelCase__ = text_classifier(["This is great !", "This is bad"] , top_k=2 ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], ] , ) lowerCAmelCase__ = text_classifier("This is great !" , top_k=1 ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}] ) # Legacy behavior lowerCAmelCase__ = text_classifier("This is great !" , return_all_scores=__magic_name__ ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}] ) lowerCAmelCase__ = text_classifier("This is great !" , return_all_scores=__magic_name__ ) self.assertEqual( nested_simplify(__magic_name__ ) , [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]] ) lowerCAmelCase__ = text_classifier(["This is great !", "Something else"] , return_all_scores=__magic_name__ ) self.assertEqual( nested_simplify(__magic_name__ ) , [ [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}], ] , ) lowerCAmelCase__ = text_classifier(["This is great !", "Something else"] , return_all_scores=__magic_name__ ) self.assertEqual( nested_simplify(__magic_name__ ) , [ {"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_0", "score": 0.504}, ] , ) @require_torch def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" import torch lowerCAmelCase__ = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="pt" , device=torch.device("cpu" ) , ) lowerCAmelCase__ = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}] ) @require_tf def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="tf" ) lowerCAmelCase__ = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "LABEL_0", "score": 0.504}] ) @slow @require_torch def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = pipeline("text-classification" ) lowerCAmelCase__ = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "POSITIVE", "score": 1.0}] ) lowerCAmelCase__ = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "NEGATIVE", "score": 1.0}] ) lowerCAmelCase__ = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "POSITIVE", "score": 0.988}] ) @slow @require_tf def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = pipeline("text-classification" , framework="tf" ) lowerCAmelCase__ = text_classifier("This is great !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "POSITIVE", "score": 1.0}] ) lowerCAmelCase__ = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "NEGATIVE", "score": 1.0}] ) lowerCAmelCase__ = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": "POSITIVE", "score": 0.988}] ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = TextClassificationPipeline(model=__magic_name__ , tokenizer=__magic_name__ ) return text_classifier, ["HuggingFace is in", "This is another test"] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 lowerCAmelCase__ = "HuggingFace is in" lowerCAmelCase__ = text_classifier(__magic_name__ ) self.assertEqual(nested_simplify(__magic_name__ ) , [{"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}] ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) lowerCAmelCase__ = ["HuggingFace is in ", "Paris is in France"] lowerCAmelCase__ = text_classifier(__magic_name__ ) self.assertEqual( nested_simplify(__magic_name__ ) , [{"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}, {"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}] , ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["label"] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format lowerCAmelCase__ = text_classifier(__magic_name__ , top_k=__magic_name__ ) lowerCAmelCase__ = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(__magic_name__ ) , [[{"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}] * N, [{"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}] * N] , ) lowerCAmelCase__ = {"text": "HuggingFace is in ", "text_pair": "Paris is in France"} lowerCAmelCase__ = text_classifier(__magic_name__ ) self.assertEqual( nested_simplify(__magic_name__ ) , {"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )} , ) self.assertTrue(outputs["label"] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. lowerCAmelCase__ = [["HuggingFace is in ", "Paris is in France"]] with self.assertRaises(__magic_name__ ): text_classifier(__magic_name__ ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility lowerCAmelCase__ = text_classifier([[["HuggingFace is in ", "Paris is in France"]]] ) self.assertEqual( nested_simplify(__magic_name__ ) , [{"label": ANY(__magic_name__ ), "score": ANY(__magic_name__ )}] , ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() )
48
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = "▁" UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model"} UpperCAmelCase__ : Union[str, Any] = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } UpperCAmelCase__ : Optional[Any] = { "facebook/mbart-large-50-one-to-many-mmt": 10_24, } # fmt: off UpperCAmelCase__ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Any = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : int , __magic_name__ : int , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]="</s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : List[Any]="<s>" , __magic_name__ : Tuple="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : List[Any]="<mask>" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__magic_name__ , tgt_lang=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__magic_name__ ) ) lowerCAmelCase__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__magic_name__ ) } lowerCAmelCase__ = {v: k for k, v in self.lang_code_to_id.items()} lowerCAmelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowerCAmelCase__ = src_lang if src_lang is not None else "en_XX" lowerCAmelCase__ = self.lang_code_to_id[self._src_lang] lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : List[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str ): """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(__magic_name__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = 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(__magic_name__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(__magic_name__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) lowerCAmelCase__ = [1] * len(self.prefix_tokens ) lowerCAmelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__magic_name__ )) + suffix_ones return prefix_ones + ([0] * len(__magic_name__ )) + ([0] * len(__magic_name__ )) + suffix_ones def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str = "en_XX" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "ro_RO" , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[src_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[tgt_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id]
48
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : List[Any] = { "configuration_jukebox": [ "JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP", "JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig", ], "tokenization_jukebox": ["JukeboxTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = [ "JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST", "JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys UpperCAmelCase__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from random import randint from tempfile import TemporaryFile import numpy as np def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : int , UpperCamelCase_ : List[Any] ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 if start < end: lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ ,lowerCAmelCase__ = _in_place_partition(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) count += _in_place_quick_sort(UpperCamelCase_ , UpperCamelCase_ , p - 1 ) count += _in_place_quick_sort(UpperCamelCase_ , p + 1 , UpperCamelCase_ ) return count def A ( UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Any ) -> Dict: '''simple docstring''' lowerCAmelCase__ = 0 lowerCAmelCase__ = randint(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = a[end] lowerCAmelCase__ = a[pivot] lowerCAmelCase__ = temp lowerCAmelCase__ = start - 1 for index in range(UpperCamelCase_ , UpperCamelCase_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value lowerCAmelCase__ = new_pivot_index + 1 lowerCAmelCase__ = a[new_pivot_index] lowerCAmelCase__ = a[index] lowerCAmelCase__ = temp lowerCAmelCase__ = a[new_pivot_index + 1] lowerCAmelCase__ = a[end] lowerCAmelCase__ = temp return new_pivot_index + 1, count UpperCAmelCase__ : Tuple = TemporaryFile() UpperCAmelCase__ : List[str] = 1_00 # 1000 elements are to be sorted UpperCAmelCase__ , UpperCAmelCase__ : Dict = 0, 1 # mean and standard deviation UpperCAmelCase__ : Tuple = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array UpperCAmelCase__ : Optional[Any] = np.load(outfile) UpperCAmelCase__ : Any = len(M) - 1 UpperCAmelCase__ : Tuple = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
48
1
'''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 ) UpperCAmelCase__ : Optional[int] = logging.getLogger(__name__) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = 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=3_05_22, type=int) UpperCAmelCase__ : Union[str, Any] = parser.parse_args() logger.info(F"Loading data from {args.data_file}") with open(args.data_file, "rb") as fp: UpperCAmelCase__ : Optional[int] = pickle.load(fp) logger.info("Counting occurrences for MLM.") UpperCAmelCase__ : Optional[int] = Counter() for tk_ids in data: counter.update(tk_ids) UpperCAmelCase__ : str = [0] * args.vocab_size for k, v in counter.items(): UpperCAmelCase__ : Dict = 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)
48
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def A ( UpperCamelCase_ : List[Any] ) -> Tuple: '''simple docstring''' if "img_encoder.pos_embed" in name: lowerCAmelCase__ = name.replace("img_encoder.pos_embed" , "vision_model.embeddings.position_embeddings" ) if "img_encoder.patch_embed.proj" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.proj" , "vision_model.embeddings.patch_embeddings.projection" ) if "img_encoder.patch_embed.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.patch_embed.norm" , "vision_model.embeddings.layernorm" ) if "img_encoder.layers" in name: lowerCAmelCase__ = name.replace("img_encoder.layers" , "vision_model.encoder.stages" ) if "blocks" in name and "res" not in name: lowerCAmelCase__ = name.replace("blocks" , "layers" ) if "attn" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("attn" , "self_attn" ) if "proj" in name and "self_attn" in name and "text" not in name: lowerCAmelCase__ = name.replace("proj" , "out_proj" ) if "pre_assign_attn.attn.proj" in name: lowerCAmelCase__ = name.replace("pre_assign_attn.attn.proj" , "pre_assign_attn.attn.out_proj" ) if "norm1" in name: lowerCAmelCase__ = name.replace("norm1" , "layer_norm1" ) if "norm2" in name and "pre_assign" not in name: lowerCAmelCase__ = name.replace("norm2" , "layer_norm2" ) if "img_encoder.norm" in name: lowerCAmelCase__ = name.replace("img_encoder.norm" , "vision_model.layernorm" ) # text encoder if "text_encoder.token_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.token_embedding" , "text_model.embeddings.token_embedding" ) if "text_encoder.positional_embedding" in name: lowerCAmelCase__ = name.replace("text_encoder.positional_embedding" , "text_model.embeddings.position_embedding.weight" ) if "text_encoder.transformer.resblocks." in name: lowerCAmelCase__ = name.replace("text_encoder.transformer.resblocks." , "text_model.encoder.layers." ) if "ln_1" in name: lowerCAmelCase__ = name.replace("ln_1" , "layer_norm1" ) if "ln_2" in name: lowerCAmelCase__ = name.replace("ln_2" , "layer_norm2" ) if "c_fc" in name: lowerCAmelCase__ = name.replace("c_fc" , "fc1" ) if "c_proj" in name: lowerCAmelCase__ = name.replace("c_proj" , "fc2" ) if "text_encoder" in name: lowerCAmelCase__ = name.replace("text_encoder" , "text_model" ) if "ln_final" in name: lowerCAmelCase__ = name.replace("ln_final" , "final_layer_norm" ) # projection layers if "img_projector.linear_hidden." in name: lowerCAmelCase__ = name.replace("img_projector.linear_hidden." , "visual_projection." ) if "img_projector.linear_out." in name: lowerCAmelCase__ = name.replace("img_projector.linear_out." , "visual_projection.3." ) if "text_projector.linear_hidden" in name: lowerCAmelCase__ = name.replace("text_projector.linear_hidden" , "text_projection" ) if "text_projector.linear_out" in name: lowerCAmelCase__ = name.replace("text_projector.linear_out" , "text_projection.3" ) return name def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> List[Any]: '''simple docstring''' for key in orig_state_dict.copy().keys(): lowerCAmelCase__ = orig_state_dict.pop(UpperCamelCase_ ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ ,lowerCAmelCase__ = int(key_split[2] ), int(key_split[4] ) lowerCAmelCase__ = config.vision_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[dim : dim * 2, :] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors lowerCAmelCase__ = key.split("." ) lowerCAmelCase__ = int(key_split[3] ) lowerCAmelCase__ = config.text_config.hidden_size if "weight" in key: lowerCAmelCase__ = val[:dim, :] lowerCAmelCase__ = val[ dim : dim * 2, : ] lowerCAmelCase__ = val[-dim:, :] else: lowerCAmelCase__ = val[:dim] lowerCAmelCase__ = val[dim : dim * 2] lowerCAmelCase__ = val[-dim:] else: lowerCAmelCase__ = rename_key(UpperCamelCase_ ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): lowerCAmelCase__ = val.squeeze_() else: lowerCAmelCase__ = val return orig_state_dict def A ( ) -> Optional[int]: '''simple docstring''' lowerCAmelCase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowerCAmelCase__ = Image.open(requests.get(UpperCamelCase_ , stream=UpperCamelCase_ ).raw ) return im @torch.no_grad() def A ( UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple="groupvit-gcc-yfcc" , UpperCamelCase_ : Dict=False ) -> Any: '''simple docstring''' lowerCAmelCase__ = GroupViTConfig() lowerCAmelCase__ = GroupViTModel(UpperCamelCase_ ).eval() lowerCAmelCase__ = torch.load(UpperCamelCase_ , map_location="cpu" )["model"] lowerCAmelCase__ = convert_state_dict(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ ,lowerCAmelCase__ = model.load_state_dict(UpperCamelCase_ , strict=UpperCamelCase_ ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(UpperCamelCase_ ) == 0) # verify result lowerCAmelCase__ = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32" ) lowerCAmelCase__ = prepare_img() lowerCAmelCase__ = processor(text=["a photo of a cat", "a photo of a dog"] , images=UpperCamelCase_ , padding=UpperCamelCase_ , return_tensors="pt" ) with torch.no_grad(): lowerCAmelCase__ = model(**UpperCamelCase_ ) if model_name == "groupvit-gcc-yfcc": lowerCAmelCase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowerCAmelCase__ = torch.tensor([[16.1_873, 8.6_230]] ) else: raise ValueError(F"""Model name {model_name} not supported.""" ) assert torch.allclose(outputs.logits_per_image , UpperCamelCase_ , atol=1E-3 ) processor.save_pretrained(UpperCamelCase_ ) model.save_pretrained(UpperCamelCase_ ) print("Successfully saved processor and model to" , UpperCamelCase_ ) if push_to_hub: print("Pushing to the hub..." ) processor.push_to_hub(UpperCamelCase_ , organization="nielsr" ) model.push_to_hub(UpperCamelCase_ , organization="nielsr" ) if __name__ == "__main__": UpperCAmelCase__ : List[str] = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to dump the processor and PyTorch model." ) parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to GroupViT checkpoint") parser.add_argument( "--model_name", default="groupvit-gccy-fcc", type=str, help="Name of the model. Expecting either 'groupvit-gcc-yfcc' or 'groupvit-gcc-redcaps'", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.", ) UpperCAmelCase__ : Any = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
48
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase__ : Optional[Any] = logging.getLogger(__name__) def A ( UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int ) -> int: '''simple docstring''' return (preds == labels).mean() @dataclass class A : snake_case__ :str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) snake_case__ :Optional[str] = field( default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) snake_case__ :Optional[str] = field( default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) snake_case__ :Optional[str] = field( default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class A : snake_case__ :str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys() )} ) snake_case__ :str = field(metadata={'help': 'Should contain the data files for the task.'} ) snake_case__ :int = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) snake_case__ :bool = field( default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def A ( ) -> Any: '''simple docstring''' lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" " --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , UpperCamelCase_ ) # Set seed set_seed(training_args.seed ) try: lowerCAmelCase__ = processors[data_args.task_name]() lowerCAmelCase__ = processor.get_labels() lowerCAmelCase__ = len(UpperCamelCase_ ) except KeyError: raise ValueError("Task not found: %s" % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=UpperCamelCase_ , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoModelForMultipleChoice.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=UpperCamelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=UpperCamelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=UpperCamelCase_ , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def compute_metrics(UpperCamelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ = np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(UpperCamelCase_ , p.label_ids )} # Data collator lowerCAmelCase__ = DataCollatorWithPadding(UpperCamelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=UpperCamelCase_ , args=UpperCamelCase_ , train_dataset=UpperCamelCase_ , eval_dataset=UpperCamelCase_ , compute_metrics=UpperCamelCase_ , data_collator=UpperCamelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_master(): with open(UpperCamelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , UpperCamelCase_ , UpperCamelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(UpperCamelCase_ ) return results def A ( UpperCamelCase_ : int ) -> str: '''simple docstring''' main() if __name__ == "__main__": main()
48
'''simple docstring''' from __future__ import annotations from functools import lru_cache from math import ceil UpperCAmelCase__ : Optional[Any] = 1_00 UpperCAmelCase__ : Any = set(range(3, NUM_PRIMES, 2)) primes.add(2) UpperCAmelCase__ : int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def A ( UpperCamelCase_ : int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} lowerCAmelCase__ = set() lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def A ( UpperCamelCase_ : int = 50_00 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , UpperCamelCase_ ): if len(partition(UpperCamelCase_ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(F"{solution() = }")
48
1
'''simple docstring''' UpperCAmelCase__ : Tuple = 6_55_21 def A ( UpperCamelCase_ : str ) -> int: '''simple docstring''' lowerCAmelCase__ = 1 lowerCAmelCase__ = 0 for plain_chr in plain_text: lowerCAmelCase__ = (a + ord(UpperCamelCase_ )) % MOD_ADLER lowerCAmelCase__ = (b + a) % MOD_ADLER return (b << 16) | a
48
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : List[Any] = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = {"vocab_file": "vocab.json"} UpperCAmelCase__ : Optional[Any] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } UpperCAmelCase__ : Union[str, Any] = {"mgp-str": 27} class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = VOCAB_FILES_NAMES snake_case__ :Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : int="[GO]" , __magic_name__ : Optional[Any]="[GO]" , __magic_name__ : List[str]="[s]" , __magic_name__ : str="[GO]" , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__( unk_token=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , pad_token=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding="utf-8" ) as vocab_handle: lowerCAmelCase__ = json.load(__magic_name__ ) lowerCAmelCase__ = {v: k for k, v in self.vocab.items()} @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return len(self.vocab ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = [] for s in text: char_tokens.extend(__magic_name__ ) return char_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str ): """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : Tuple ): """simple docstring""" return self.decoder.get(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error("Vocabulary path ({}) should be a directory".format(__magic_name__ ) ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(__magic_name__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + "\n" ) return (vocab_file,)
48
1
'''simple docstring''' import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration UpperCAmelCase__ : Optional[Any] = pytest.mark.integration UpperCAmelCase__ : str = {"comet"} UpperCAmelCase__ : Optional[Any] = importlib.util.find_spec("fairseq") is not None UpperCAmelCase__ : Optional[int] = {"code_eval"} UpperCAmelCase__ : List[Any] = os.name == "nt" UpperCAmelCase__ : Optional[int] = {"bertscore", "frugalscore", "perplexity"} UpperCAmelCase__ : int = importlib.util.find_spec("transformers") is not None def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[Any] , UpperCamelCase_ : List[str] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest("\"test requires Fairseq\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : List[Any] ) -> str: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest("\"test requires transformers\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( UpperCamelCase_ : Any ) -> int: '''simple docstring''' @wraps(UpperCamelCase_ ) def wrapper(self : Optional[int] , UpperCamelCase_ : Optional[Any] ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest("\"test not supported on Windows\"" ) else: test_case(self , UpperCamelCase_ ) return wrapper def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob("./metrics/*/" )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @local class A ( parameterized.TestCase ): snake_case__ :Union[str, Any] = {} snake_case__ :Optional[Any] = None @pytest.mark.filterwarnings("ignore:metric_module_factory is deprecated:FutureWarning" ) @pytest.mark.filterwarnings("ignore:load_metric is deprecated:FutureWarning" ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) lowerCAmelCase__ = datasets.load.import_main_class(metric_module.__name__ , dataset=__magic_name__ ) # check parameters lowerCAmelCase__ = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(__magic_name__ , metric_module.__name__ ): with self.use_local_metrics(): try: lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "[...]" lowerCAmelCase__ = importlib.import_module( datasets.load.metric_module_factory(os.path.join("metrics" , __magic_name__ ) ).module_path ) # run doctest with self.use_local_metrics(): lowerCAmelCase__ = doctest.testmod(__magic_name__ , verbose=__magic_name__ , raise_on_error=__magic_name__ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](__magic_name__ ): yield else: yield @contextmanager def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" def load_local_metric(__magic_name__ : Union[str, Any] , *__magic_name__ : Any , **__magic_name__ : Any ): return load_metric(os.path.join("metrics" , __magic_name__ ) , *__magic_name__ , **__magic_name__ ) with patch("datasets.load_metric" ) as mock_load_metric: lowerCAmelCase__ = load_local_metric yield @classmethod def __SCREAMING_SNAKE_CASE ( cls : Any , __magic_name__ : Optional[int] ): """simple docstring""" def wrapper(__magic_name__ : Dict ): lowerCAmelCase__ = contextmanager(__magic_name__ ) lowerCAmelCase__ = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher("bleurt" ) def A ( UpperCamelCase_ : str ) -> Any: '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string("sv" , "" , "" ) # handle pytest cli flags class A ( SCREAMING_SNAKE_CASE__ ): def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] ): """simple docstring""" assert len(input_dict["input_ids"] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch("bleurt.score._create_predictor" ) as mock_create_predictor: lowerCAmelCase__ = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher("bertscore" ) def A ( UpperCamelCase_ : List[Any] ) -> Optional[Any]: '''simple docstring''' import torch def bert_cos_score_idf(UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any] , *UpperCamelCase_ : Union[str, Any] , **UpperCamelCase_ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch("bert_score.scorer.get_model" ), patch( "bert_score.scorer.bert_cos_score_idf" ) as mock_bert_cos_score_idf: lowerCAmelCase__ = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher("comet" ) def A ( UpperCamelCase_ : Optional[int] ) -> Any: '''simple docstring''' def load_from_checkpoint(UpperCamelCase_ : Tuple ): class A : def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : int , **__magic_name__ : Dict ): """simple docstring""" assert len(__magic_name__ ) == 2 lowerCAmelCase__ = [0.19, 0.92] return scores, sum(__magic_name__ ) / len(__magic_name__ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch("comet.download_model" ) as mock_download_model: lowerCAmelCase__ = None with patch("comet.load_from_checkpoint" ) as mock_load_from_checkpoint: lowerCAmelCase__ = load_from_checkpoint yield def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = load_metric(os.path.join("metrics" , "seqeval" ) ) lowerCAmelCase__ = "ERROR" lowerCAmelCase__ = F"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}""" with pytest.raises(UpperCamelCase_ , match=re.escape(UpperCamelCase_ ) ): metric.compute(predictions=[] , references=[] , scheme=UpperCamelCase_ )
48
'''simple docstring''' from math import sqrt def A ( UpperCamelCase_ : int ) -> int: '''simple docstring''' lowerCAmelCase__ = 0 for i in range(1 , int(sqrt(UpperCamelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(UpperCamelCase_ ): total += i + n // i elif i == sqrt(UpperCamelCase_ ): total += i return total - n def A ( UpperCamelCase_ : int = 1_00_00 ) -> int: '''simple docstring''' lowerCAmelCase__ = sum( i for i in range(1 , UpperCamelCase_ ) if sum_of_divisors(sum_of_divisors(UpperCamelCase_ ) ) == i and sum_of_divisors(UpperCamelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
48
1
'''simple docstring''' from __future__ import annotations def A ( UpperCamelCase_ : int ) -> list[int]: '''simple docstring''' lowerCAmelCase__ = 2 lowerCAmelCase__ = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(UpperCamelCase_ ) if n > 1: factors.append(UpperCamelCase_ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
48
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def A ( UpperCamelCase_ : np.ndarray ) -> np.ndarray: '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.mean(1 ) # Centralize the data of class i lowerCAmelCase__ = data - column_reshape(UpperCamelCase_ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(UpperCamelCase_ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' lowerCAmelCase__ = features.mean(1 ) lowerCAmelCase__ = np.nan for i in range(UpperCamelCase_ ): lowerCAmelCase__ = features[:, labels == i] lowerCAmelCase__ = data.shape[1] lowerCAmelCase__ = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) lowerCAmelCase__ = device_data * np.dot( column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ ) , (column_reshape(UpperCamelCase_ ) - column_reshape(UpperCamelCase_ )).T , ) return covariance_sum / features.shape[1] def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' if features.any(): lowerCAmelCase__ = features.mean(1 ) # Center the dataset lowerCAmelCase__ = features - np.reshape(UpperCamelCase_ , (data_mean.size, 1) ) lowerCAmelCase__ = np.dot(UpperCamelCase_ , centered_data.T ) / features.shape[1] lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.eigh(UpperCamelCase_ ) # Take all the columns in the reverse order (-1), and then takes only the first lowerCAmelCase__ = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space lowerCAmelCase__ = np.dot(filtered_eigenvectors.T , UpperCamelCase_ ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( UpperCamelCase_ : np.ndarray , UpperCamelCase_ : np.ndarray , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> np.ndarray: '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: lowerCAmelCase__ ,lowerCAmelCase__ = eigh( covariance_between_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , covariance_within_classes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) , ) lowerCAmelCase__ = eigenvectors[:, ::-1][:, :dimensions] lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = np.linalg.svd(UpperCamelCase_ ) lowerCAmelCase__ = svd_matrix[:, 0:dimensions] lowerCAmelCase__ = np.dot(filtered_svd_matrix.T , UpperCamelCase_ ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=UpperCamelCase_ ) logging.error("Dataset empty" ) raise AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) lowerCAmelCase__ = np.array([0, 0, 0, 1, 1] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = linear_discriminant_analysis( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) if isinstance(UpperCamelCase_ , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def A ( ) -> None: '''simple docstring''' lowerCAmelCase__ = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) lowerCAmelCase__ = 2 lowerCAmelCase__ = np.array([[6.92_820_323, 8.66_025_404, 10.39_230_485], [3.0, 3.0, 3.0]] ) with pytest.raises(UpperCamelCase_ ) as error_info: lowerCAmelCase__ = principal_component_analysis(UpperCamelCase_ , UpperCamelCase_ ) if not np.allclose(UpperCamelCase_ , UpperCamelCase_ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
48
1
'''simple docstring''' import json import multiprocessing as mp import re from collections import defaultdict from functools import partial from typing import Dict, List, Optional, Set, Tuple, Type from datasets import Dataset from datasketch import MinHash, MinHashLSH from dpu_utils.utils.iterators import ThreadedIterator from tqdm import tqdm UpperCAmelCase__ : int = re.compile("[^A-Za-z_0-9]") # parameters used in DuplicationIndex UpperCAmelCase__ : Any = 10 UpperCAmelCase__ : Union[str, Any] = 2_56 def A ( UpperCamelCase_ : List[str] ) -> Optional[MinHash]: '''simple docstring''' if len(UpperCamelCase_ ) < MIN_NUM_TOKENS: return None lowerCAmelCase__ = MinHash(num_perm=UpperCamelCase_ ) for token in set(UpperCamelCase_ ): min_hash.update(token.encode() ) return min_hash def A ( UpperCamelCase_ : str ) -> Set[str]: '''simple docstring''' return {t for t in NON_ALPHA.split(UpperCamelCase_ ) if len(t.strip() ) > 0} class A : def __init__( self : Tuple , *, __magic_name__ : float = 0.85 , ): """simple docstring""" lowerCAmelCase__ = duplication_jaccard_threshold lowerCAmelCase__ = NUM_PERM lowerCAmelCase__ = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm ) lowerCAmelCase__ = defaultdict(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Tuple , __magic_name__ : MinHash ): """simple docstring""" lowerCAmelCase__ = self._index.query(__magic_name__ ) if code_key in self._index.keys: print(f"""Duplicate key {code_key}""" ) return self._index.insert(__magic_name__ , __magic_name__ ) if len(__magic_name__ ) > 0: for base_duplicate in close_duplicates: if base_duplicate in self._duplicate_clusters: self._duplicate_clusters[base_duplicate].add(__magic_name__ ) break else: self._duplicate_clusters[close_duplicates[0]].add(__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = [] for base, duplicates in self._duplicate_clusters.items(): lowerCAmelCase__ = [base] + list(__magic_name__ ) # reformat the cluster to be a list of dict lowerCAmelCase__ = [{"base_index": el[0], "repo_name": el[1], "path": el[2]} for el in cluster] duplicate_clusters.append(__magic_name__ ) return duplicate_clusters def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = self.get_duplicate_clusters() with open(__magic_name__ , "w" ) as f: json.dump(__magic_name__ , __magic_name__ ) def A ( UpperCamelCase_ : Optional[int] ) -> str: '''simple docstring''' lowerCAmelCase__ ,lowerCAmelCase__ = element lowerCAmelCase__ = get_min_hash([t for t in NON_ALPHA.split(data["content"] ) if len(t.strip() ) > 0] ) if min_hash is not None: return (index, data["repo_name"], data["path"]), min_hash def A ( UpperCamelCase_ : Type[Dataset] ) -> Dict: '''simple docstring''' with mp.Pool() as pool: for data in pool.imap_unordered( _compute_min_hash , ThreadedIterator(UpperCamelCase_ , max_queue_size=1_00_00 ) , chunksize=1_00 , ): if data is not None: yield data def A ( UpperCamelCase_ : Type[Dataset] , UpperCamelCase_ : float ) -> str: '''simple docstring''' lowerCAmelCase__ = DuplicationIndex(duplication_jaccard_threshold=UpperCamelCase_ ) for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(UpperCamelCase_ ) ) , max_queue_size=1_00 ) ): di.add(UpperCamelCase_ , UpperCamelCase_ ) # Returns a List[Cluster] where Cluster is List[str] with the filenames. return di.get_duplicate_clusters() def A ( UpperCamelCase_ : str , UpperCamelCase_ : str ) -> float: '''simple docstring''' lowerCAmelCase__ = get_tokens(UpperCamelCase_ ) lowerCAmelCase__ = get_tokens(UpperCamelCase_ ) return len(tokensa & tokensa ) / len(tokensa | tokensa ) UpperCAmelCase__ : str = None def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : Any ) -> Any: '''simple docstring''' lowerCAmelCase__ = [] for elementa in cluster: lowerCAmelCase__ = _shared_dataset[elementa["base_index"]]["content"] for elementa in extremes: lowerCAmelCase__ = _shared_dataset[elementa["base_index"]]["content"] if jaccard_similarity(UpperCamelCase_ , UpperCamelCase_ ) >= jaccard_threshold: elementa["copies"] += 1 break else: lowerCAmelCase__ = 1 extremes.append(UpperCamelCase_ ) return extremes def A ( UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str ) -> str: '''simple docstring''' global _shared_dataset lowerCAmelCase__ = dataset lowerCAmelCase__ = [] lowerCAmelCase__ = partial(_find_cluster_extremes_shared , jaccard_threshold=UpperCamelCase_ ) with mp.Pool() as pool: for extremes in tqdm( pool.imap_unordered( UpperCamelCase_ , UpperCamelCase_ , ) , total=len(UpperCamelCase_ ) , ): extremes_list.append(UpperCamelCase_ ) return extremes_list def A ( UpperCamelCase_ : Type[Dataset] , UpperCamelCase_ : float = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]: '''simple docstring''' lowerCAmelCase__ = make_duplicate_clusters(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = {x["base_index"] for cluster in duplicate_clusters for x in cluster} lowerCAmelCase__ = {} lowerCAmelCase__ = find_extremes(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) for extremes in extremes_clusters: for element in extremes: lowerCAmelCase__ = element lowerCAmelCase__ = duplicate_indices - set(extreme_dict.keys() ) lowerCAmelCase__ = dataset.filter(lambda UpperCamelCase_ , UpperCamelCase_ : idx not in remove_indices , with_indices=UpperCamelCase_ ) # update duplicate_clusters for cluster in duplicate_clusters: for element in cluster: lowerCAmelCase__ = element["base_index"] in extreme_dict if element["is_extreme"]: lowerCAmelCase__ = extreme_dict[element["base_index"]]["copies"] print(F"""Original dataset size: {len(UpperCamelCase_ )}""" ) print(F"""Number of duplicate clusters: {len(UpperCamelCase_ )}""" ) print(F"""Files in duplicate cluster: {len(UpperCamelCase_ )}""" ) print(F"""Unique files in duplicate cluster: {len(UpperCamelCase_ )}""" ) print(F"""Filtered dataset size: {len(UpperCamelCase_ )}""" ) return ds_filter, duplicate_clusters
48
'''simple docstring''' def A ( UpperCamelCase_ : str , UpperCamelCase_ : int ) -> list: '''simple docstring''' lowerCAmelCase__ = word.split() def justify(UpperCamelCase_ : list , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> str: lowerCAmelCase__ = max_width - width lowerCAmelCase__ = len(UpperCamelCase_ ) if len(UpperCamelCase_ ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase__ = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase__ = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase__ = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(UpperCamelCase_ ): num_spaces_between_words_list[i] += 1 lowerCAmelCase__ = [] for i in range(UpperCamelCase_ ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " " ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = [] lowerCAmelCase__ = 0 for word in words: if width + len(UpperCamelCase_ ) + len(UpperCamelCase_ ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(UpperCamelCase_ ) width += len(UpperCamelCase_ ) else: # justify the line and add it to result answer.append(justify(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ) # reset new line and new width lowerCAmelCase__ ,lowerCAmelCase__ = [word], len(UpperCamelCase_ ) lowerCAmelCase__ = max_width - width - len(UpperCamelCase_ ) answer.append(" ".join(UpperCamelCase_ ) + (remaining_spaces + 1) * " " ) return answer if __name__ == "__main__": from doctest import testmod testmod()
48
1
'''simple docstring''' import re from filelock import FileLock try: import nltk UpperCAmelCase__ : Union[str, Any] = True except (ImportError, ModuleNotFoundError): UpperCAmelCase__ : Tuple = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def A ( UpperCamelCase_ : str ) -> str: '''simple docstring''' re.sub("<n>" , "" , UpperCamelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase_ ) )
48
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 UpperCAmelCase__ : str = sys.version_info >= (3, 10) def A ( UpperCamelCase_ : Any=None , UpperCamelCase_ : List[Any]=None ) -> Optional[int]: '''simple docstring''' return field(default_factory=lambda: default , metadata=UpperCamelCase_ ) @dataclass class A : snake_case__ :int snake_case__ :float snake_case__ :str snake_case__ :bool @dataclass class A : snake_case__ :int = 42 snake_case__ :str = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :Optional[bool] = None class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Any = 'titi' snake_case__ :Optional[int] = 'toto' class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'titi' snake_case__ :str = 'toto' snake_case__ :int = 42 @dataclass class A : snake_case__ :BasicEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.foo ) @dataclass class A : snake_case__ :MixedTypeEnum = "toto" def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = MixedTypeEnum(self.foo ) @dataclass class A : snake_case__ :Optional[int] = None snake_case__ :Optional[float] = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :Optional[str] = None snake_case__ :Optional[List[str]] = list_field(default=[] ) snake_case__ :Optional[List[int]] = list_field(default=[] ) @dataclass class A : snake_case__ :List[int] = list_field(default=[] ) snake_case__ :List[int] = list_field(default=[1, 2, 3] ) snake_case__ :List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) snake_case__ :List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A : snake_case__ :List[int] = field() snake_case__ :str = field() snake_case__ :BasicEnum = field() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = BasicEnum(self.required_enum ) @dataclass class A : snake_case__ :int snake_case__ :"BasicEnum" = field() snake_case__ :"Optional[bool]" = None snake_case__ :"str" = field(default='toto' , metadata={'help': 'help message'} ) snake_case__ :"List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class A : snake_case__ :bool = False snake_case__ :bool = True snake_case__ :bool | None = None @dataclass class A : snake_case__ :int | None = None snake_case__ :float | None = field(default=SCREAMING_SNAKE_CASE__ , metadata={'help': 'help message'} ) snake_case__ :str | None = None snake_case__ :list[str] | None = list_field(default=[] ) snake_case__ :list[int] | None = list_field(default=[] ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : argparse.ArgumentParser , __magic_name__ : argparse.ArgumentParser ): """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} lowerCAmelCase__ = {k: v for k, v in vars(__magic_name__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , __magic_name__ ) and yy.get("choices" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](__magic_name__ ) , yy["type"](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--bar" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--baz" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--flag" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((lowerCAmelCase__) ,) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) expected.add_argument("--baz" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=__magic_name__ , dest="baz" ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) lowerCAmelCase__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) lowerCAmelCase__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) lowerCAmelCase__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" @dataclass class A : snake_case__ :Literal["titi", "toto", 42] = "toto" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) lowerCAmelCase__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) lowerCAmelCase__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) lowerCAmelCase__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--bar" , default=__magic_name__ , type=__magic_name__ , help="help message" ) expected.add_argument("--baz" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=__magic_name__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=__magic_name__ ) lowerCAmelCase__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) lowerCAmelCase__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("--required_str" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=__magic_name__ , ) expected.add_argument("--opt" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("--baz" , default="toto" , type=__magic_name__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } lowerCAmelCase__ = parser.parse_dict(__magic_name__ )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_json" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) lowerCAmelCase__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase__ = os.path.join(__magic_name__ , "temp_yaml" ) os.mkdir(__magic_name__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] lowerCAmelCase__ = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
48
1
'''simple docstring''' import re import string import numpy as np import datasets UpperCAmelCase__ : Tuple = "\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" UpperCAmelCase__ : int = "\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" UpperCAmelCase__ : str = "\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A ( datasets.Metric ): def __SCREAMING_SNAKE_CASE ( self : List[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 __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Dict , __magic_name__ : int , __magic_name__ : Optional[Any]=None , __magic_name__ : Dict=False , __magic_name__ : Any=False , __magic_name__ : List[Any]=False , ): """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: lowerCAmelCase__ = np.array([re.sub(__magic_name__ , "" , __magic_name__ ) for x in predictions] ) lowerCAmelCase__ = np.array([re.sub(__magic_name__ , "" , __magic_name__ ) for x in references] ) else: lowerCAmelCase__ = np.asarray(__magic_name__ ) lowerCAmelCase__ = np.asarray(__magic_name__ ) if ignore_case: lowerCAmelCase__ = np.char.lower(__magic_name__ ) lowerCAmelCase__ = np.char.lower(__magic_name__ ) if ignore_punctuation: lowerCAmelCase__ = string.punctuation.maketrans("" , "" , string.punctuation ) lowerCAmelCase__ = np.char.translate(__magic_name__ , table=__magic_name__ ) lowerCAmelCase__ = np.char.translate(__magic_name__ , table=__magic_name__ ) if ignore_numbers: lowerCAmelCase__ = string.digits.maketrans("" , "" , string.digits ) lowerCAmelCase__ = np.char.translate(__magic_name__ , table=__magic_name__ ) lowerCAmelCase__ = np.char.translate(__magic_name__ , table=__magic_name__ ) lowerCAmelCase__ = predictions == references return {"exact_match": np.mean(__magic_name__ ) * 100}
48
'''simple docstring''' import sys from collections import defaultdict class A : def __init__( self : Any ): """simple docstring""" lowerCAmelCase__ = [] def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[Any] ): """simple docstring""" return self.node_position[vertex] def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = pos def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , __magic_name__ : List[str] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: lowerCAmelCase__ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: lowerCAmelCase__ = 2 * start + 1 else: lowerCAmelCase__ = 2 * start + 2 if heap[smallest_child] < heap[start]: lowerCAmelCase__ ,lowerCAmelCase__ = heap[smallest_child], positions[smallest_child] lowerCAmelCase__ ,lowerCAmelCase__ = ( heap[start], positions[start], ) lowerCAmelCase__ ,lowerCAmelCase__ = temp, tempa lowerCAmelCase__ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __magic_name__ ) self.top_to_bottom(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : List[str] , __magic_name__ : List[str] ): """simple docstring""" lowerCAmelCase__ = position[index] while index != 0: lowerCAmelCase__ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: lowerCAmelCase__ = heap[parent] lowerCAmelCase__ = position[parent] self.set_position(position[parent] , __magic_name__ ) else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , __magic_name__ ) break lowerCAmelCase__ = parent else: lowerCAmelCase__ = val lowerCAmelCase__ = temp self.set_position(__magic_name__ , 0 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : int ): """simple docstring""" lowerCAmelCase__ = len(__magic_name__ ) // 2 - 1 for i in range(__magic_name__ , -1 , -1 ): self.top_to_bottom(__magic_name__ , __magic_name__ , len(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = positions[0] lowerCAmelCase__ = sys.maxsize self.top_to_bottom(__magic_name__ , 0 , len(__magic_name__ ) , __magic_name__ ) return temp def A ( UpperCamelCase_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = Heap() lowerCAmelCase__ = [0] * len(UpperCamelCase_ ) lowerCAmelCase__ = [-1] * len(UpperCamelCase_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph lowerCAmelCase__ = [] # Heap of Distance of vertices from their neighboring vertex lowerCAmelCase__ = [] for vertex in range(len(UpperCamelCase_ ) ): distance_tv.append(sys.maxsize ) positions.append(UpperCamelCase_ ) heap.node_position.append(UpperCamelCase_ ) lowerCAmelCase__ = [] lowerCAmelCase__ = 1 lowerCAmelCase__ = sys.maxsize for neighbor, distance in adjacency_list[0]: lowerCAmelCase__ = 0 lowerCAmelCase__ = distance heap.heapify(UpperCamelCase_ , UpperCamelCase_ ) for _ in range(1 , len(UpperCamelCase_ ) ): lowerCAmelCase__ = heap.delete_minimum(UpperCamelCase_ , UpperCamelCase_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) lowerCAmelCase__ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(UpperCamelCase_ )] ): lowerCAmelCase__ = distance heap.bottom_to_top( UpperCamelCase_ , heap.get_position(UpperCamelCase_ ) , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > UpperCAmelCase__ : Optional[int] = int(input("Enter number of edges: ").strip()) UpperCAmelCase__ : str = defaultdict(list) for _ in range(edges_number): UpperCAmelCase__ : int = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
48
1
'''simple docstring''' from __future__ import annotations def A ( UpperCamelCase_ : int | float | str , UpperCamelCase_ : int | float | str ) -> list[str]: '''simple docstring''' if nth_term == "": return [""] lowerCAmelCase__ = int(UpperCamelCase_ ) lowerCAmelCase__ = int(UpperCamelCase_ ) lowerCAmelCase__ = [] for temp in range(int(UpperCamelCase_ ) ): series.append(F"""1 / {pow(temp + 1 , int(UpperCamelCase_ ) )}""" if series else "1" ) return series if __name__ == "__main__": import doctest doctest.testmod() UpperCAmelCase__ : str = int(input("Enter the last number (nth term) of the P-Series")) UpperCAmelCase__ : List[Any] = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
48
'''simple docstring''' import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCAmelCase__ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") if is_sentencepiece_available(): import sentencepiece as sp UpperCAmelCase__ : Tuple = 5 UpperCAmelCase__ : List[Any] = 10 @require_sentencepiece @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Tuple = SpeechaTextTokenizer snake_case__ :Dict = False snake_case__ :Optional[int] = True def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" super().setUp() lowerCAmelCase__ = sp.SentencePieceProcessor() spm_model.Load(__magic_name__ ) lowerCAmelCase__ = ["<s>", "<pad>", "</s>", "<unk>"] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(__magic_name__ ) )] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = Path(self.tmpdirname ) save_json(__magic_name__ , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(__magic_name__ , save_dir / VOCAB_FILES_NAMES["spm_file"] ) lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__magic_name__ ) , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1001 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__magic_name__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__magic_name__ ) , [289, 50, 14, 174, 386] , ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __magic_name__ , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__magic_name__ ) self.assertListEqual(__magic_name__ , [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertListEqual( __magic_name__ , [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 __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = {"input_ids": [[3791, 797, 31, 11, 64, 797, 31, 2429, 433, 12, 1176, 12, 20, 786, 915, 142, 2413, 240, 37, 3238, 797, 31, 11, 35, 93, 915, 142, 2413, 240, 37, 5540, 567, 1276, 93, 37, 610, 40, 62, 455, 657, 1042, 123, 780, 177, 37, 309, 241, 1298, 514, 20, 292, 2737, 114, 2469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3388, 511, 459, 4, 3555, 40, 321, 302, 705, 4, 3388, 511, 583, 326, 5, 5, 5, 62, 3310, 560, 177, 2680, 217, 1508, 32, 31, 853, 418, 64, 583, 511, 1605, 62, 35, 93, 560, 177, 2680, 217, 1508, 1521, 64, 583, 511, 519, 62, 20, 1515, 764, 20, 149, 261, 5625, 7972, 20, 5540, 567, 1276, 93, 3925, 1675, 11, 15, 802, 7972, 576, 217, 1508, 11, 35, 93, 1253, 2441, 15, 289, 652, 31, 416, 321, 3842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2681, 1153, 3434, 20, 5540, 37, 567, 126, 1253, 2441, 3376, 449, 210, 431, 1563, 177, 767, 5540, 11, 1203, 472, 11, 2953, 685, 285, 364, 706, 1153, 20, 6799, 20, 2869, 20, 4464, 126, 40, 2429, 20, 1040, 866, 2664, 418, 20, 318, 20, 1726, 186, 20, 265, 522, 35, 93, 2191, 4634, 20, 1040, 12, 6799, 15, 228, 2356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [2575, 2666, 684, 1582, 1176, 12, 627, 149, 619, 20, 4902, 563, 11, 20, 149, 261, 3420, 2356, 174, 142, 4714, 131, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__magic_name__ , model_name="facebook/s2t-small-mustc-en-de-st" , revision="a14f04cf0776c02f62a8cb800cf7909e15ea23ad" , ) @require_sentencepiece class A ( unittest.TestCase ): snake_case__ :Union[str, Any] = 'valhalla/s2t_mustc_multilinguial_medium' snake_case__ :Tuple = 'C\'est trop cool' snake_case__ :List[str] = 'Esto es genial' @classmethod def __SCREAMING_SNAKE_CASE ( cls : List[Any] ): """simple docstring""" lowerCAmelCase__ = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id["pt"] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id["ru"] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id["it"] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id["de"] , 11 ) def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 10000 ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" self.assertIn(__magic_name__ , self.tokenizer.all_special_ids ) lowerCAmelCase__ = [ES_CODE, 4, 1601, 47, 7647, 2] lowerCAmelCase__ = self.tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) lowerCAmelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) self.assertNotIn(self.tokenizer.eos_token , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = "fr" lowerCAmelCase__ = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , __magic_name__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = "fr" self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) lowerCAmelCase__ = "es" self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
48
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase__ : Optional[Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : List[str] = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys UpperCAmelCase__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig UpperCAmelCase__ : Tuple = logging.get_logger(__name__) # General docstring UpperCAmelCase__ : int = "RegNetConfig" # Base docstring UpperCAmelCase__ : Optional[int] = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[int] = [1, 10_88, 7, 7] # Image classification docstring UpperCAmelCase__ : Tuple = "facebook/regnet-y-040" UpperCAmelCase__ : Optional[Any] = "tabby, tabby cat" UpperCAmelCase__ : int = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class A ( tf.keras.layers.Layer ): def __init__( self : str , __magic_name__ : int , __magic_name__ : int = 3 , __magic_name__ : int = 1 , __magic_name__ : int = 1 , __magic_name__ : Optional[str] = "relu" , **__magic_name__ : int , ): """simple docstring""" super().__init__(**__magic_name__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb lowerCAmelCase__ = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=__magic_name__ , strides=__magic_name__ , padding="VALID" , groups=__magic_name__ , use_bias=__magic_name__ , name="convolution" , ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) lowerCAmelCase__ = ACTaFN[activation] if activation is not None else tf.identity def __SCREAMING_SNAKE_CASE ( self : Any , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.convolution(self.padding(__magic_name__ ) ) lowerCAmelCase__ = self.normalization(__magic_name__ ) lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : List[Any] , __magic_name__ : RegNetConfig , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config.num_channels lowerCAmelCase__ = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = shape_list(__magic_name__ )[1] if tf.executing_eagerly() and 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." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 2, 3, 1) ) lowerCAmelCase__ = self.embedder(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Any , __magic_name__ : int , __magic_name__ : int = 2 , **__magic_name__ : Optional[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.ConvaD( filters=__magic_name__ , kernel_size=1 , strides=__magic_name__ , use_bias=__magic_name__ , name="convolution" ) lowerCAmelCase__ = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : bool = False ): """simple docstring""" return self.normalization(self.convolution(__magic_name__ ) , training=__magic_name__ ) class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , **__magic_name__ : List[Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) lowerCAmelCase__ = [ tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=__magic_name__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.pooler(__magic_name__ ) for layer_module in self.attention: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = hidden_state * pooled return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.2" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : int , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 1 , **__magic_name__ : str ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = in_channels != out_channels or stride != 1 lowerCAmelCase__ = max(1 , out_channels // config.groups_width ) lowerCAmelCase__ = ( TFRegNetShortCut(__magic_name__ , stride=__magic_name__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) lowerCAmelCase__ = [ TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( __magic_name__ , stride=__magic_name__ , groups=__magic_name__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(__magic_name__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(__magic_name__ , kernel_size=1 , activation=__magic_name__ , name="layer.3" ), ] lowerCAmelCase__ = ACTaFN[config.hidden_act] def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : Any ): """simple docstring""" lowerCAmelCase__ = hidden_state for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) lowerCAmelCase__ = self.shortcut(__magic_name__ ) hidden_state += residual lowerCAmelCase__ = self.activation(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Union[str, Any] , __magic_name__ : RegNetConfig , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int = 2 , __magic_name__ : int = 2 , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer lowerCAmelCase__ = [ # downsampling is done in the first layer with stride of 2 layer(__magic_name__ , __magic_name__ , __magic_name__ , stride=__magic_name__ , name="layers.0" ), *[layer(__magic_name__ , __magic_name__ , __magic_name__ , name=f"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[str] ): """simple docstring""" for layer_module in self.layers: lowerCAmelCase__ = layer_module(__magic_name__ ) return hidden_state class A ( tf.keras.layers.Layer ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __magic_name__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) lowerCAmelCase__ = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__magic_name__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__magic_name__ , __magic_name__ , __magic_name__ , depth=__magic_name__ , name=f"""stages.{i+1}""" ) ) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : tf.Tensor , __magic_name__ : bool = False , __magic_name__ : bool = True ): """simple docstring""" lowerCAmelCase__ = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) lowerCAmelCase__ = stage_module(__magic_name__ ) if output_hidden_states: lowerCAmelCase__ = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=__magic_name__ , hidden_states=__magic_name__ ) @keras_serializable class A ( tf.keras.layers.Layer ): snake_case__ :List[Any] = RegNetConfig def __init__( self : str , __magic_name__ : Union[str, Any] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(**__magic_name__ ) lowerCAmelCase__ = config lowerCAmelCase__ = TFRegNetEmbeddings(__magic_name__ , name="embedder" ) lowerCAmelCase__ = TFRegNetEncoder(__magic_name__ , name="encoder" ) lowerCAmelCase__ = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__magic_name__ , name="pooler" ) @unpack_inputs def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.embedder(__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = self.encoder( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = encoder_outputs[0] lowerCAmelCase__ = self.pooler(__magic_name__ ) # Change to NCHW output format have uniformity in the modules lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) lowerCAmelCase__ = tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: lowerCAmelCase__ = tuple([tf.transpose(__magic_name__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=__magic_name__ , pooler_output=__magic_name__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :str = RegNetConfig snake_case__ :Optional[Any] = 'regnet' snake_case__ :Tuple = 'pixel_values' @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} UpperCAmelCase__ : List[str] = R"\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCAmelCase__ : Tuple = R"\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\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 [`~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__ , ) class A ( SCREAMING_SNAKE_CASE__ ): def __init__( self : Any , __magic_name__ : RegNetConfig , *__magic_name__ : Optional[int] , **__magic_name__ : Union[str, Any] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : tf.Tensor , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : int=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( pixel_values=__magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=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__ , ) class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def __init__( self : Tuple , __magic_name__ : RegNetConfig , *__magic_name__ : Tuple , **__magic_name__ : Optional[int] ): """simple docstring""" super().__init__(__magic_name__ , *__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = config.num_labels lowerCAmelCase__ = TFRegNetMainLayer(__magic_name__ , name="regnet" ) # classification head lowerCAmelCase__ = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(__magic_name__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__magic_name__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : tf.Tensor = None , __magic_name__ : tf.Tensor = None , __magic_name__ : bool = None , __magic_name__ : bool = None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase__ = self.regnet( __magic_name__ , output_hidden_states=__magic_name__ , return_dict=__magic_name__ , training=__magic_name__ ) lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase__ = self.classifier[0](__magic_name__ ) lowerCAmelCase__ = self.classifier[1](__magic_name__ ) lowerCAmelCase__ = None if labels is None else self.hf_compute_loss(labels=__magic_name__ , logits=__magic_name__ ) if not return_dict: lowerCAmelCase__ = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__magic_name__ , logits=__magic_name__ , hidden_states=outputs.hidden_states )
48
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = "▁" UpperCAmelCase__ : List[str] = {"vocab_file": "sentencepiece.bpe.model"} UpperCAmelCase__ : Union[str, Any] = { "vocab_file": { "facebook/mbart-large-50-one-to-many-mmt": ( "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model" ), } } UpperCAmelCase__ : Optional[Any] = { "facebook/mbart-large-50-one-to-many-mmt": 10_24, } # fmt: off UpperCAmelCase__ : Tuple = ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"] class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Optional[int] = VOCAB_FILES_NAMES snake_case__ :str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ :Any = PRETRAINED_VOCAB_FILES_MAP snake_case__ :Tuple = ['input_ids', 'attention_mask'] snake_case__ :List[int] = [] snake_case__ :List[int] = [] def __init__( self : int , __magic_name__ : int , __magic_name__ : Dict=None , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]="</s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : List[Any]="<s>" , __magic_name__ : Tuple="<unk>" , __magic_name__ : List[Any]="<pad>" , __magic_name__ : List[Any]="<mask>" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : List[Any] , ): """simple docstring""" lowerCAmelCase__ = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase__ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__magic_name__ , tgt_lang=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__magic_name__ ) ) lowerCAmelCase__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token lowerCAmelCase__ = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab lowerCAmelCase__ = 1 lowerCAmelCase__ = len(self.sp_model ) lowerCAmelCase__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__magic_name__ ) } lowerCAmelCase__ = {v: k for k, v in self.lang_code_to_id.items()} lowerCAmelCase__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) lowerCAmelCase__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} lowerCAmelCase__ = src_lang if src_lang is not None else "en_XX" lowerCAmelCase__ = self.lang_code_to_id[self._src_lang] lowerCAmelCase__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self._src_lang @src_lang.setter def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : List[Any] , __magic_name__ : Dict ): """simple docstring""" lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __SCREAMING_SNAKE_CASE ( self : int , __magic_name__ : str ): """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str ): """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] lowerCAmelCase__ = self.sp_model.PieceToId(__magic_name__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : int ): """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : List[Any] ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = 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(__magic_name__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(__magic_name__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ = os.path.join( __magic_name__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) lowerCAmelCase__ = [1] * len(self.prefix_tokens ) lowerCAmelCase__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__magic_name__ )) + suffix_ones return prefix_ones + ([0] * len(__magic_name__ )) + ([0] * len(__magic_name__ )) + suffix_ones def __SCREAMING_SNAKE_CASE ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ): """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def __SCREAMING_SNAKE_CASE ( self : Dict , __magic_name__ : Dict , __magic_name__ : str , __magic_name__ : Optional[str] , __magic_name__ : Optional[str] , **__magic_name__ : Optional[Any] ): """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowerCAmelCase__ = src_lang lowerCAmelCase__ = self(__magic_name__ , add_special_tokens=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.convert_tokens_to_ids(__magic_name__ ) lowerCAmelCase__ = tgt_lang_id return inputs def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : str = "en_XX" , __magic_name__ : Optional[List[str]] = None , __magic_name__ : str = "ro_RO" , **__magic_name__ : Union[str, Any] , ): """simple docstring""" lowerCAmelCase__ = src_lang lowerCAmelCase__ = tgt_lang return super().prepare_seqaseq_batch(__magic_name__ , __magic_name__ , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[src_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id] def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = self.lang_code_to_id[tgt_lang] lowerCAmelCase__ = [self.cur_lang_code_id] lowerCAmelCase__ = [self.eos_token_id]
48
'''simple docstring''' from datetime import datetime import matplotlib.pyplot as plt import torch def A ( UpperCamelCase_ : Tuple ) -> int: '''simple docstring''' for param in module.parameters(): lowerCAmelCase__ = False def A ( ) -> Tuple: '''simple docstring''' lowerCAmelCase__ = "cuda" if torch.cuda.is_available() else "cpu" if torch.backends.mps.is_available() and torch.backends.mps.is_built(): lowerCAmelCase__ = "mps" if device == "mps": print( "WARNING: MPS currently doesn't seem to work, and messes up backpropagation without any visible torch" " errors. I recommend using CUDA on a colab notebook or CPU instead if you're facing inexplicable issues" " with generations." ) return device def A ( UpperCamelCase_ : Optional[int] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase__ = plt.imshow(UpperCamelCase_ ) fig.axes.get_xaxis().set_visible(UpperCamelCase_ ) fig.axes.get_yaxis().set_visible(UpperCamelCase_ ) plt.show() def A ( ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase__ = datetime.now() lowerCAmelCase__ = current_time.strftime("%H:%M:%S" ) return timestamp
48
1
'''simple docstring''' 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 A ( ) -> List[Any]: '''simple docstring''' raise RuntimeError("CUDA out of memory." ) class A ( nn.Module ): def __init__( self : Dict ): """simple docstring""" super().__init__() lowerCAmelCase__ = nn.Linear(3 , 4 ) lowerCAmelCase__ = nn.BatchNormad(4 ) lowerCAmelCase__ = nn.Linear(4 , 5 ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : int ): """simple docstring""" return self.lineara(self.batchnorm(self.lineara(__magic_name__ ) ) ) class A ( unittest.TestCase ): def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__ : Optional[int] ): nonlocal batch_sizes batch_sizes.append(__magic_name__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(__magic_name__ , [128, 64, 32, 16, 8] ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__ : Tuple , __magic_name__ : Tuple ): nonlocal batch_sizes batch_sizes.append(__magic_name__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga lowerCAmelCase__ ,lowerCAmelCase__ = mock_training_loop_function("hello" ) self.assertListEqual(__magic_name__ , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, "hello"] ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(__magic_name__ : Optional[int] ): pass with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__magic_name__ : Optional[Any] ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(__magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : Union[str, Any] ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(__magic_name__ ) 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 __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(__magic_name__ : Optional[Any] ): raise ValueError("Oops, we had an error!" ) with self.assertRaises(__magic_name__ ) as cm: mock_training_loop_function() self.assertIn("Oops, we had an error!" , cm.exception.args[0] ) @require_cuda def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = torch.cuda.memory_allocated() lowerCAmelCase__ = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , __magic_name__ ) lowerCAmelCase__ = release_memory(__magic_name__ ) self.assertEqual(torch.cuda.memory_allocated() , __magic_name__ )
48
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) UpperCAmelCase__ : List[Any] = {"configuration_encoder_decoder": ["EncoderDecoderConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Union[str, Any] = ["EncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[int] = ["TFEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ : Optional[Any] = ["FlaxEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_encoder_decoder import EncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encoder_decoder import EncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_encoder_decoder import TFEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel else: import sys UpperCAmelCase__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
48
1
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING UpperCAmelCase__ : Optional[int] = logging.get_logger(__name__) class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :List[Any] = 'upernet' def __init__( self : Optional[Any] , __magic_name__ : Any=None , __magic_name__ : str=512 , __magic_name__ : List[Any]=0.02 , __magic_name__ : int=[1, 2, 3, 6] , __magic_name__ : Dict=True , __magic_name__ : str=0.4 , __magic_name__ : Optional[Any]=384 , __magic_name__ : Optional[Any]=256 , __magic_name__ : str=1 , __magic_name__ : str=False , __magic_name__ : str=255 , **__magic_name__ : str , ): """simple docstring""" super().__init__(**__magic_name__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) lowerCAmelCase__ = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(__magic_name__ , __magic_name__ ): lowerCAmelCase__ = backbone_config.get("model_type" ) lowerCAmelCase__ = CONFIG_MAPPING[backbone_model_type] lowerCAmelCase__ = config_class.from_dict(__magic_name__ ) lowerCAmelCase__ = backbone_config lowerCAmelCase__ = hidden_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = pool_scales lowerCAmelCase__ = use_auxiliary_head lowerCAmelCase__ = auxiliary_loss_weight lowerCAmelCase__ = auxiliary_in_channels lowerCAmelCase__ = auxiliary_channels lowerCAmelCase__ = auxiliary_num_convs lowerCAmelCase__ = auxiliary_concat_input lowerCAmelCase__ = loss_ignore_index def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = copy.deepcopy(self.__dict__ ) lowerCAmelCase__ = self.backbone_config.to_dict() lowerCAmelCase__ = self.__class__.model_type return output
48
'''simple docstring''' import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def A ( UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict , UpperCamelCase_ : Dict , UpperCamelCase_ : int ) -> Any: '''simple docstring''' lowerCAmelCase__ = BigBirdConfig.from_json_file(UpperCamelCase_ ) print(F"""Building PyTorch model from configuration: {config}""" ) if is_trivia_qa: lowerCAmelCase__ = BigBirdForQuestionAnswering(UpperCamelCase_ ) else: lowerCAmelCase__ = BigBirdForPreTraining(UpperCamelCase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(UpperCamelCase_ , UpperCamelCase_ , is_trivia_qa=UpperCamelCase_ ) # Save pytorch-model print(F"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(UpperCamelCase_ ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--big_bird_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head." ) UpperCAmelCase__ : int = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
48
1
'''simple docstring''' import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = CLIPTokenizer snake_case__ :Optional[Any] = CLIPTokenizerFast snake_case__ :Optional[Any] = True snake_case__ :Dict = {} snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" super().setUp() # fmt: off lowerCAmelCase__ = ["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__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] lowerCAmelCase__ = {"unk_token": "<unk>"} lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase__ = 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(__magic_name__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **__magic_name__ : int ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , **__magic_name__ : List[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : List[Any] , __magic_name__ : Tuple ): """simple docstring""" lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = "lower newer" return input_text, output_text def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] lowerCAmelCase__ = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = tokens + [tokenizer.unk_token] lowerCAmelCase__ = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) @require_ftfy def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCAmelCase__ = self.tokenizer_class.from_pretrained(__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = self.rust_tokenizer_class.from_pretrained(__magic_name__ , **__magic_name__ ) lowerCAmelCase__ = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." lowerCAmelCase__ = tokenizer_s.tokenize(__magic_name__ ) lowerCAmelCase__ = tokenizer_r.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways lowerCAmelCase__ = "xa\u0303y" + " " + "x\xe3y" lowerCAmelCase__ = tokenizer_s.tokenize(__magic_name__ ) lowerCAmelCase__ = tokenizer_r.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) # Test that the tokenization is identical on unicode of space type lowerCAmelCase__ = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: lowerCAmelCase__ = tokenizer_s.tokenize(__magic_name__ ) lowerCAmelCase__ = tokenizer_r.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) # Test that the tokenization is identical on unicode of line break type lowerCAmelCase__ = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: lowerCAmelCase__ = tokenizer_s.tokenize(__magic_name__ ) lowerCAmelCase__ = tokenizer_r.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCAmelCase__ = "hello" # `hello` is a token in the vocabulary of `pretrained_name` lowerCAmelCase__ = f"""{text_of_1_token} {text_of_1_token}""" lowerCAmelCase__ = self.rust_tokenizer_class.from_pretrained( __magic_name__ , use_fast=__magic_name__ , ) lowerCAmelCase__ = tokenizer_r(__magic_name__ , return_offsets_mapping=__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__magic_name__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__magic_name__ ) + 1, len(__magic_name__ ) + 1 + len(__magic_name__ )) , ) lowerCAmelCase__ = f""" {text}""" lowerCAmelCase__ = self.rust_tokenizer_class.from_pretrained( __magic_name__ , use_fast=__magic_name__ , ) lowerCAmelCase__ = tokenizer_r(__magic_name__ , return_offsets_mapping=__magic_name__ , add_special_tokens=__magic_name__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__magic_name__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__magic_name__ ) + 1, 1 + len(__magic_name__ ) + 1 + len(__magic_name__ )) , ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" with self.assertRaises(__magic_name__ ) as context: self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer" ) self.assertTrue( context.exception.args[0].startswith( "The `backend_tokenizer` provided does not match the expected format." ) ) @require_ftfy def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" super().test_tokenization_python_rust_equals() def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" pass
48
'''simple docstring''' from __future__ import annotations import unittest from transformers import FunnelConfig, is_tf_available from transformers.testing_utils import require_tf from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, ) class A : def __init__( self : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : str=13 , __magic_name__ : List[str]=7 , __magic_name__ : Tuple=True , __magic_name__ : Tuple=True , __magic_name__ : str=True , __magic_name__ : int=True , __magic_name__ : int=99 , __magic_name__ : List[str]=[1, 1, 2] , __magic_name__ : Dict=1 , __magic_name__ : Tuple=32 , __magic_name__ : Any=4 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=37 , __magic_name__ : Tuple="gelu_new" , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : List[str]=0.1 , __magic_name__ : Tuple=0.0 , __magic_name__ : int=512 , __magic_name__ : Optional[int]=3 , __magic_name__ : List[str]=0.02 , __magic_name__ : Dict=3 , __magic_name__ : List[Any]=4 , __magic_name__ : Any=None , __magic_name__ : Dict=False , ): """simple docstring""" lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_input_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = block_sizes lowerCAmelCase__ = num_decoder_layers lowerCAmelCase__ = d_model lowerCAmelCase__ = n_head lowerCAmelCase__ = d_head lowerCAmelCase__ = d_inner lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout lowerCAmelCase__ = attention_dropout lowerCAmelCase__ = activation_dropout lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = 2 lowerCAmelCase__ = num_labels lowerCAmelCase__ = num_choices lowerCAmelCase__ = scope lowerCAmelCase__ = initializer_std # Used in the tests to check the size of the first attention layer lowerCAmelCase__ = n_head # Used in the tests to check the size of the first hidden state lowerCAmelCase__ = self.d_model # Used in the tests to check the number of output hidden states/attentions lowerCAmelCase__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers) # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with # the last hidden state of the first block (which is the first hidden state of the decoder). if not base: lowerCAmelCase__ = self.num_hidden_layers + 2 def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_input_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = None lowerCAmelCase__ = None lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase__ = FunnelConfig( vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : str , __magic_name__ : Any , __magic_name__ : List[Any] , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : int , __magic_name__ : int , ): """simple docstring""" lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = [input_ids, input_mask] lowerCAmelCase__ = model(__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) ) lowerCAmelCase__ = False lowerCAmelCase__ = TFFunnelBaseModel(config=__magic_name__ ) lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForPreTraining(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : str , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , __magic_name__ : Dict , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForMaskedLM(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] , __magic_name__ : List[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : List[Any] , __magic_name__ : Any , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForSequenceClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Any , __magic_name__ : List[str] , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = self.num_choices lowerCAmelCase__ = TFFunnelForMultipleChoice(config=__magic_name__ ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = tf.tile(tf.expand_dims(__magic_name__ , 1 ) , (1, self.num_choices, 1) ) lowerCAmelCase__ = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : str , ): """simple docstring""" lowerCAmelCase__ = self.num_labels lowerCAmelCase__ = TFFunnelForTokenClassification(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : List[str] , ): """simple docstring""" lowerCAmelCase__ = TFFunnelForQuestionAnswering(config=__magic_name__ ) lowerCAmelCase__ = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} lowerCAmelCase__ = model(__magic_name__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.prepare_config_and_inputs() ( ( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) ,( lowerCAmelCase__ ) , ) = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :int = ( ( TFFunnelModel, TFFunnelForMaskedLM, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForTokenClassification, ) if is_tf_available() else () ) snake_case__ :Any = ( { 'feature-extraction': (TFFunnelBaseModel, TFFunnelModel), 'fill-mask': TFFunnelForMaskedLM, 'question-answering': TFFunnelForQuestionAnswering, 'text-classification': TFFunnelForSequenceClassification, 'token-classification': TFFunnelForTokenClassification, 'zero-shot': TFFunnelForSequenceClassification, } if is_tf_available() else {} ) snake_case__ :str = False snake_case__ :Any = False def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @require_tf class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Any = ( (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else () ) snake_case__ :int = False snake_case__ :List[Any] = False def __SCREAMING_SNAKE_CASE ( self : str ): """simple docstring""" lowerCAmelCase__ = TFFunnelModelTester(self , base=__magic_name__ ) lowerCAmelCase__ = ConfigTester(self , config_class=__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" self.config_tester.run_common_tests() def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_base_model(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__magic_name__ )
48
1
'''simple docstring''' import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class A ( SCREAMING_SNAKE_CASE__ , unittest.TestCase ): snake_case__ :Optional[Any] = DebertaTokenizer snake_case__ :int = True snake_case__ :Dict = DebertaTokenizerFast def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "[UNK]", ] lowerCAmelCase__ = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) lowerCAmelCase__ = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] lowerCAmelCase__ = {"unk_token": "[UNK]"} lowerCAmelCase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) lowerCAmelCase__ = 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(__magic_name__ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(__magic_name__ ) ) def __SCREAMING_SNAKE_CASE ( self : Optional[Any] , **__magic_name__ : Optional[Any] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Tuple , __magic_name__ : str ): """simple docstring""" lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = "lower newer" return input_text, output_text def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = "lower newer" lowerCAmelCase__ = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"] lowerCAmelCase__ = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) lowerCAmelCase__ = tokens + [tokenizer.unk_token] lowerCAmelCase__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def __SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = tokenizer("Hello" , "World" ) lowerCAmelCase__ = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd["token_type_ids"] , __magic_name__ ) @slow def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = self.tokenizer_class.from_pretrained("microsoft/deberta-base" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=__magic_name__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=__magic_name__ ) lowerCAmelCase__ = tokenizer.encode( "sequence builders" , add_special_tokens=__magic_name__ , add_prefix_space=__magic_name__ ) lowerCAmelCase__ = tokenizer.encode( "sequence builders" , "multi-sequence build" , add_special_tokens=__magic_name__ , add_prefix_space=__magic_name__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(__magic_name__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(__magic_name__ , __magic_name__ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def __SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: lowerCAmelCase__ = tokenizer_class.from_pretrained("microsoft/deberta-base" ) lowerCAmelCase__ = [ "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations", "ALBERT incorporates two parameter reduction techniques", "The first one is a factorized embedding parameterization. By decomposing the large vocabulary" " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of" " vocabulary embedding.", ] lowerCAmelCase__ = tokenizer(__magic_name__ , padding=__magic_name__ ) lowerCAmelCase__ = [tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) for seq in encoding["input_ids"]] # fmt: off lowerCAmelCase__ = { "input_ids": [ [1, 2118, 11126, 565, 35, 83, 25191, 163, 18854, 13, 12156, 12, 16101, 25376, 13807, 9, 22205, 27893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2118, 11126, 565, 24536, 80, 43797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 133, 78, 65, 16, 10, 3724, 1538, 33183, 11303, 43797, 1938, 4, 870, 24165, 29105, 5, 739, 32644, 33183, 11303, 36173, 88, 80, 650, 7821, 45940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 13171, 31, 5, 1836, 9, 32644, 33183, 11303, 4, 2] ], "token_type_ids": [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], "attention_mask": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on lowerCAmelCase__ = [ "ALBERT: A Lite BERT for Self-supervised Learning of Language Representations", "ALBERT incorporates two parameter reduction techniques", "The first one is a factorized embedding parameterization. By decomposing the large vocabulary" " embedding matrix into two small matrices, we separate the size of the hidden layers from the size of" " vocabulary embedding.", ] self.assertDictEqual(encoding.data , __magic_name__ ) for expected, decoded in zip(__magic_name__ , __magic_name__ ): self.assertEqual(__magic_name__ , __magic_name__ )
48
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : List[str] = { "google/umt5-small": "https://huggingface.co/google/umt5-small/resolve/main/config.json", # See all umt5 models at https://huggingface.co/models?filter=umt5 } class A ( SCREAMING_SNAKE_CASE__ ): snake_case__ :Union[str, Any] = 'umt5' snake_case__ :Any = ['past_key_values'] def __init__( self : List[Any] , __magic_name__ : Tuple=250112 , __magic_name__ : str=512 , __magic_name__ : int=64 , __magic_name__ : str=1024 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=32 , __magic_name__ : Optional[Any]=128 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : int=1E-6 , __magic_name__ : Optional[int]=1.0 , __magic_name__ : Dict="gated-gelu" , __magic_name__ : List[str]=True , __magic_name__ : Tuple=True , __magic_name__ : Optional[int]="T5Tokenizer" , __magic_name__ : str=True , __magic_name__ : int=0 , __magic_name__ : Union[str, Any]=1 , __magic_name__ : str=0 , **__magic_name__ : Any , ): """simple docstring""" super().__init__( is_encoder_decoder=__magic_name__ , tokenizer_class=__magic_name__ , tie_word_embeddings=__magic_name__ , pad_token_id=__magic_name__ , eos_token_id=__magic_name__ , decoder_start_token_id=__magic_name__ , **__magic_name__ , ) lowerCAmelCase__ = vocab_size lowerCAmelCase__ = d_model lowerCAmelCase__ = d_kv lowerCAmelCase__ = d_ff lowerCAmelCase__ = num_layers lowerCAmelCase__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry lowerCAmelCase__ = num_heads lowerCAmelCase__ = relative_attention_num_buckets lowerCAmelCase__ = relative_attention_max_distance lowerCAmelCase__ = dropout_rate lowerCAmelCase__ = layer_norm_epsilon lowerCAmelCase__ = initializer_factor lowerCAmelCase__ = feed_forward_proj lowerCAmelCase__ = use_cache lowerCAmelCase__ = self.feed_forward_proj.split("-" ) lowerCAmelCase__ = act_info[-1] lowerCAmelCase__ = act_info[0] == "gated" if len(__magic_name__ ) > 1 and act_info[0] != "gated" or len(__magic_name__ ) > 2: raise ValueError( f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. " "'gated-gelu' or 'relu'" ) if feed_forward_proj == "gated-gelu": lowerCAmelCase__ = "gelu_new" @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" return self.d_model @property def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" return self.num_heads @property def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return self.num_layers class A ( SCREAMING_SNAKE_CASE__ ): @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs def __SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" lowerCAmelCase__ = { "input_ids": {0: "batch", 1: "encoder_sequence"}, "attention_mask": {0: "batch", 1: "encoder_sequence"}, } if self.use_past: lowerCAmelCase__ = "past_encoder_sequence + sequence" lowerCAmelCase__ = {0: "batch"} lowerCAmelCase__ = {0: "batch", 1: "past_decoder_sequence + sequence"} else: lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} lowerCAmelCase__ = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(__magic_name__ , direction="inputs" ) return common_inputs @property # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 13 @property def __SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" return 5E-4
48
1