code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer snake_case__ : int = logging.get_logger(__name__) snake_case__ : List[str] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} snake_case__ : int = { '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } snake_case__ : Any = { '''bert-base-uncased''': 512, '''bert-large-uncased''': 512, '''bert-base-cased''': 512, '''bert-large-cased''': 512, '''bert-base-multilingual-uncased''': 512, '''bert-base-multilingual-cased''': 512, '''bert-base-chinese''': 512, '''bert-base-german-cased''': 512, '''bert-large-uncased-whole-word-masking''': 512, '''bert-large-cased-whole-word-masking''': 512, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 512, '''bert-large-cased-whole-word-masking-finetuned-squad''': 512, '''bert-base-cased-finetuned-mrpc''': 512, '''bert-base-german-dbmdz-cased''': 512, '''bert-base-german-dbmdz-uncased''': 512, '''TurkuNLP/bert-base-finnish-cased-v1''': 512, '''TurkuNLP/bert-base-finnish-uncased-v1''': 512, '''wietsedv/bert-base-dutch-cased''': 512, } snake_case__ : Tuple = { '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = BertTokenizer def __init__( self : Any , UpperCamelCase_ : List[str]=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : Tuple="[UNK]" , UpperCamelCase_ : List[Any]="[SEP]" , UpperCamelCase_ : List[str]="[PAD]" , UpperCamelCase_ : List[Any]="[CLS]" , UpperCamelCase_ : str="[MASK]" , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : Tuple , ): super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Tuple = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars ): lowerCAmelCase : Optional[Any] = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) ) lowerCAmelCase : List[Any] = do_lower_case lowerCAmelCase : Optional[Any] = strip_accents lowerCAmelCase : Tuple = tokenize_chinese_chars lowerCAmelCase : int = normalizer_class(**UpperCamelCase_ ) lowerCAmelCase : Tuple = do_lower_case def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : int=None ): lowerCAmelCase : Dict = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase__ ( self : str , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : int = [self.sep_token_id] lowerCAmelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : str , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): lowerCAmelCase : str = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
60
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) _a = logging.getLogger(__name__) if __name__ == "__main__": _a = argparse.ArgumentParser( description='Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)' ) parser.add_argument( '--data_file', type=str, default='data/dump.bert-base-uncased.pickle', help='The binarized dataset.' ) parser.add_argument( '--token_counts_dump', type=str, default='data/token_counts.bert-base-uncased.pickle', help='The dump file.' ) parser.add_argument('--vocab_size', default=30_522, type=int) _a = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, 'rb') as fp: _a = pickle.load(fp) logger.info('Counting occurrences for MLM.') _a = Counter() for tk_ids in data: counter.update(tk_ids) _a = [0] * args.vocab_size for k, v in counter.items(): _a = 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)
61
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer _A = logging.get_logger(__name__) _A = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _A = { 'vocab_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json' ), }, } _A = { 'yjernite/retribert-base-uncased': 512, } _A = { 'yjernite/retribert-base-uncased': {'do_lower_case': True}, } class UpperCAmelCase__ ( A_ ): """simple docstring""" UpperCAmelCase__ : Any = VOCAB_FILES_NAMES UpperCAmelCase__ : Dict = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Tuple = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase__ : Optional[int] = RetriBertTokenizer UpperCAmelCase__ : int = ["input_ids", "attention_mask"] def __init__( self , A_=None , A_=None , A_=True , A_="[UNK]" , A_="[SEP]" , A_="[PAD]" , A_="[CLS]" , A_="[MASK]" , A_=True , A_=None , **A_ , ) -> Any: super().__init__( A_ , tokenizer_file=A_ , do_lower_case=A_ , unk_token=A_ , sep_token=A_ , pad_token=A_ , cls_token=A_ , mask_token=A_ , tokenize_chinese_chars=A_ , strip_accents=A_ , **A_ , ) __UpperCamelCase =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , A_ ) != do_lower_case or normalizer_state.get('strip_accents' , A_ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , A_ ) != tokenize_chinese_chars ): __UpperCamelCase =getattr(A_ , normalizer_state.pop('type' ) ) __UpperCamelCase =do_lower_case __UpperCamelCase =strip_accents __UpperCamelCase =tokenize_chinese_chars __UpperCamelCase =normalizer_class(**A_ ) __UpperCamelCase =do_lower_case def _a ( self , A_ , A_=None ) -> Optional[Any]: __UpperCamelCase =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _a ( self , A_ , A_ = None ) -> List[int]: __UpperCamelCase =[self.sep_token_id] __UpperCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _a ( self , A_ , A_ = None ) -> Tuple[str]: __UpperCamelCase =self._tokenizer.model.save(A_ , name=A_ ) return tuple(A_ )
62
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class __SCREAMING_SNAKE_CASE (lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __a =StableDiffusionPanoramaPipeline __a =TEXT_TO_IMAGE_PARAMS __a =TEXT_TO_IMAGE_BATCH_PARAMS __a =TEXT_TO_IMAGE_IMAGE_PARAMS __a =TEXT_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase__ ( self : List[str] ): torch.manual_seed(0 ) _a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) _a = DDIMScheduler() torch.manual_seed(0 ) _a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) _a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) _a = CLIPTextModel(__a ) _a = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _a = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def UpperCamelCase__ ( self : int , __a : Tuple , __a : List[str]=0 ): _a = torch.manual_seed(__a ) _a = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def UpperCamelCase__ ( self : Dict ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = StableDiffusionPanoramaPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = sd_pipe(**__a ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : Dict ): super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ ( self : List[str] ): super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.2_5e-3 ) def UpperCamelCase__ ( self : Union[str, Any] ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = StableDiffusionPanoramaPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = "french fries" _a = sd_pipe(**__a , negative_prompt=__a ) _a = output.images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : int ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = StableDiffusionPanoramaPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = sd_pipe(**__a , view_batch_size=2 ) _a = output.images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : str ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" ) _a = StableDiffusionPanoramaPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = sd_pipe(**__a ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCamelCase__ ( self : int ): _a = "cpu" # ensure determinism for the device-dependent torch.Generator _a = self.get_dummy_components() _a = PNDMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , skip_prk_steps=__a ) _a = StableDiffusionPanoramaPipeline(**__a ) _a = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) _a = self.get_dummy_inputs(__a ) _a = sd_pipe(**__a ).images _a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _a = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __SCREAMING_SNAKE_CASE (unittest.TestCase ): """simple docstring""" def UpperCamelCase__ ( self : Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self : str , __a : Optional[int]=0 ): _a = torch.manual_seed(__a ) _a = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def UpperCamelCase__ ( self : str ): _a = "stabilityai/stable-diffusion-2-base" _a = DDIMScheduler.from_pretrained(__a , subfolder="scheduler" ) _a = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = self.get_inputs() _a = pipe(**__a ).images _a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) _a = np.array( [ 0.36968392, 0.27025372, 0.32446766, 0.28379387, 0.36363274, 0.30733347, 0.27100027, 0.27054125, 0.25536096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def UpperCamelCase__ ( self : Any ): _a = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=__a ) _a = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = self.get_inputs() _a = pipe(**__a ).images _a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) _a = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def UpperCamelCase__ ( self : Optional[int] ): _a = 0 def callback_fn(__a : int , __a : int , __a : torch.FloatTensor ) -> None: _a = True nonlocal number_of_steps number_of_steps += 1 if step == 1: _a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) _a = latents[0, -3:, -3:, -1] _a = np.array( [ 0.18681869, 0.33907816, 0.5361276, 0.14432865, -0.02856611, -0.73941123, 0.23397987, 0.47322682, -0.37823164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: _a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) _a = latents[0, -3:, -3:, -1] _a = np.array( [ 0.18539645, 0.33987248, 0.5378559, 0.14437142, -0.02455261, -0.7338317, 0.23990755, 0.47356272, -0.3786505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 _a = False _a = "stabilityai/stable-diffusion-2-base" _a = DDIMScheduler.from_pretrained(__a , subfolder="scheduler" ) _a = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) _a = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing() _a = self.get_inputs() pipe(**__a , callback=__a , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def UpperCamelCase__ ( self : Tuple ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _a = "stabilityai/stable-diffusion-2-base" _a = DDIMScheduler.from_pretrained(__a , subfolder="scheduler" ) _a = StableDiffusionPanoramaPipeline.from_pretrained(__a , scheduler=__a , safety_checker=__a ) _a = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _a = self.get_inputs() _a = pipe(**__a ) _a = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
63
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration A_ = 50_00_00 A_ , A_ = os.path.split(__file__) A_ = os.path.join(RESULTS_BASEPATH, '''results''', RESULTS_FILENAME.replace('''.py''', '''.json''')) @get_duration def UpperCAmelCase__ (snake_case__ : datasets.Dataset , **snake_case__ : Optional[int] ): """simple docstring""" _snake_case : Tuple = dataset.map(**snake_case__ ) @get_duration def UpperCAmelCase__ (snake_case__ : datasets.Dataset , **snake_case__ : Any ): """simple docstring""" _snake_case : List[str] = dataset.filter(**snake_case__ ) def UpperCAmelCase__ (): """simple docstring""" _snake_case : Dict = {"""num examples""": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: _snake_case : Dict = datasets.Features({"""text""": datasets.Value("""string""" ), """numbers""": datasets.Value("""float32""" )} ) _snake_case : List[Any] = generate_example_dataset( os.path.join(snake_case__ , """dataset.arrow""" ) , snake_case__ , num_examples=snake_case__ ) _snake_case : List[Any] = transformers.AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=snake_case__ ) def tokenize(snake_case__ : Optional[int] ): return tokenizer(examples["""text"""] ) _snake_case : str = map(snake_case__ ) _snake_case : Optional[int] = map(snake_case__ , batched=snake_case__ ) _snake_case : int = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type="""numpy""" ): _snake_case : Dict = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type="""pandas""" ): _snake_case : List[str] = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type="""torch""" , columns="""numbers""" ): _snake_case : Union[str, Any] = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) with dataset.formatted_as(type="""tensorflow""" , columns="""numbers""" ): _snake_case : List[str] = map(snake_case__ , function=lambda snake_case__ : None , batched=snake_case__ ) _snake_case : Dict = map(snake_case__ , function=snake_case__ , batched=snake_case__ ) _snake_case : List[str] = filter(snake_case__ ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(snake_case__ , """wb""" ) as f: f.write(json.dumps(snake_case__ ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
64
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
import math def lowerCAmelCase_ ( __A, __A ) -> float: '''simple docstring''' return math.pow(__A, 2 ) - a def lowerCAmelCase_ ( __A ) -> float: '''simple docstring''' return 2 * x def lowerCAmelCase_ ( __A ) -> float: '''simple docstring''' UpperCAmelCase__ = 2.0 while start <= a: UpperCAmelCase__ = math.pow(__A, 2 ) return start def lowerCAmelCase_ ( __A, __A = 9_999, __A = 0.00000000000001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("math domain error" ) UpperCAmelCase__ = get_initial_point(__A ) for _ in range(__A ): UpperCAmelCase__ = value UpperCAmelCase__ = value - fx(__A, __A ) / fx_derivative(__A ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
65
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES __a = logging.get_logger(__name__) __a = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) __a = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __a = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) __a = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) __a = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) __a = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) __a = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) __a = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) __a = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) __a = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) __a = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) __a = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) __a = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) __a = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) __a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) __a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) __a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) __a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) __a = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) __a = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Optional[int] = FLAX_MODEL_MAPPING __a = auto_class_update(FlaxAutoModel) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Union[str, Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING __a = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Dict = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING __a = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Optional[int] = FLAX_MODEL_FOR_MASKED_LM_MAPPING __a = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Union[str, Any] = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING __a = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Union[str, Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __a = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : str = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING __a = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : int = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING __a = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : List[Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING __a = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Optional[int] = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING __a = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Optional[Any] = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING __a = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING __a = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class lowerCamelCase ( _BaseAutoModelClass ): '''simple docstring''' _A : Optional[int] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING __a = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
66
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
'''simple docstring''' import dataclasses import json import warnings from dataclasses import dataclass, field from time import time from typing import List from ..utils import logging __UpperCAmelCase =logging.get_logger(__name__) def __lowerCAmelCase ( UpperCamelCase__=None , UpperCamelCase__=None ) -> int: return field(default_factory=lambda: default , metadata=UpperCamelCase__ ) @dataclass class a__ : lowerCamelCase : List[str] =list_field( default=[] , metadata={ "help": ( "Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version" " of all available models" ) } , ) lowerCamelCase : List[int] =list_field( default=[8] , metadata={"help": "List of batch sizes for which memory and time performance will be evaluated"} ) lowerCamelCase : List[int] =list_field( default=[8, 3_2, 1_2_8, 5_1_2] , metadata={"help": "List of sequence lengths for which memory and time performance will be evaluated"} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to benchmark inference of model. Inference can be disabled via --no-inference."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available cuda devices. Cuda can be disabled via --no-cuda."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to run on available tpu devices. TPU can be disabled via --no-tpu."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Use FP16 to accelerate inference."} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Benchmark training of model"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Verbose memory tracing"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={"help": "Whether to perform speed measurements. Speed measurements can be disabled via --no-speed."} , ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": "Whether to perform memory measurements. Memory measurements can be disabled via --no-memory" } , ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Trace memory line by line"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save result to a CSV file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Save all print statements in a log file"} ) lowerCamelCase : bool =field(default=UpperCAmelCase__ , metadata={"help": "Whether to print environment information"} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use" " multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled" " for debugging / testing and on TPU." ) } , ) lowerCamelCase : str =field( default=F'''inference_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv."} , ) lowerCamelCase : str =field( default=F'''inference_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv."} , ) lowerCamelCase : str =field( default=F'''train_time_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving time results to csv for training."} , ) lowerCamelCase : str =field( default=F'''train_memory_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving memory results to csv for training."} , ) lowerCamelCase : str =field( default=F'''env_info_{round(time() )}.csv''' , metadata={"help": "CSV filename used if saving environment information."} , ) lowerCamelCase : str =field( default=F'''log_{round(time() )}.csv''' , metadata={"help": "Log filename used if print statements are saved in log."} , ) lowerCamelCase : int =field(default=3 , metadata={"help": "Times an experiment will be run."} ) lowerCamelCase : bool =field( default=UpperCAmelCase__ , metadata={ "help": ( "Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain" " model weights." ) } , ) def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" warnings.warn( f"""The class {self.__class__} is deprecated. Hugging Face Benchmarking utils""" ''' are deprecated in general and it is advised to use external Benchmarking libraries ''' ''' to benchmark Transformer models.''' , a , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" return json.dumps(dataclasses.asdict(self ) , indent=2 ) @property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" if len(self.models ) <= 0: raise ValueError( '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models''' ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].''' ) return self.models @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" if not self.multi_process: return False elif self.is_tpu: logger.info('''Multiprocessing is currently not possible on TPU.''' ) return False else: return True
67
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
import unittest import numpy as np from transformers import is_flax_available from transformers.testing_utils import require_flax from ..test_modeling_flax_common import ids_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.generation import ( FlaxForcedBOSTokenLogitsProcessor, FlaxForcedEOSTokenLogitsProcessor, FlaxLogitsProcessorList, FlaxMinLengthLogitsProcessor, FlaxTemperatureLogitsWarper, FlaxTopKLogitsWarper, FlaxTopPLogitsWarper, ) @require_flax class a__ ( unittest.TestCase ): """simple docstring""" def UpperCamelCase ( self , lowercase , lowercase ) -> Any: '''simple docstring''' A__ = jnp.ones((batch_size, length) ) / length return scores def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = None A__ = 20 A__ = self._get_uniform_logits(batch_size=2 , length=lowercase ) # tweak scores to not be uniform anymore A__ = scores.at[1, 5].set((1 / length) + 0.1 ) # peak, 1st batch A__ = scores.at[1, 10].set((1 / length) - 0.4 ) # valley, 1st batch # compute softmax A__ = jax.nn.softmax(lowercase , axis=-1 ) A__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) A__ = FlaxTemperatureLogitsWarper(temperature=1.3 ) A__ = jax.nn.softmax(temp_dist_warper_sharper(lowercase , scores.copy() , cur_len=lowercase ) , axis=-1 ) A__ = jax.nn.softmax(temp_dist_warper_smoother(lowercase , scores.copy() , cur_len=lowercase ) , axis=-1 ) # uniform distribution stays uniform self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_sharp[0, :] , atol=1e-3 ) ) self.assertTrue(jnp.allclose(probs[0, :] , warped_prob_smooth[0, :] , atol=1e-3 ) ) # sharp peaks get higher, valleys get lower self.assertLess(probs[1, :].max() , warped_prob_sharp[1, :].max() ) self.assertGreater(probs[1, :].min() , warped_prob_sharp[1, :].min() ) # smooth peaks get lower, valleys get higher self.assertGreater(probs[1, :].max() , warped_prob_smooth[1, :].max() ) self.assertLess(probs[1, :].min() , warped_prob_smooth[1, :].min() ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = None A__ = 10 A__ = 2 # create ramp distribution A__ = np.broadcast_to(np.arange(lowercase )[None, :] , (batch_size, vocab_size) ).copy() A__ = ramp_logits[1:, : vocab_size // 2] + vocab_size A__ = FlaxTopKLogitsWarper(3 ) A__ = top_k_warp(lowercase , lowercase , cur_len=lowercase ) # check that correct tokens are filtered self.assertListEqual(jnp.isinf(scores[0] ).tolist() , 7 * [True] + 3 * [False] ) self.assertListEqual(jnp.isinf(scores[1] ).tolist() , 2 * [True] + 3 * [False] + 5 * [True] ) # check special case A__ = 5 A__ = FlaxTopKLogitsWarper(top_k=1 , filter_value=0.0 , min_tokens_to_keep=3 ) A__ = np.broadcast_to(np.arange(lowercase )[None, :] , (batch_size, length) ).copy() A__ = top_k_warp_safety_check(lowercase , lowercase , cur_len=lowercase ) # min_tokens overwrites k: 3 tokens are kept => 2 tokens are nullified self.assertListEqual((scores == 0.0).sum(axis=-1 ).tolist() , [2, 2] ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = None A__ = 10 A__ = 2 # create distribution and take log (inverse to Softmax as taken in TopPLogitsWarper) A__ = np.log(np.array([[0.3, 0.1, 0.1, 0.5], [0.15, 0.3, 0.3, 0.25]] ) ) A__ = FlaxTopPLogitsWarper(0.8 ) A__ = np.exp(top_p_warp(lowercase , lowercase , cur_len=lowercase ) ) # dist should be filtered to keep min num values so that sum is >= top_p # exp (-inf) => 0 A__ = np.array([[0.3, 0.0, 0.0, 0.5], [0.0, 0.3, 0.3, 0.25]] ) self.assertTrue(np.allclose(lowercase , lowercase , atol=1e-3 ) ) # check edge cases with negative and extreme logits A__ = np.broadcast_to(np.arange(lowercase )[None, :] , (batch_size, vocab_size) ).copy() - ( vocab_size // 2 ) # make ramp_logits more extreme A__ = ramp_logits[1] * 100.0 # make sure at least 2 tokens are kept A__ = FlaxTopPLogitsWarper(0.9 , min_tokens_to_keep=2 , filter_value=0.0 ) A__ = top_p_warp(lowercase , lowercase , cur_len=lowercase ) # first batch should keep three tokens, second batch would keep only 1, but due to `min_tokens_to_keep=2` keeps 2. self.assertListEqual((filtered_dist != 0.0).sum(axis=-1 ).tolist() , [3, 2] ) def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = 20 A__ = 4 A__ = 0 A__ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase ) # check that min length is applied at length 5 A__ = ids_tensor((batch_size, 20) , vocab_size=20 ) A__ = 5 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = min_dist_processor(lowercase , lowercase , cur_len=lowercase ) self.assertListEqual(scores_before_min_length[:, eos_token_id].tolist() , 4 * [-float("inf" )] ) # check that min length is not applied anymore at length 15 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = 15 A__ = min_dist_processor(lowercase , lowercase , cur_len=lowercase ) self.assertFalse(jnp.isinf(lowercase ).any() ) def UpperCamelCase ( self ) -> str: '''simple docstring''' A__ = 20 A__ = 4 A__ = 0 A__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase ) # check that all scores are -inf except the bos_token_id score A__ = ids_tensor((batch_size, 1) , vocab_size=20 ) A__ = 1 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = logits_processor(lowercase , lowercase , cur_len=lowercase ) self.assertTrue(jnp.isneginf(scores[:, bos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, bos_token_id].tolist() , 4 * [0] ) # score for bos_token_id shold be zero # check that bos_token_id is not forced if current length is greater than 1 A__ = 3 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = logits_processor(lowercase , lowercase , cur_len=lowercase ) self.assertFalse(jnp.isinf(lowercase ).any() ) def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' A__ = 20 A__ = 4 A__ = 0 A__ = 5 A__ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase ) # check that all scores are -inf except the eos_token_id when max_length is reached A__ = ids_tensor((batch_size, 4) , vocab_size=20 ) A__ = 4 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = logits_processor(lowercase , lowercase , cur_len=lowercase ) self.assertTrue(jnp.isneginf(scores[:, eos_token_id + 1 :] ).all() ) self.assertListEqual(scores[:, eos_token_id].tolist() , 4 * [0] ) # score for eos_token_id should be zero # check that eos_token_id is not forced if max_length is not reached A__ = 3 A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = logits_processor(lowercase , lowercase , cur_len=lowercase ) self.assertFalse(jnp.isinf(lowercase ).any() ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = 4 A__ = 10 A__ = 15 A__ = 2 A__ = 1 A__ = 15 # dummy input_ids and scores A__ = ids_tensor((batch_size, sequence_length) , lowercase ) A__ = input_ids.copy() A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = scores.copy() # instantiate all dist processors A__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) A__ = FlaxTopKLogitsWarper(3 ) A__ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors A__ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase ) A__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase ) A__ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase ) A__ = 10 # no processor list A__ = temp_dist_warp(lowercase , lowercase , cur_len=lowercase ) A__ = top_k_warp(lowercase , lowercase , cur_len=lowercase ) A__ = top_p_warp(lowercase , lowercase , cur_len=lowercase ) A__ = min_dist_proc(lowercase , lowercase , cur_len=lowercase ) A__ = bos_dist_proc(lowercase , lowercase , cur_len=lowercase ) A__ = eos_dist_proc(lowercase , lowercase , cur_len=lowercase ) # with processor list A__ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) A__ = processor(lowercase , lowercase , cur_len=lowercase ) # scores should be equal self.assertTrue(jnp.allclose(lowercase , lowercase , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' A__ = 4 A__ = 10 A__ = 15 A__ = 2 A__ = 1 A__ = 15 # dummy input_ids and scores A__ = ids_tensor((batch_size, sequence_length) , lowercase ) A__ = input_ids.copy() A__ = self._get_uniform_logits(lowercase , lowercase ) A__ = scores.copy() # instantiate all dist processors A__ = FlaxTemperatureLogitsWarper(temperature=0.5 ) A__ = FlaxTopKLogitsWarper(3 ) A__ = FlaxTopPLogitsWarper(0.8 ) # instantiate all logits processors A__ = FlaxMinLengthLogitsProcessor(min_length=10 , eos_token_id=lowercase ) A__ = FlaxForcedBOSTokenLogitsProcessor(bos_token_id=lowercase ) A__ = FlaxForcedEOSTokenLogitsProcessor(max_length=lowercase , eos_token_id=lowercase ) A__ = 10 # no processor list def run_no_processor_list(lowercase , lowercase , lowercase ): A__ = temp_dist_warp(lowercase , lowercase , cur_len=lowercase ) A__ = top_k_warp(lowercase , lowercase , cur_len=lowercase ) A__ = top_p_warp(lowercase , lowercase , cur_len=lowercase ) A__ = min_dist_proc(lowercase , lowercase , cur_len=lowercase ) A__ = bos_dist_proc(lowercase , lowercase , cur_len=lowercase ) A__ = eos_dist_proc(lowercase , lowercase , cur_len=lowercase ) return scores # with processor list def run_processor_list(lowercase , lowercase , lowercase ): A__ = FlaxLogitsProcessorList( [temp_dist_warp, top_k_warp, top_p_warp, min_dist_proc, bos_dist_proc, eos_dist_proc] ) A__ = processor(lowercase , lowercase , cur_len=lowercase ) return scores A__ = jax.jit(lowercase ) A__ = jax.jit(lowercase ) A__ = jitted_run_no_processor_list(lowercase , lowercase , lowercase ) A__ = jitted_run_processor_list(lowercase , lowercase , lowercase ) # scores should be equal self.assertTrue(jnp.allclose(lowercase , lowercase , atol=1e-3 ) ) # input_ids should never be changed self.assertListEqual(input_ids.tolist() , input_ids_comp.tolist() )
68
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel __UpperCamelCase = logging.getLogger(__name__) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase ) -> Optional[Any]: # save results if os.path.exists(UpperCAmelCase ): if os.path.exists(os.path.join(UpperCAmelCase , 'config.json' ) ) and os.path.isfile( os.path.join(UpperCAmelCase , 'config.json' ) ): os.remove(os.path.join(UpperCAmelCase , 'config.json' ) ) if os.path.exists(os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ) and os.path.isfile( os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ): os.remove(os.path.join(UpperCAmelCase , 'pytorch_model.bin' ) ) else: os.makedirs(UpperCAmelCase ) model.save_pretrained(UpperCAmelCase ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase=False ) -> Union[str, Any]: snake_case_ = 2 if unlogit: snake_case_ = torch.pow(UpperCAmelCase , UpperCAmelCase ) snake_case_ = p * torch.log(UpperCAmelCase ) snake_case_ = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase ( UpperCAmelCase ) -> List[str]: logger.info('lv, h >\t' + '\t'.join(f'{x + 1}' for x in range(len(UpperCAmelCase ) ) ) ) for row in range(len(UpperCAmelCase ) ): if tensor.dtype != torch.long: logger.info(f'layer {row + 1}:\t' + '\t'.join(f'{x:.5f}' for x in tensor[row].cpu().data ) ) else: logger.info(f'layer {row + 1}:\t' + '\t'.join(f'{x:d}' for x in tensor[row].cpu().data ) ) def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=True , UpperCAmelCase=True , UpperCAmelCase=None , UpperCAmelCase=False ) -> Union[str, Any]: snake_case_ , snake_case_ = model.config.num_hidden_layers, model.config.num_attention_heads snake_case_ = torch.zeros(UpperCAmelCase , UpperCAmelCase ).to(args.device ) snake_case_ = torch.zeros(UpperCAmelCase , UpperCAmelCase ).to(args.device ) if head_mask is None: snake_case_ = torch.ones(UpperCAmelCase , UpperCAmelCase ).to(args.device ) head_mask.requires_grad_(requires_grad=UpperCAmelCase ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: snake_case_ = None snake_case_ = 0.0 snake_case_ = 0.0 for step, inputs in enumerate(tqdm(UpperCAmelCase , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): snake_case_ = tuple(t.to(args.device ) for t in inputs ) ((snake_case_) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) snake_case_ = model(UpperCAmelCase , labels=UpperCAmelCase , head_mask=UpperCAmelCase ) # (loss), lm_logits, presents, (all hidden_states), (attentions) snake_case_ , snake_case_ , snake_case_ = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(UpperCAmelCase ): snake_case_ = entropy(attn.detach() , UpperCAmelCase ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(UpperCAmelCase ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: snake_case_ = 2 snake_case_ = torch.pow(torch.pow(UpperCAmelCase , UpperCAmelCase ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-20 if not args.dont_normalize_global_importance: snake_case_ = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info('Attention entropies' ) print_ad_tensor(UpperCAmelCase ) if compute_importance: logger.info('Head importance scores' ) print_ad_tensor(UpperCAmelCase ) logger.info('Head ranked by importance scores' ) snake_case_ = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) snake_case_ = torch.arange( head_importance.numel() , device=args.device ) snake_case_ = head_ranks.view_as(UpperCAmelCase ) print_ad_tensor(UpperCAmelCase ) return attn_entropy, head_importance, total_loss def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> List[Any]: snake_case_ , snake_case_ , snake_case_ = compute_heads_importance(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase ) snake_case_ = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , UpperCAmelCase , original_score * args.masking_threshold ) snake_case_ = torch.ones_like(UpperCAmelCase ) snake_case_ = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) snake_case_ = original_score while current_score >= original_score * args.masking_threshold: snake_case_ = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads snake_case_ = float('Inf' ) snake_case_ = head_importance.view(-1 ).sort()[1] if len(UpperCAmelCase ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads snake_case_ = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) snake_case_ = new_head_mask.view(-1 ) snake_case_ = 0.0 snake_case_ = new_head_mask.view_as(UpperCAmelCase ) snake_case_ = new_head_mask.clone().detach() print_ad_tensor(UpperCAmelCase ) # Compute metric and head importance again snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , head_mask=UpperCAmelCase ) snake_case_ = 1 / loss logger.info( 'Masking: current score: %f, remaining heads %d (%.1f percents)' , UpperCAmelCase , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info('Final head mask' ) print_ad_tensor(UpperCAmelCase ) np.save(os.path.join(args.output_dir , 'head_mask.npy' ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]: snake_case_ = datetime.now() snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , compute_importance=UpperCAmelCase , head_mask=UpperCAmelCase ) snake_case_ = 1 / loss snake_case_ = datetime.now() - before_time snake_case_ = sum(p.numel() for p in model.parameters() ) snake_case_ = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(UpperCAmelCase ) ) } for k, v in heads_to_prune.items(): if isinstance(UpperCAmelCase , UpperCAmelCase ): snake_case_ = [ v, ] assert sum(len(UpperCAmelCase ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(UpperCAmelCase ) snake_case_ = sum(p.numel() for p in model.parameters() ) snake_case_ = datetime.now() snake_case_ , snake_case_ , snake_case_ = compute_heads_importance( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , compute_entropy=UpperCAmelCase , compute_importance=UpperCAmelCase , head_mask=UpperCAmelCase , actually_pruned=UpperCAmelCase , ) snake_case_ = 1 / loss snake_case_ = datetime.now() - before_time logger.info( 'Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)' , UpperCAmelCase , UpperCAmelCase , pruned_num_params / original_num_params * 100 , ) logger.info('Pruning: score with masking: %f score with pruning: %f' , UpperCAmelCase , UpperCAmelCase ) logger.info('Pruning: speed ratio (original timing / new timing): %f percents' , original_time / new_time * 100 ) save_model(UpperCAmelCase , args.output_dir ) def UpperCAmelCase ( ) -> List[str]: snake_case_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--data_dir' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='The input data dir. Should contain the .tsv files (or other data files) for the task.' , ) parser.add_argument( '--model_name_or_path' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='Path to pretrained model or model identifier from huggingface.co/models' , ) parser.add_argument( '--output_dir' , default=UpperCAmelCase , type=UpperCAmelCase , required=UpperCAmelCase , help='The output directory where the model predictions and checkpoints will be written.' , ) # Other parameters parser.add_argument( '--config_name' , default='' , type=UpperCAmelCase , help='Pretrained config name or path if not the same as model_name_or_path' , ) parser.add_argument( '--tokenizer_name' , default='' , type=UpperCAmelCase , help='Pretrained tokenizer name or path if not the same as model_name_or_path' , ) parser.add_argument( '--cache_dir' , default=UpperCAmelCase , type=UpperCAmelCase , help='Where do you want to store the pre-trained models downloaded from s3' , ) parser.add_argument( '--data_subset' , type=UpperCAmelCase , default=-1 , help='If > 0: limit the data to a subset of data_subset instances.' ) parser.add_argument( '--overwrite_output_dir' , action='store_true' , help='Whether to overwrite data in output directory' ) parser.add_argument( '--overwrite_cache' , action='store_true' , help='Overwrite the cached training and evaluation sets' ) parser.add_argument( '--dont_normalize_importance_by_layer' , action='store_true' , help='Don\'t normalize importance score by layers' ) parser.add_argument( '--dont_normalize_global_importance' , action='store_true' , help='Don\'t normalize all importance scores between 0 and 1' , ) parser.add_argument( '--try_masking' , action='store_true' , help='Whether to try to mask head until a threshold of accuracy.' ) parser.add_argument( '--masking_threshold' , default=0.9 , type=UpperCAmelCase , help='masking threshold in term of metrics (stop masking when metric < threshold * original metric value).' , ) parser.add_argument( '--masking_amount' , default=0.1 , type=UpperCAmelCase , help='Amount to heads to masking at each masking step.' ) parser.add_argument('--metric_name' , default='acc' , type=UpperCAmelCase , help='Metric to use for head masking.' ) parser.add_argument( '--max_seq_length' , default=128 , type=UpperCAmelCase , help=( 'The maximum total input sequence length after WordPiece tokenization. \n' 'Sequences longer than this will be truncated, sequences shorter padded.' ) , ) parser.add_argument('--batch_size' , default=1 , type=UpperCAmelCase , help='Batch size.' ) parser.add_argument('--seed' , type=UpperCAmelCase , default=42 ) parser.add_argument('--local_rank' , type=UpperCAmelCase , default=-1 , help='local_rank for distributed training on gpus' ) parser.add_argument('--no_cuda' , action='store_true' , help='Whether not to use CUDA when available' ) parser.add_argument('--server_ip' , type=UpperCAmelCase , default='' , help='Can be used for distant debugging.' ) parser.add_argument('--server_port' , type=UpperCAmelCase , default='' , help='Can be used for distant debugging.' ) snake_case_ = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print('Waiting for debugger attach' ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=UpperCAmelCase ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: snake_case_ = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) snake_case_ = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) snake_case_ = torch.device('cuda' , args.local_rank ) snake_case_ = 1 torch.distributed.init_process_group(backend='nccl' ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info('device: {} n_gpu: {}, distributed: {}'.format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) snake_case_ = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: snake_case_ = nn.parallel.DistributedDataParallel( UpperCAmelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=UpperCAmelCase ) elif args.n_gpu > 1: snake_case_ = nn.DataParallel(UpperCAmelCase ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=UpperCAmelCase ) torch.save(UpperCAmelCase , os.path.join(args.output_dir , 'run_args.bin' ) ) logger.info('Training/evaluation parameters %s' , UpperCAmelCase ) # Prepare dataset snake_case_ = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) snake_case_ = (torch.from_numpy(UpperCAmelCase ),) snake_case_ = TensorDataset(*UpperCAmelCase ) snake_case_ = RandomSampler(UpperCAmelCase ) snake_case_ = DataLoader(UpperCAmelCase , sampler=UpperCAmelCase , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: snake_case_ = mask_heads(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) prune_heads(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) if __name__ == "__main__": main()
69
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class UpperCAmelCase ( unittest.TestCase ): def lowercase__ ( self : str ) -> Optional[Any]: _lowerCAmelCase = ["""a""", """b""", """c"""] # Defaults to last layer if both are None _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices(__snake_case , __snake_case , __snake_case ) self.assertEqual(__snake_case , ["""c"""] ) self.assertEqual(__snake_case , [2] ) # Out indices set to match out features _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices(["""a""", """c"""] , __snake_case , __snake_case ) self.assertEqual(__snake_case , ["""a""", """c"""] ) self.assertEqual(__snake_case , [0, 2] ) # Out features set to match out indices _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices(__snake_case , [0, 2] , __snake_case ) self.assertEqual(__snake_case , ["""a""", """c"""] ) self.assertEqual(__snake_case , [0, 2] ) # Out features selected from negative indices _lowerCAmelCase , _lowerCAmelCase = get_aligned_output_features_output_indices(__snake_case , [-3, -1] , __snake_case ) self.assertEqual(__snake_case , ["""a""", """c"""] ) self.assertEqual(__snake_case , [-3, -1] ) def lowercase__ ( self : Optional[int] ) -> Union[str, Any]: # Stage names must be set with self.assertRaises(__snake_case ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , __snake_case ) # Out features must be a list with self.assertRaises(__snake_case ): verify_out_features_out_indices(("""a""", """b""") , (0, 1) , ["""a""", """b"""] ) # Out features must be a subset of stage names with self.assertRaises(__snake_case ): verify_out_features_out_indices(["""a""", """b"""] , (0, 1) , ["""a"""] ) # Out indices must be a list or tuple with self.assertRaises(__snake_case ): verify_out_features_out_indices(__snake_case , 0 , ["""a""", """b"""] ) # Out indices must be a subset of stage names with self.assertRaises(__snake_case ): verify_out_features_out_indices(__snake_case , (0, 1) , ["""a"""] ) # Out features and out indices must be the same length with self.assertRaises(__snake_case ): verify_out_features_out_indices(["""a""", """b"""] , (0,) , ["""a""", """b""", """c"""] ) # Out features should match out indices with self.assertRaises(__snake_case ): verify_out_features_out_indices(["""a""", """b"""] , (0, 2) , ["""a""", """b""", """c"""] ) # Out features and out indices should be in order with self.assertRaises(__snake_case ): verify_out_features_out_indices(["""b""", """a"""] , (0, 1) , ["""a""", """b"""] ) # Check passes with valid inputs verify_out_features_out_indices(["""a""", """b""", """d"""] , (0, 1, -1) , ["""a""", """b""", """c""", """d"""] ) def lowercase__ ( self : int ) -> List[str]: _lowerCAmelCase = BackboneMixin() _lowerCAmelCase = ["""a""", """b""", """c"""] _lowerCAmelCase = ["""a""", """c"""] _lowerCAmelCase = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly _lowerCAmelCase = ["""a""", """b"""] self.assertEqual(backbone.out_features , ["""a""", """b"""] ) self.assertEqual(backbone.out_indices , [0, 1] ) _lowerCAmelCase = [-3, -1] self.assertEqual(backbone.out_features , ["""a""", """c"""] ) self.assertEqual(backbone.out_indices , [-3, -1] )
70
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = 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__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ :Optional[Any] = logging.get_logger() def A ( a_ ,a_ ,a_ ,a_ ,a_ = True ) -> Optional[int]: print(F'Converting {name}...' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __UpperCamelCase : List[str] =timm.create_model('levit_128s' ,pretrained=a_ ) else: __UpperCamelCase : str =timm.create_model('levit_128' ,pretrained=a_ ) if hidden_sizes == 192: __UpperCamelCase : Optional[Any] =timm.create_model('levit_192' ,pretrained=a_ ) if hidden_sizes == 256: __UpperCamelCase : Union[str, Any] =timm.create_model('levit_256' ,pretrained=a_ ) if hidden_sizes == 384: __UpperCamelCase : Optional[Any] =timm.create_model('levit_384' ,pretrained=a_ ) from_model.eval() __UpperCamelCase : Any =LevitForImageClassificationWithTeacher(a_ ).eval() __UpperCamelCase : Optional[int] =OrderedDict() __UpperCamelCase : List[str] =from_model.state_dict() __UpperCamelCase : Any =list(from_model.state_dict().keys() ) __UpperCamelCase : int =list(our_model.state_dict().keys() ) print(len(a_ ) ,len(a_ ) ) for i in range(len(a_ ) ): __UpperCamelCase : Optional[Any] =weights[og_keys[i]] our_model.load_state_dict(a_ ) __UpperCamelCase : Optional[int] =torch.randn((2, 3, 224, 224) ) __UpperCamelCase : Optional[Any] =from_model(a_ ) __UpperCamelCase : Union[str, Any] =our_model(a_ ).logits assert torch.allclose(a_ ,a_ ), "The model logits don't match the original one." __UpperCamelCase : str =name print(a_ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __UpperCamelCase : Tuple =LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F'Pushed {checkpoint_name}' ) def A ( a_ ,a_ = None ,a_ = True ) -> Any: __UpperCamelCase : Optional[Any] ='imagenet-1k-id2label.json' __UpperCamelCase : str =1_000 __UpperCamelCase : Any =(1, num_labels) __UpperCamelCase : List[Any] ='huggingface/label-files' __UpperCamelCase : List[Any] =num_labels __UpperCamelCase : List[Any] =json.load(open(hf_hub_download(a_ ,a_ ,repo_type='dataset' ) ,'r' ) ) __UpperCamelCase : Union[str, Any] ={int(a_ ): v for k, v in idalabel.items()} __UpperCamelCase : Union[str, Any] =idalabel __UpperCamelCase : int ={v: k for k, v in idalabel.items()} __UpperCamelCase : List[str] =partial(a_ ,num_labels=a_ ,idalabel=a_ ,labelaid=a_ ) __UpperCamelCase : List[str] ={ 'levit-128S': 128, 'levit-128': 128, 'levit-192': 192, 'levit-256': 256, 'levit-384': 384, } __UpperCamelCase : str ={ 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] ,num_attention_heads=[6, 9, 12] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0.1 ,), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] ,a_ ,names_to_config[model_name] ,a_ ,a_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] ,a_ ,a_ ,a_ ,a_ ) return config, expected_shape if __name__ == "__main__": A_ :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) A_ :int = parser.parse_args() A_ :Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
71
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Any = tempfile.mkdtemp() # fmt: off _lowerCamelCase : str = ['''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''lo''', '''l</w>''', '''w</w>''', '''r</w>''', '''t</w>''', '''low</w>''', '''er</w>''', '''lowest</w>''', '''newer</w>''', '''wider''', '''<unk>''', '''<|startoftext|>''', '''<|endoftext|>'''] # fmt: on _lowerCamelCase : Union[str, Any] = dict(zip(__lowerCAmelCase , range(len(__lowerCAmelCase ) ) ) ) _lowerCamelCase : Optional[Any] = ['''#version: 0.2''', '''l o''', '''lo w</w>''', '''e r</w>''', ''''''] _lowerCamelCase : str = {'''unk_token''': '''<unk>'''} _lowerCamelCase : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _lowerCamelCase : List[Any] = 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(__lowerCAmelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__lowerCAmelCase ) ) _lowerCamelCase : Union[str, Any] = { '''do_resize''': True, '''size''': 2_0, '''do_center_crop''': True, '''crop_size''': 1_8, '''do_normalize''': True, '''image_mean''': [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73], '''image_std''': [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11], } _lowerCamelCase : Any = os.path.join(self.tmpdirname , __lowerCAmelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , **__lowerCAmelCase : List[Any] ): """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : str , **__lowerCAmelCase : str ): """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any , **__lowerCAmelCase : List[str] ): """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : Tuple = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] _lowerCamelCase : Optional[int] = [Image.fromarray(np.moveaxis(__lowerCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Tuple = self.get_tokenizer() _lowerCamelCase : Tuple = self.get_rust_tokenizer() _lowerCamelCase : Union[str, Any] = self.get_image_processor() _lowerCamelCase : Optional[int] = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) _lowerCamelCase : Tuple = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=__lowerCAmelCase ) _lowerCamelCase : List[str] = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) _lowerCamelCase : Tuple = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , __lowerCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , __lowerCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , __lowerCAmelCase ) self.assertIsInstance(processor_fast.image_processor , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : str = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _lowerCamelCase : Dict = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) _lowerCamelCase : Dict = self.get_image_processor(do_normalize=__lowerCAmelCase , padding_value=1.0 ) _lowerCamelCase : int = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__lowerCAmelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , __lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : int = self.get_image_processor() _lowerCamelCase : Union[str, Any] = self.get_tokenizer() _lowerCamelCase : Optional[Any] = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _lowerCamelCase : Any = self.prepare_image_inputs() _lowerCamelCase : int = image_processor(__lowerCAmelCase , return_tensors='''np''' ) _lowerCamelCase : Union[str, Any] = processor(images=__lowerCAmelCase , 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 : Tuple ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.get_image_processor() _lowerCamelCase : Any = self.get_tokenizer() _lowerCamelCase : Dict = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = '''lower newer''' _lowerCamelCase : List[Any] = processor(text=__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = tokenizer(__lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : str = self.get_image_processor() _lowerCamelCase : Union[str, Any] = self.get_tokenizer() _lowerCamelCase : Union[str, Any] = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _lowerCamelCase : Any = '''lower newer''' _lowerCamelCase : Dict = self.prepare_image_inputs() _lowerCamelCase : Optional[Any] = processor(text=__lowerCAmelCase , images=__lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__lowerCAmelCase ): processor() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Optional[int] = self.get_image_processor() _lowerCamelCase : List[str] = self.get_tokenizer() _lowerCamelCase : Dict = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _lowerCamelCase : str = self.prepare_image_inputs() _lowerCamelCase : Any = self.prepare_image_inputs() _lowerCamelCase : str = processor(images=__lowerCAmelCase , visual_prompt=__lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''conditional_pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(__lowerCAmelCase ): processor() def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" _lowerCamelCase : int = self.get_image_processor() _lowerCamelCase : Union[str, Any] = self.get_tokenizer() _lowerCamelCase : List[str] = CLIPSegProcessor(tokenizer=__lowerCAmelCase , image_processor=__lowerCAmelCase ) _lowerCamelCase : Any = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _lowerCamelCase : Optional[Any] = processor.batch_decode(__lowerCAmelCase ) _lowerCamelCase : Any = tokenizer.batch_decode(__lowerCAmelCase ) self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
72
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase = logging.get_logger(__name__) _lowercase = { '''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 lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: str = '''dpr''' def __init__( self : Optional[int] ,A_ : Optional[int]=3_0522 ,A_ : Dict=768 ,A_ : str=12 ,A_ : List[Any]=12 ,A_ : str=3072 ,A_ : Tuple="gelu" ,A_ : Dict=0.1 ,A_ : Optional[Any]=0.1 ,A_ : Dict=512 ,A_ : Dict=2 ,A_ : List[Any]=0.02 ,A_ : List[str]=1e-12 ,A_ : str=0 ,A_ : Dict="absolute" ,A_ : int = 0 ,**A_ : Union[str, Any] ,) -> Dict: super().__init__(pad_token_id=A_ ,**A_ ) A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = hidden_act A = intermediate_size A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = initializer_range A = layer_norm_eps A = projection_dim A = position_embedding_type
74
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
'''simple docstring''' import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig a_ : Tuple = logging.get_logger(__name__) class __UpperCamelCase : def __init__( self, lowerCAmelCase, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =question_encoder lowerCamelCase_ =generator lowerCamelCase_ =self.question_encoder def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" if os.path.isfile(lowerCAmelCase ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(lowerCAmelCase, exist_ok=lowerCAmelCase ) lowerCamelCase_ =os.path.join(lowerCAmelCase, '''question_encoder_tokenizer''' ) lowerCamelCase_ =os.path.join(lowerCAmelCase, '''generator_tokenizer''' ) self.question_encoder.save_pretrained(lowerCAmelCase ) self.generator.save_pretrained(lowerCAmelCase ) @classmethod def lowercase__ ( cls, lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer lowerCamelCase_ =kwargs.pop('''config''', lowerCAmelCase ) if config is None: lowerCamelCase_ =RagConfig.from_pretrained(lowerCAmelCase ) lowerCamelCase_ =AutoTokenizer.from_pretrained( lowerCAmelCase, config=config.question_encoder, subfolder='''question_encoder_tokenizer''' ) lowerCamelCase_ =AutoTokenizer.from_pretrained( lowerCAmelCase, config=config.generator, subfolder='''generator_tokenizer''' ) return cls(question_encoder=lowerCAmelCase, generator=lowerCAmelCase ) def __call__( self, *lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" return self.current_tokenizer(*lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, *lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" return self.generator.batch_decode(*lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self, *lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" return self.generator.decode(*lowerCAmelCase, **lowerCAmelCase ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.question_encoder def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ =self.generator def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = None, lowerCAmelCase = "longest", lowerCAmelCase = None, lowerCAmelCase = True, **lowerCAmelCase, ): """simple docstring""" warnings.warn( '''`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the ''' '''regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` ''' '''context manager to prepare your targets. See the documentation of your specific tokenizer for more ''' '''details''', lowerCAmelCase, ) if max_length is None: lowerCamelCase_ =self.current_tokenizer.model_max_length lowerCamelCase_ =self( lowerCAmelCase, add_special_tokens=lowerCAmelCase, return_tensors=lowerCAmelCase, max_length=lowerCAmelCase, padding=lowerCAmelCase, truncation=lowerCAmelCase, **lowerCAmelCase, ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: lowerCamelCase_ =self.current_tokenizer.model_max_length lowerCamelCase_ =self( text_target=lowerCAmelCase, add_special_tokens=lowerCAmelCase, return_tensors=lowerCAmelCase, padding=lowerCAmelCase, max_length=lowerCAmelCase, truncation=lowerCAmelCase, **lowerCAmelCase, ) lowerCamelCase_ =labels['''input_ids'''] return model_inputs
75
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class _UpperCamelCase ( __A , __A ): '''simple docstring''' lowerCamelCase__ =1 @register_to_config def __init__( self : Dict , a : int = 1000 , a : Optional[Union[np.ndarray, List[float]]] = None ) -> Any: """simple docstring""" self.set_timesteps(a ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE : int = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE : str = 4 # running values SCREAMING_SNAKE_CASE : Optional[int] = [] def __UpperCamelCase ( self : Tuple , a : int , a : Union[str, torch.device] = None ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = num_inference_steps SCREAMING_SNAKE_CASE : Tuple = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE : Dict = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE : Tuple = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE : Any = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE : List[Any] = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE : Optional[Any] = timesteps.to(a ) SCREAMING_SNAKE_CASE : str = [] def __UpperCamelCase ( self : int , a : torch.FloatTensor , a : int , a : torch.FloatTensor , a : bool = True , ) -> Union[SchedulerOutput, Tuple]: """simple docstring""" if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) SCREAMING_SNAKE_CASE : Dict = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE : Tuple = timestep_index + 1 SCREAMING_SNAKE_CASE : Union[str, Any] = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(a ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE : List[Any] = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE : Tuple = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE : int = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE : Optional[int] = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE : List[str] = self._get_prev_sample(a , a , a , a ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=a ) def __UpperCamelCase ( self : Optional[int] , a : torch.FloatTensor , *a : Union[str, Any] , **a : Union[str, Any] ) -> torch.FloatTensor: """simple docstring""" return sample def __UpperCamelCase ( self : List[Any] , a : str , a : Tuple , a : Any , a : Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.alphas[timestep_index] SCREAMING_SNAKE_CASE : Any = self.betas[timestep_index] SCREAMING_SNAKE_CASE : str = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE : str = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE : List[Any] = (sample - sigma * ets) / max(a , 1e-8 ) SCREAMING_SNAKE_CASE : Optional[int] = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return self.config.num_train_timesteps
76
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
"""simple docstring""" _UpperCamelCase : Any = range(2, 20 + 1) _UpperCamelCase : List[str] = [10**k for k in range(ks[-1] + 1)] _UpperCamelCase : dict[int, dict[int, list[list[int]]]] = {} def a_ ( _lowerCAmelCase : int , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[str] , _lowerCAmelCase : Any ): '''simple docstring''' lowercase__ : Dict = sum(a_i[j] for j in range(_lowerCAmelCase , len(_lowerCAmelCase ) ) ) lowercase__ : int = sum(a_i[j] * base[j] for j in range(min(len(_lowerCAmelCase ) , _lowerCAmelCase ) ) ) lowercase__ , lowercase__ : List[Any] = 0, 0 lowercase__ : Optional[Any] = n - i lowercase__ : Optional[Any] = memo.get(_lowerCAmelCase ) if sub_memo is not None: lowercase__ : str = sub_memo.get(_lowerCAmelCase ) if jumps is not None and len(_lowerCAmelCase ) > 0: # find and make the largest jump without going over lowercase__ : Dict = -1 for _k in range(len(_lowerCAmelCase ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: lowercase__ : Union[str, Any] = _k break if max_jump >= 0: lowercase__ , lowercase__ , lowercase__ : Optional[Any] = jumps[max_jump] # since the difference between jumps is cached, add c lowercase__ : Any = diff + c for j in range(min(_lowerCAmelCase , len(_lowerCAmelCase ) ) ): lowercase__ , lowercase__ : Any = divmod(_lowerCAmelCase , 10 ) if new_c > 0: add(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) else: lowercase__ : Union[str, Any] = [] else: lowercase__ : Optional[int] = {c: []} lowercase__ : int = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps lowercase__ , lowercase__ : Optional[int] = next_term(_lowerCAmelCase , k - 1 , i + dn , _lowerCAmelCase ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead lowercase__ , lowercase__ : Optional[int] = compute(_lowerCAmelCase , _lowerCAmelCase , i + dn , _lowerCAmelCase ) diff += _diff dn += terms_jumped lowercase__ : List[str] = sub_memo[c] # keep jumps sorted by # of terms skipped lowercase__ : str = 0 while j < len(_lowerCAmelCase ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(_lowerCAmelCase , (diff, dn, k) ) return (diff, dn) def a_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : Tuple , _lowerCAmelCase : Tuple , _lowerCAmelCase : Union[str, Any] ): '''simple docstring''' if i >= n: return 0, i if k > len(_lowerCAmelCase ): a_i.extend([0 for _ in range(k - len(_lowerCAmelCase ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) lowercase__ : Tuple = i lowercase__ , lowercase__ , lowercase__ : Tuple = 0, 0, 0 for j in range(len(_lowerCAmelCase ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 lowercase__ : Optional[int] = ds_c + ds_b diff += addend lowercase__ : int = 0 for j in range(_lowerCAmelCase ): lowercase__ : Tuple = a_i[j] + addend lowercase__ , lowercase__ : List[str] = divmod(_lowerCAmelCase , 10 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) return diff, i - start_i def a_ ( _lowerCAmelCase : str , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' for j in range(_lowerCAmelCase , len(_lowerCAmelCase ) ): lowercase__ : int = digits[j] + addend if s >= 10: lowercase__ , lowercase__ : Dict = divmod(_lowerCAmelCase , 10 ) lowercase__ : str = addend // 10 + quotient else: lowercase__ : int = s lowercase__ : Optional[Any] = addend // 10 if addend == 0: break while addend > 0: lowercase__ , lowercase__ : str = divmod(_lowerCAmelCase , 10 ) digits.append(_lowerCAmelCase ) def a_ ( _lowerCAmelCase : int = 10**15 ): '''simple docstring''' lowercase__ : int = [1] lowercase__ : Tuple = 1 lowercase__ : int = 0 while True: lowercase__ , lowercase__ : Dict = next_term(_lowerCAmelCase , 20 , i + dn , _lowerCAmelCase ) dn += terms_jumped if dn == n - i: break lowercase__ : List[Any] = 0 for j in range(len(_lowerCAmelCase ) ): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
77
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
"""simple docstring""" import random class A_ : """simple docstring""" @staticmethod def UpperCAmelCase__ ( lowercase_ :str ) -> tuple[list[int], list[int]]: UpperCAmelCase = [ord(lowercase_ ) for i in text] UpperCAmelCase = [] UpperCAmelCase = [] for i in plain: UpperCAmelCase = random.randint(1 , 3_00 ) UpperCAmelCase = (i + k) * k cipher.append(lowercase_ ) key.append(lowercase_ ) return cipher, key @staticmethod def UpperCAmelCase__ ( lowercase_ :list[int] , lowercase_ :list[int] ) -> str: UpperCAmelCase = [] for i in range(len(lowercase_ ) ): UpperCAmelCase = int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(lowercase_ ) ) return "".join(lowercase_ ) if __name__ == "__main__": snake_case_ , snake_case_ = Onepad().encrypt("""Hello""") print(c, k) print(Onepad().decrypt(c, k))
78
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') lowerCamelCase_ = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowerCamelCase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'''} , ) snake_case = field(default=snake_case_ , metadata={'''help''': '''A folder containing the training data.'''} ) snake_case = field(default=snake_case_ , metadata={'''help''': '''A folder containing the validation data.'''} ) snake_case = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) snake_case = field(default=32 , metadata={'''help''': '''The size of the square patches to use for masking.'''} ) snake_case = field( default=0.6 , metadata={'''help''': '''Percentage of patches to mask.'''} , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def lowerCAmelCase ( self : Any ): '''simple docstring''' _A = {} if self.train_dir is not None: _A = self.train_dir if self.validation_dir is not None: _A = self.validation_dir _A = data_files if data_files else None @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ''' '''checkpoint identifier on the hub. ''' '''Don\'t set if you want to train a model from scratch.''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'''} , ) snake_case = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) snake_case = field(default=snake_case_ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The size (resolution) of each image. If not specified, will use `image_size` of the configuration.''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Stride to use for the encoder.'''} , ) class _UpperCAmelCase : """simple docstring""" def __init__( self : Tuple , __UpperCAmelCase : Optional[int]=192 , __UpperCAmelCase : Dict=32 , __UpperCAmelCase : int=4 , __UpperCAmelCase : int=0.6 ): '''simple docstring''' _A = input_size _A = mask_patch_size _A = model_patch_size _A = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError("Input size must be divisible by mask patch size" ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError("Mask patch size must be divisible by model patch size" ) _A = self.input_size // self.mask_patch_size _A = self.mask_patch_size // self.model_patch_size _A = self.rand_size**2 _A = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : Any ): '''simple docstring''' _A = np.random.permutation(self.token_count )[: self.mask_count] _A = np.zeros(self.token_count , dtype=__UpperCAmelCase ) _A = 1 _A = mask.reshape((self.rand_size, self.rand_size) ) _A = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def __lowercase ( __lowercase ) -> str: '''simple docstring''' _A = torch.stack([example["pixel_values"] for example in examples] ) _A = torch.stack([example["mask"] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def __lowercase ( ) -> Dict: '''simple docstring''' _A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _A , _A , _A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _A , _A , _A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_mim" , __lowercase , __lowercase ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _A = training_args.get_process_log_level() logger.setLevel(__lowercase ) transformers.utils.logging.set_verbosity(__lowercase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset. _A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _A = None if "validation" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __lowercase ) and data_args.train_val_split > 0.0: _A = ds["train"].train_test_split(data_args.train_val_split ) _A = split["train"] _A = split["test"] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _A = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name_or_path: _A = AutoConfig.from_pretrained(model_args.config_name_or_path , **__lowercase ) elif model_args.model_name_or_path: _A = AutoConfig.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: _A = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(F'''New config: {config}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(__lowercase , "decoder_type" ): _A = "simmim" # adapt config _A = model_args.image_size if model_args.image_size is not None else config.image_size _A = model_args.patch_size if model_args.patch_size is not None else config.patch_size _A = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { "image_size": model_args.image_size, "patch_size": model_args.patch_size, "encoder_stride": model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: _A = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **__lowercase ) elif model_args.model_name_or_path: _A = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: _A = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } _A = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: _A = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) _A = AutoModelForMaskedImageModeling.from_config(__lowercase ) if training_args.do_train: _A = ds["train"].column_names else: _A = ds["validation"].column_names if data_args.image_column_name is not None: _A = data_args.image_column_name elif "image" in column_names: _A = "image" elif "img" in column_names: _A = "img" else: _A = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py _A = Compose( [ Lambda(lambda __lowercase : img.convert("RGB" ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator _A = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(__lowercase ): _A = [transforms(__lowercase ) for image in examples[image_column_name]] _A = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError("--do_train requires a train dataset" ) if data_args.max_train_samples is not None: _A = ds["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__lowercase ) if training_args.do_eval: if "validation" not in ds: raise ValueError("--do_eval requires a validation dataset" ) if data_args.max_eval_samples is not None: _A = ( ds["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__lowercase ) # Initialize our trainer _A = Trainer( model=__lowercase , args=__lowercase , train_dataset=ds["train"] if training_args.do_train else None , eval_dataset=ds["validation"] if training_args.do_eval else None , tokenizer=__lowercase , data_collator=__lowercase , ) # Training if training_args.do_train: _A = None if training_args.resume_from_checkpoint is not None: _A = training_args.resume_from_checkpoint elif last_checkpoint is not None: _A = last_checkpoint _A = trainer.train(resume_from_checkpoint=__lowercase ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _A = trainer.evaluate() trainer.log_metrics("eval" , __lowercase ) trainer.save_metrics("eval" , __lowercase ) # Write model card and (optionally) push to hub _A = { "finetuned_from": model_args.model_name_or_path, "tasks": "masked-image-modeling", "dataset": data_args.dataset_name, "tags": ["masked-image-modeling"], } if training_args.push_to_hub: trainer.push_to_hub(**__lowercase ) else: trainer.create_model_card(**__lowercase ) if __name__ == "__main__": main()
79
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def _UpperCamelCase ( __A ) -> Dict: # picklable for multiprocessing '''simple docstring''' return x.sum() def _UpperCamelCase ( __A ) -> int: # picklable for multiprocessing '''simple docstring''' return i + 1 @dataclass class lowercase_ : __UpperCAmelCase = 42 __UpperCAmelCase = 42 class lowercase_ ( a__ ): def __a ( self ): UpperCamelCase__ = {} UpperCamelCase__ = [] UpperCamelCase__ = 1 UpperCamelCase__ = [1, 2] UpperCamelCase__ = {"a": 1, "b": 2} UpperCamelCase__ = {"a": [1, 2], "b": [3, 4]} UpperCamelCase__ = {"a": {"1": 1}, "b": 2} UpperCamelCase__ = {"a": 1, "b": 2, "c": 3, "d": 4} UpperCamelCase__ = {} UpperCamelCase__ = [] UpperCamelCase__ = 2 UpperCamelCase__ = [2, 3] UpperCamelCase__ = {"a": 2, "b": 3} UpperCamelCase__ = {"a": [2, 3], "b": [4, 5]} UpperCamelCase__ = {"a": {"1": 2}, "b": 3} UpperCamelCase__ = {"a": 2, "b": 3, "c": 4, "d": 5} self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) self.assertEqual(map_nested(a , a ) , a ) UpperCamelCase__ = 2 self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) self.assertEqual(map_nested(a , a , num_proc=a ) , a ) UpperCamelCase__ = {"a": np.eye(2 ), "b": np.zeros(3 ), "c": np.ones(2 )} UpperCamelCase__ = {"a": 2, "b": 0, "c": 2} UpperCamelCase__ = { "a": np.eye(2 ).astype(a ), "b": np.zeros(3 ).astype(a ), "c": np.ones(2 ).astype(a ), } self.assertEqual(map_nested(a , a , map_numpy=a ) , a ) self.assertEqual( {k: v.tolist() for k, v in map_nested(a , a , map_numpy=a ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(a , a , map_numpy=a , num_proc=a ) , a ) self.assertEqual( {k: v.tolist() for k, v in map_nested(a , a , map_numpy=a , num_proc=a ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(a ): # can't pickle a local lambda map_nested(lambda a : x + 1 , a , num_proc=a ) def __a ( self ): UpperCamelCase__ = {"a": 1, "b": 2} UpperCamelCase__ = {"a": 3, "b": 4} UpperCamelCase__ = {"a": 5, "b": 6} UpperCamelCase__ = sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(a , a , a ) ) , a ) def __a ( self ): class lowercase_ : __UpperCAmelCase = 'bar' UpperCamelCase__ = Foo() self.assertEqual(foo.my_attr , "bar" ) with temporary_assignment(a , "my_attr" , "BAR" ): self.assertEqual(foo.my_attr , "BAR" ) self.assertEqual(foo.my_attr , "bar" ) @pytest.mark.parametrize( "iterable_length, num_proc, expected_num_proc" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def _UpperCamelCase ( __A , __A , __A ) -> List[Any]: '''simple docstring''' with patch("datasets.utils.py_utils._single_map_nested" ) as mock_single_map_nested, patch( "datasets.parallel.parallel.Pool" ) as mock_multiprocessing_pool: UpperCamelCase__ = {F'''{i}''': i for i in range(__A )} UpperCamelCase__ = map_nested(lambda __A : x + 10 , __A , num_proc=__A , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class lowercase_ ( a__ ): @require_tf def __a ( self ): import tensorflow as tf from tensorflow.keras import layers UpperCamelCase__ = layers.Dense(2 ) def gen_random_output(): UpperCamelCase__ = tf.random.uniform((1, 3) ) return model(a ).numpy() with temp_seed(42 , set_tensorflow=a ): UpperCamelCase__ = gen_random_output() with temp_seed(42 , set_tensorflow=a ): UpperCamelCase__ = gen_random_output() UpperCamelCase__ = gen_random_output() np.testing.assert_equal(a , a ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def __a ( self ): import torch def gen_random_output(): UpperCamelCase__ = torch.nn.Linear(3 , 2 ) UpperCamelCase__ = torch.rand(1 , 3 ) return model(a ).detach().numpy() with temp_seed(42 , set_pytorch=a ): UpperCamelCase__ = gen_random_output() with temp_seed(42 , set_pytorch=a ): UpperCamelCase__ = gen_random_output() UpperCamelCase__ = gen_random_output() np.testing.assert_equal(a , a ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def __a ( self ): def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): UpperCamelCase__ = gen_random_output() with temp_seed(42 ): UpperCamelCase__ = gen_random_output() UpperCamelCase__ = gen_random_output() np.testing.assert_equal(a , a ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("input_data" , [{}] ) def _UpperCamelCase ( __A ) -> Any: '''simple docstring''' UpperCamelCase__ = NestedDataStructure(__A ).data assert output_data == input_data @pytest.mark.parametrize( "data, expected_output" , [ ({}, []), ([], []), ("foo", ["foo"]), (["foo", "bar"], ["foo", "bar"]), ([["foo", "bar"]], ["foo", "bar"]), ([[["foo"], ["bar"]]], ["foo", "bar"]), ([[["foo"], "bar"]], ["foo", "bar"]), ({"a": 1, "b": 2}, [1, 2]), ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]), ({"a": {"1": 1}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": [2]}, [1, 2]), ] , ) def _UpperCamelCase ( __A , __A ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ = NestedDataStructure(__A ).flatten() assert output == expected_output def _UpperCamelCase ( ) -> Dict: '''simple docstring''' UpperCamelCase__ = A(x=1 , y="foobar" ) UpperCamelCase__ = {"x": 1, "y": "foobar"} assert asdict(__A ) == expected_output UpperCamelCase__ = {"a": {"b": A(x=10 , y="foo" )}, "c": [A(x=20 , y="bar" )]} UpperCamelCase__ = {"a": {"b": {"x": 10, "y": "foo"}}, "c": [{"x": 20, "y": "bar"}]} assert asdict(__A ) == expected_output with pytest.raises(__A ): asdict([1, A(x=10 , y="foo" )] ) def _UpperCamelCase ( __A ) -> int: '''simple docstring''' return text.split() def _UpperCamelCase ( __A ) -> List[str]: '''simple docstring''' yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def _UpperCamelCase ( ) -> int: '''simple docstring''' with Pool(2 ) as pool: UpperCamelCase__ = list(iflatmap_unordered(__A , _split_text , kwargs_iterable=[{"text": "hello there"}] * 10 ) ) assert out.count("hello" ) == 10 assert out.count("there" ) == 10 assert len(__A ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: UpperCamelCase__ = list(iflatmap_unordered(__A , _split_text , kwargs_iterable=[{"text": "hello there"}] * 10 ) ) assert out.count("hello" ) == 10 assert out.count("there" ) == 10 assert len(__A ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: UpperCamelCase__ = [] for yield_time, content in iflatmap_unordered( __A , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"content": "a"}, {"content": "b"}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__A ) assert out.count("a" ) == 2 assert out.count("b" ) == 2 assert len(__A ) == 4
80
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowerCamelCase_ : List[str] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : int = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys lowerCamelCase_ : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
81
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging A__ = logging.get_logger(__name__) class __lowerCAmelCase : __lowerCamelCase = 42 __lowerCamelCase = None @staticmethod def snake_case ( ): """simple docstring""" raise NotImplementedError def snake_case ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): """simple docstring""" raise NotImplementedError def snake_case ( self , _snake_case ): """simple docstring""" raise NotImplementedError def snake_case ( self ): """simple docstring""" if not self.is_available(): raise RuntimeError( F'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' ) @classmethod def snake_case ( cls ): """simple docstring""" return F'`pip install {cls.pip_package or cls.name}`' class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''optuna''' @staticmethod def snake_case ( ): """simple docstring""" return is_optuna_available() def snake_case ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): """simple docstring""" return run_hp_search_optuna(_snake_case , _snake_case , _snake_case , **_snake_case ) def snake_case ( self , _snake_case ): """simple docstring""" return default_hp_space_optuna(_snake_case ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''ray''' __lowerCamelCase = '''\'ray[tune]\'''' @staticmethod def snake_case ( ): """simple docstring""" return is_ray_available() def snake_case ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): """simple docstring""" return run_hp_search_ray(_snake_case , _snake_case , _snake_case , **_snake_case ) def snake_case ( self , _snake_case ): """simple docstring""" return default_hp_space_ray(_snake_case ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''sigopt''' @staticmethod def snake_case ( ): """simple docstring""" return is_sigopt_available() def snake_case ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): """simple docstring""" return run_hp_search_sigopt(_snake_case , _snake_case , _snake_case , **_snake_case ) def snake_case ( self , _snake_case ): """simple docstring""" return default_hp_space_sigopt(_snake_case ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = '''wandb''' @staticmethod def snake_case ( ): """simple docstring""" return is_wandb_available() def snake_case ( self , _snake_case , _snake_case , _snake_case , **_snake_case ): """simple docstring""" return run_hp_search_wandb(_snake_case , _snake_case , _snake_case , **_snake_case ) def snake_case ( self , _snake_case ): """simple docstring""" return default_hp_space_wandb(_snake_case ) A__ = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(snake_case ) > 0: _lowerCAmelCase = available_backends[0].name if len(snake_case ) > 1: logger.info( F'{len(snake_case )} hyperparameter search backends available. Using {name} as the default.' ) return name raise RuntimeError( """No hyperparameter search backend available.\n""" + """\n""".join( F' - To install {backend.name} run {backend.pip_install()}' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
82
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ : Optional[Any] = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys snake_case_ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
83
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
"""simple docstring""" import argparse import collections import json import os import re import string import sys import numpy as np __UpperCAmelCase = re.compile(R'\b(a|an|the)\b', re.UNICODE) __UpperCAmelCase = None def _snake_case ( ) -> List[str]: '''simple docstring''' lowerCAmelCase_ :Optional[int] = argparse.ArgumentParser("""Official evaluation script for SQuAD version 2.0.""" ) parser.add_argument("""data_file""" , metavar="""data.json""" , help="""Input data JSON file.""" ) parser.add_argument("""pred_file""" , metavar="""pred.json""" , help="""Model predictions.""" ) parser.add_argument( """--out-file""" , """-o""" , metavar="""eval.json""" , help="""Write accuracy metrics to file (default is stdout).""" ) parser.add_argument( """--na-prob-file""" , """-n""" , metavar="""na_prob.json""" , help="""Model estimates of probability of no answer.""" ) parser.add_argument( """--na-prob-thresh""" , """-t""" , type=lowercase__ , default=1.0 , help="""Predict \"\" if no-answer probability exceeds this (default = 1.0).""" , ) parser.add_argument( """--out-image-dir""" , """-p""" , metavar="""out_images""" , default=lowercase__ , help="""Save precision-recall curves to directory.""" ) parser.add_argument("""--verbose""" , """-v""" , action="""store_true""" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def _snake_case ( lowercase__ : int ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ :Tuple = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase_ :Any = bool(qa["""answers"""]["""text"""] ) return qid_to_has_ans def _snake_case ( lowercase__ : Optional[Any] ) -> Any: '''simple docstring''' def remove_articles(lowercase__ : int ): return ARTICLES_REGEX.sub(""" """ , lowercase__ ) def white_space_fix(lowercase__ : List[str] ): return " ".join(text.split() ) def remove_punc(lowercase__ : Union[str, Any] ): lowerCAmelCase_ :List[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase__ : List[str] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase__ ) ) ) ) def _snake_case ( lowercase__ : Optional[Any] ) -> Dict: '''simple docstring''' if not s: return [] return normalize_answer(lowercase__ ).split() def _snake_case ( lowercase__ : Any , lowercase__ : Any ) -> Optional[int]: '''simple docstring''' return int(normalize_answer(lowercase__ ) == normalize_answer(lowercase__ ) ) def _snake_case ( lowercase__ : List[str] , lowercase__ : int ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ :Any = get_tokens(lowercase__ ) lowerCAmelCase_ :str = get_tokens(lowercase__ ) lowerCAmelCase_ :Optional[Any] = collections.Counter(lowercase__ ) & collections.Counter(lowercase__ ) lowerCAmelCase_ :Optional[int] = sum(common.values() ) if len(lowercase__ ) == 0 or len(lowercase__ ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 lowerCAmelCase_ :Dict = 1.0 * num_same / len(lowercase__ ) lowerCAmelCase_ :str = 1.0 * num_same / len(lowercase__ ) lowerCAmelCase_ :List[Any] = (2 * precision * recall) / (precision + recall) return fa def _snake_case ( lowercase__ : Tuple , lowercase__ : str ) -> Optional[int]: '''simple docstring''' lowerCAmelCase_ :int = {} lowerCAmelCase_ :Dict = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: lowerCAmelCase_ :Tuple = qa["""id"""] lowerCAmelCase_ :Union[str, Any] = [t for t in qa["""answers"""]["""text"""] if normalize_answer(lowercase__ )] if not gold_answers: # For unanswerable questions, only correct answer is empty string lowerCAmelCase_ :Any = [""""""] if qid not in preds: print(f"""Missing prediction for {qid}""" ) continue lowerCAmelCase_ :List[str] = preds[qid] # Take max over all gold answers lowerCAmelCase_ :Any = max(compute_exact(lowercase__ , lowercase__ ) for a in gold_answers ) lowerCAmelCase_ :List[str] = max(compute_fa(lowercase__ , lowercase__ ) for a in gold_answers ) return exact_scores, fa_scores def _snake_case ( lowercase__ : Any , lowercase__ : Dict , lowercase__ : Tuple , lowercase__ : List[str] ) -> Optional[Any]: '''simple docstring''' lowerCAmelCase_ :Any = {} for qid, s in scores.items(): lowerCAmelCase_ :str = na_probs[qid] > na_prob_thresh if pred_na: lowerCAmelCase_ :List[str] = float(not qid_to_has_ans[qid] ) else: lowerCAmelCase_ :Optional[Any] = s return new_scores def _snake_case ( lowercase__ : List[str] , lowercase__ : Dict , lowercase__ : str=None ) -> Dict: '''simple docstring''' if not qid_list: lowerCAmelCase_ :Dict = len(lowercase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores.values() ) / total), ("""f1""", 100.0 * sum(fa_scores.values() ) / total), ("""total""", total), ] ) else: lowerCAmelCase_ :int = len(lowercase__ ) return collections.OrderedDict( [ ("""exact""", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("""f1""", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("""total""", total), ] ) def _snake_case ( lowercase__ : Dict , lowercase__ : List[Any] , lowercase__ : List[str] ) -> Tuple: '''simple docstring''' for k in new_eval: lowerCAmelCase_ :int = new_eval[k] def _snake_case ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : str , lowercase__ : str ) -> Dict: '''simple docstring''' plt.step(lowercase__ , lowercase__ , color="""b""" , alpha=0.2 , where="""post""" ) plt.fill_between(lowercase__ , lowercase__ , step="""post""" , alpha=0.2 , color="""b""" ) plt.xlabel("""Recall""" ) plt.ylabel("""Precision""" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(lowercase__ ) plt.savefig(lowercase__ ) plt.clf() def _snake_case ( lowercase__ : int , lowercase__ : int , lowercase__ : Tuple , lowercase__ : List[str] , lowercase__ : Union[str, Any]=None , lowercase__ : List[Any]=None ) -> int: '''simple docstring''' lowerCAmelCase_ :int = sorted(lowercase__ , key=lambda lowercase__ : na_probs[k] ) lowerCAmelCase_ :Tuple = 0.0 lowerCAmelCase_ :List[str] = 1.0 lowerCAmelCase_ :Optional[Any] = 0.0 lowerCAmelCase_ :List[str] = [1.0] lowerCAmelCase_ :Dict = [0.0] lowerCAmelCase_ :str = 0.0 for i, qid in enumerate(lowercase__ ): if qid_to_has_ans[qid]: true_pos += scores[qid] lowerCAmelCase_ :List[Any] = true_pos / float(i + 1 ) lowerCAmelCase_ :List[Any] = true_pos / float(lowercase__ ) if i == len(lowercase__ ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(lowercase__ ) recalls.append(lowercase__ ) if out_image: plot_pr_curve(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return {"ap": 100.0 * avg_prec} def _snake_case ( lowercase__ : str , lowercase__ : Tuple , lowercase__ : int , lowercase__ : Any , lowercase__ : str , lowercase__ : int ) -> Union[str, Any]: '''simple docstring''' if out_image_dir and not os.path.exists(lowercase__ ): os.makedirs(lowercase__ ) lowerCAmelCase_ :Dict = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return lowerCAmelCase_ :Optional[int] = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_exact.png""" ) , title="""Precision-Recall curve for Exact Match score""" , ) lowerCAmelCase_ :int = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_f1.png""" ) , title="""Precision-Recall curve for F1 score""" , ) lowerCAmelCase_ :List[str] = {k: float(lowercase__ ) for k, v in qid_to_has_ans.items()} lowerCAmelCase_ :str = make_precision_recall_eval( lowercase__ , lowercase__ , lowercase__ , lowercase__ , out_image=os.path.join(lowercase__ , """pr_oracle.png""" ) , title="""Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)""" , ) merge_eval(lowercase__ , lowercase__ , """pr_exact""" ) merge_eval(lowercase__ , lowercase__ , """pr_f1""" ) merge_eval(lowercase__ , lowercase__ , """pr_oracle""" ) def _snake_case ( lowercase__ : Tuple , lowercase__ : List[Any] , lowercase__ : Dict , lowercase__ : int ) -> List[Any]: '''simple docstring''' if not qid_list: return lowerCAmelCase_ :str = [na_probs[k] for k in qid_list] lowerCAmelCase_ :Tuple = np.ones_like(lowercase__ ) / float(len(lowercase__ ) ) plt.hist(lowercase__ , weights=lowercase__ , bins=2_0 , range=(0.0, 1.0) ) plt.xlabel("""Model probability of no-answer""" ) plt.ylabel("""Proportion of dataset""" ) plt.title(f"""Histogram of no-answer probability: {name}""" ) plt.savefig(os.path.join(lowercase__ , f"""na_prob_hist_{name}.png""" ) ) plt.clf() def _snake_case ( lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase_ :int = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) lowerCAmelCase_ :List[Any] = num_no_ans lowerCAmelCase_ :int = cur_score lowerCAmelCase_ :Optional[Any] = 0.0 lowerCAmelCase_ :Union[str, Any] = sorted(lowercase__ , key=lambda lowercase__ : na_probs[k] ) for i, qid in enumerate(lowercase__ ): if qid not in scores: continue if qid_to_has_ans[qid]: lowerCAmelCase_ :Optional[int] = scores[qid] else: if preds[qid]: lowerCAmelCase_ :Optional[int] = -1 else: lowerCAmelCase_ :Union[str, Any] = 0 cur_score += diff if cur_score > best_score: lowerCAmelCase_ :Dict = cur_score lowerCAmelCase_ :Tuple = na_probs[qid] return 100.0 * best_score / len(lowercase__ ), best_thresh def _snake_case ( lowercase__ : Dict , lowercase__ : List[str] , lowercase__ : Optional[int] , lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : Union[str, Any] ) -> List[Any]: '''simple docstring''' lowerCAmelCase_ , lowerCAmelCase_ :Any = find_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) lowerCAmelCase_ , lowerCAmelCase_ :Union[str, Any] = find_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) lowerCAmelCase_ :Optional[Any] = best_exact lowerCAmelCase_ :List[Any] = exact_thresh lowerCAmelCase_ :Tuple = best_fa lowerCAmelCase_ :str = fa_thresh def _snake_case ( ) -> Any: '''simple docstring''' with open(OPTS.data_file ) as f: lowerCAmelCase_ :Union[str, Any] = json.load(lowercase__ ) lowerCAmelCase_ :Optional[Any] = dataset_json["""data"""] with open(OPTS.pred_file ) as f: lowerCAmelCase_ :Dict = json.load(lowercase__ ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: lowerCAmelCase_ :Tuple = json.load(lowercase__ ) else: lowerCAmelCase_ :str = {k: 0.0 for k in preds} lowerCAmelCase_ :List[str] = make_qid_to_has_ans(lowercase__ ) # maps qid to True/False lowerCAmelCase_ :List[str] = [k for k, v in qid_to_has_ans.items() if v] lowerCAmelCase_ :int = [k for k, v in qid_to_has_ans.items() if not v] lowerCAmelCase_ , lowerCAmelCase_ :str = get_raw_scores(lowercase__ , lowercase__ ) lowerCAmelCase_ :Optional[Any] = apply_no_ans_threshold(lowercase__ , lowercase__ , lowercase__ , OPTS.na_prob_thresh ) lowerCAmelCase_ :Union[str, Any] = apply_no_ans_threshold(lowercase__ , lowercase__ , lowercase__ , OPTS.na_prob_thresh ) lowerCAmelCase_ :Any = make_eval_dict(lowercase__ , lowercase__ ) if has_ans_qids: lowerCAmelCase_ :Dict = make_eval_dict(lowercase__ , lowercase__ , qid_list=lowercase__ ) merge_eval(lowercase__ , lowercase__ , """HasAns""" ) if no_ans_qids: lowerCAmelCase_ :List[Any] = make_eval_dict(lowercase__ , lowercase__ , qid_list=lowercase__ ) merge_eval(lowercase__ , lowercase__ , """NoAns""" ) if OPTS.na_prob_file: find_all_best_thresh(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , OPTS.out_image_dir ) histogram_na_prob(lowercase__ , lowercase__ , OPTS.out_image_dir , """hasAns""" ) histogram_na_prob(lowercase__ , lowercase__ , OPTS.out_image_dir , """noAns""" ) if OPTS.out_file: with open(OPTS.out_file , """w""" ) as f: json.dump(lowercase__ , lowercase__ ) else: print(json.dumps(lowercase__ , indent=2 ) ) if __name__ == "__main__": __UpperCAmelCase = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt main()
84
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features _SCREAMING_SNAKE_CASE : Tuple = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : List[str] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) _SCREAMING_SNAKE_CASE : Tuple = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _snake_case : lowerCAmelCase_ : str = field( default=lowercase_ , metadata={"help": "Model type selected in the list: " + ", ".join(lowercase_ )} ) lowerCAmelCase_ : str = field( default=lowercase_ , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) lowerCAmelCase_ : 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." ) } , ) lowerCAmelCase_ : int = field( default=128 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) lowerCAmelCase_ : int = field( default=64 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) lowerCAmelCase_ : int = field( default=30 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) lowerCAmelCase_ : bool = field( default=lowercase_ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) lowerCAmelCase_ : bool = field( default=lowercase_ , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) lowerCAmelCase_ : float = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCAmelCase_ : int = field( default=20 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCAmelCase_ : int = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) lowerCAmelCase_ : int = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class _snake_case ( lowercase_ ): lowerCAmelCase_ : int = "train" lowerCAmelCase_ : Tuple = "dev" class _snake_case ( lowercase_ ): lowerCAmelCase_ : SquadDataTrainingArguments lowerCAmelCase_ : List[SquadFeatures] lowerCAmelCase_ : Split lowerCAmelCase_ : bool def __init__( self , a__ , a__ , a__ = None , a__ = Split.train , a__ = False , a__ = None , a__ = "pt" , ) -> Any: '''simple docstring''' snake_case_ = args snake_case_ = is_language_sensitive snake_case_ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(a__ , a__ ): try: snake_case_ = Split[mode] except KeyError: raise KeyError("mode is not a valid split name" ) snake_case_ = mode # Load data features from cache or dataset file snake_case_ = "v2" if args.version_2_with_negative else "v1" snake_case_ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}' , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. snake_case_ = cached_features_file + ".lock" with FileLock(a__ ): if os.path.exists(a__ ) and not args.overwrite_cache: snake_case_ = time.time() snake_case_ = torch.load(a__ ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. snake_case_ = self.old_features["features"] snake_case_ = self.old_features.get("dataset" , a__ ) snake_case_ = self.old_features.get("examples" , a__ ) logger.info( F'Loading features from cached file {cached_features_file} [took %.3f s]' , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in' " future run" ) else: if mode == Split.dev: snake_case_ = self.processor.get_dev_examples(args.data_dir ) else: snake_case_ = self.processor.get_train_examples(args.data_dir ) snake_case_ , snake_case_ = squad_convert_examples_to_features( examples=self.examples , tokenizer=a__ , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=a__ , ) snake_case_ = time.time() torch.save( {"features": self.features, "dataset": self.dataset, "examples": self.examples} , a__ , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]' ) def __len__( self ) -> str: '''simple docstring''' return len(self.features ) def __getitem__( self , a__ ) -> Dict[str, torch.Tensor]: '''simple docstring''' snake_case_ = self.features[i] snake_case_ = torch.tensor(feature.input_ids , dtype=torch.long ) snake_case_ = torch.tensor(feature.attention_mask , dtype=torch.long ) snake_case_ = torch.tensor(feature.token_type_ids , dtype=torch.long ) snake_case_ = torch.tensor(feature.cls_index , dtype=torch.long ) snake_case_ = torch.tensor(feature.p_mask , dtype=torch.float ) snake_case_ = torch.tensor(feature.is_impossible , dtype=torch.float ) snake_case_ = { "input_ids": input_ids, "attention_mask": attention_mask, "token_type_ids": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"cls_index": cls_index, "p_mask": p_mask} ) if self.args.version_2_with_negative: inputs.update({"is_impossible": is_impossible} ) if self.is_language_sensitive: inputs.update({"langs": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: snake_case_ = torch.tensor(feature.start_position , dtype=torch.long ) snake_case_ = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"start_positions": start_positions, "end_positions": end_positions} ) return inputs
85
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
"""simple docstring""" import os from pathlib import Path def __lowerCAmelCase (): from torch.utils.cpp_extension import load __lowerCAmelCase : Dict = Path(_UpperCamelCase ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' __lowerCAmelCase : int = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , _UpperCamelCase , with_cuda=_UpperCamelCase , extra_include_paths=[str(_UpperCamelCase )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
86
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowercase_ ( _lowerCamelCase : Union[str, Any] , _lowerCamelCase : str , _lowerCamelCase : int=1024 , _lowerCamelCase : List[Any]=1024 , _lowerCamelCase : List[Any]=False , **_lowerCamelCase : Optional[int]): lowercase__ : Optional[Any] = AutoTokenizer.from_pretrained(_lowerCamelCase) lowercase__ : Optional[Any] = SeqaSeqDataset(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , type_path="train" , **_lowerCamelCase) lowercase__ : Union[str, Any] = tok.pad_token_id def get_lens(_lowerCamelCase : Optional[Any]): lowercase__ : Optional[int] = tqdm( DataLoader(_lowerCamelCase , batch_size=512 , num_workers=8 , shuffle=_lowerCamelCase , collate_fn=ds.collate_fn) , desc=str(ds.len_file) , ) lowercase__ : List[str] = [] for batch in dl: lowercase__ : Any = batch["input_ids"].ne(_lowerCamelCase).sum(1).tolist() lowercase__ : List[str] = batch["labels"].ne(_lowerCamelCase).sum(1).tolist() if consider_target: for src, tgt in zip(_lowerCamelCase , _lowerCamelCase): max_lens.append(max(_lowerCamelCase , _lowerCamelCase)) else: max_lens.extend(_lowerCamelCase) return max_lens lowercase__ : List[Any] = get_lens(_lowerCamelCase) lowercase__ : List[Any] = SeqaSeqDataset(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , type_path="val" , **_lowerCamelCase) lowercase__ : int = get_lens(_lowerCamelCase) pickle_save(_lowerCamelCase , train_ds.len_file) pickle_save(_lowerCamelCase , val_ds.len_file) if __name__ == "__main__": fire.Fire(save_len_file)
87
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int=13 , UpperCamelCase__ : Optional[int]=7 , UpperCamelCase__ : Any=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : int=99 , UpperCamelCase__ : Any=16 , UpperCamelCase__ : str=36 , UpperCamelCase__ : List[str]=6 , UpperCamelCase__ : List[str]=6 , UpperCamelCase__ : Union[str, Any]=6 , UpperCamelCase__ : int=37 , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : int=512 , UpperCamelCase__ : str=16 , UpperCamelCase__ : int=2 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : Optional[Any]=4 , UpperCamelCase__ : Dict=None , ) -> Any: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = embedding_size __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_hidden_groups __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Tuple ) -> Dict: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Any ) -> List[Any]: """simple docstring""" return AlbertConfig( 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def _lowercase ( self : int , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] ) -> Tuple: """simple docstring""" __magic_name__ = AlbertModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = AlbertForPreTraining(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , sentence_order_label=UpperCamelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple ) -> Dict: """simple docstring""" __magic_name__ = AlbertForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple ) -> List[Any]: """simple docstring""" __magic_name__ = AlbertForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int ) -> Tuple: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = AlbertForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] ) -> int: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = AlbertForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : str ) -> List[Any]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = AlbertForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : int ) -> Optional[int]: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": AlbertModel, """fill-mask""": AlbertForMaskedLM, """question-answering""": AlbertForQuestionAnswering, """text-classification""": AlbertForSequenceClassification, """token-classification""": AlbertForTokenClassification, """zero-shot""": AlbertForSequenceClassification, } if is_torch_available() else {} ) a__ = True def _lowercase ( self : str , UpperCamelCase__ : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any]=False ) -> Union[str, Any]: """simple docstring""" __magic_name__ = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if return_labels: if model_class in get_values(UpperCamelCase__ ): __magic_name__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase__ ) __magic_name__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ ) return inputs_dict def _lowercase ( self : int ) -> int: """simple docstring""" __magic_name__ = AlbertModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : Dict ) -> Dict: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase__ ) def _lowercase ( self : int ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ ) def _lowercase ( self : List[Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> Tuple: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> List[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : Tuple ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __magic_name__ = type self.model_tester.create_and_check_model(*UpperCamelCase__ ) @slow def _lowercase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ = AlbertModel.from_pretrained(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : Dict ) -> Union[str, Any]: """simple docstring""" __magic_name__ = AlbertModel.from_pretrained("""albert-base-v2""" ) __magic_name__ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __magic_name__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCamelCase__ , atol=1E-4 ) )
88
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = {'''configuration_focalnet''': ['''FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''FocalNetConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FocalNetForImageClassification''', '''FocalNetForMaskedImageModeling''', '''FocalNetBackbone''', '''FocalNetModel''', '''FocalNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_focalnet import ( FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST, FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, FocalNetPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=False , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=16 , lowerCamelCase__=2 , lowerCamelCase__=0.02 , lowerCamelCase__=3 , lowerCamelCase__=4 , lowerCamelCase__=None , ) -> Any: '''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 lowercase_ ( 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 = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self ) -> int: '''simple docstring''' return BioGptConfig( 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=lowerCamelCase__ , initializer_range=self.initializer_range , ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> int: '''simple docstring''' __lowerCamelCase = BioGptModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ ) __lowerCamelCase = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> str: '''simple docstring''' __lowerCamelCase = BioGptForCausalLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ ) -> str: '''simple docstring''' __lowerCamelCase = BioGptModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() # create attention mask __lowerCamelCase = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase__ ) __lowerCamelCase = self.seq_length // 2 __lowerCamelCase = 0 # first forward pass __lowerCamelCase , __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __lowerCamelCase = ids_tensor((1,) , lowerCamelCase__ ).item() + 1 __lowerCamelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __lowerCamelCase = random_other_next_tokens # append to next input_ids and attn_mask __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=lowerCamelCase__ )] , dim=1 , ) # get two different outputs __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ )['last_hidden_state'] __lowerCamelCase = model(lowerCamelCase__ , past_key_values=lowerCamelCase__ , attention_mask=lowerCamelCase__ )['last_hidden_state'] # select random slice __lowerCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowerCamelCase = output_from_no_past[:, -1, random_slice_idx].detach() __lowerCamelCase = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1e-3 ) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ ) -> List[Any]: '''simple docstring''' __lowerCamelCase = BioGptModel(config=lowerCamelCase__ ).to(lowerCamelCase__ ).eval() __lowerCamelCase = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase__ ) # first forward pass __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , use_cache=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase = outputs.to_tuple() # 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) , 2 ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ )['last_hidden_state'] __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , past_key_values=lowerCamelCase__ )[ 'last_hidden_state' ] # 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(lowerCamelCase__ , lowerCamelCase__ , atol=1e-3 ) ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ , lowerCamelCase__=False ) -> Union[str, Any]: '''simple docstring''' __lowerCamelCase = BioGptForCausalLM(lowerCamelCase__ ) model.to(lowerCamelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __lowerCamelCase = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def lowercase_ ( self , lowerCamelCase__ , *lowerCamelCase__ ) -> List[Any]: '''simple docstring''' __lowerCamelCase = BioGptModel(lowerCamelCase__ ) __lowerCamelCase = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_01 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def lowercase_ ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , *lowerCamelCase__ ) -> Tuple: '''simple docstring''' __lowerCamelCase = self.num_labels __lowerCamelCase = BioGptForTokenClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ ( self ) -> str: '''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 __lowerCAmelCase ( __magic_name__ , __magic_name__ , __magic_name__ , unittest.TestCase ): """simple docstring""" snake_case_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case_ = (BioGptForCausalLM,) if is_torch_available() else () snake_case_ = ( { '''feature-extraction''': BioGptModel, '''text-classification''': BioGptForSequenceClassification, '''text-generation''': BioGptForCausalLM, '''token-classification''': BioGptForTokenClassification, '''zero-shot''': BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case_ = False def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = BioGptModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=37 ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self ) -> Any: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def lowercase_ ( self ) -> 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(*lowerCamelCase__ ) def lowercase_ ( self ) -> Optional[Any]: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCamelCase__ ) def lowercase_ ( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*lowerCamelCase__ , gradient_checkpointing=lowerCamelCase__ ) def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCamelCase__ ) def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCamelCase__ ) def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCamelCase__ ) @slow def lowercase_ ( self ) -> Tuple: '''simple docstring''' __lowerCamelCase = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(lowerCamelCase__ ) __lowerCamelCase = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __lowerCamelCase = 'left' # Define PAD Token = EOS Token = 50256 __lowerCamelCase = tokenizer.eos_token __lowerCamelCase = model.config.eos_token_id # use different length sentences to test batching __lowerCamelCase = [ 'Hello, my dog is a little', 'Today, I', ] __lowerCamelCase = tokenizer(lowerCamelCase__ , return_tensors='pt' , padding=lowerCamelCase__ ) __lowerCamelCase = inputs['input_ids'].to(lowerCamelCase__ ) __lowerCamelCase = model.generate( input_ids=lowerCamelCase__ , attention_mask=inputs['attention_mask'].to(lowerCamelCase__ ) , ) __lowerCamelCase = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(lowerCamelCase__ ) __lowerCamelCase = model.generate(input_ids=lowerCamelCase__ ) __lowerCamelCase = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() __lowerCamelCase = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(lowerCamelCase__ ) __lowerCamelCase = model.generate(input_ids=lowerCamelCase__ , max_length=model.config.max_length - num_paddings ) __lowerCamelCase = tokenizer.batch_decode(lowerCamelCase__ , skip_special_tokens=lowerCamelCase__ ) __lowerCamelCase = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase__ ) __lowerCamelCase = tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase__ ) __lowerCamelCase = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , [non_padded_sentence, padded_sentence] ) @slow def lowercase_ ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase = BioGptModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def lowercase_ ( self ) -> Union[str, Any]: '''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(lowerCamelCase__ ) __lowerCamelCase = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __lowerCamelCase = BioGptForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowercase_ ( self ) -> 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(lowerCamelCase__ ) __lowerCamelCase = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __lowerCamelCase = BioGptForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __lowerCamelCase = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" @slow def lowercase_ ( self ) -> str: '''simple docstring''' __lowerCamelCase = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) __lowerCamelCase = torch.tensor([[2, 4_805, 9, 656, 21]] ) __lowerCamelCase = model(lowerCamelCase__ )[0] __lowerCamelCase = 42_384 __lowerCamelCase = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , lowerCamelCase__ ) __lowerCamelCase = torch.tensor( [[[-9.52_36, -9.89_18, 10.45_57], [-11.04_69, -9.64_23, 8.10_22], [-8.86_64, -7.88_26, 5.53_25]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) ) @slow def lowercase_ ( self ) -> Optional[int]: '''simple docstring''' __lowerCamelCase = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) __lowerCamelCase = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(lowerCamelCase__ ) torch.manual_seed(0 ) __lowerCamelCase = tokenizer('COVID-19 is' , return_tensors='pt' ).to(lowerCamelCase__ ) __lowerCamelCase = model.generate( **lowerCamelCase__ , min_length=100 , max_length=1_024 , num_beams=5 , early_stopping=lowerCamelCase__ , ) __lowerCamelCase = tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase__ ) __lowerCamelCase = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ )
90
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
"""simple docstring""" def _A (__a = 1_00_00_00 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = 1 SCREAMING_SNAKE_CASE_ : Optional[int] = 1 SCREAMING_SNAKE_CASE_ : str = {1: 1} for inputa in range(2 , __a ): SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Dict = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: SCREAMING_SNAKE_CASE_ : Dict = (3 * number) + 1 counter += 1 if inputa not in counters: SCREAMING_SNAKE_CASE_ : Dict = counter if counter > pre_counter: SCREAMING_SNAKE_CASE_ : Tuple = inputa SCREAMING_SNAKE_CASE_ : Optional[int] = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
91
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict ): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) __lowerCAmelCase = torch.permute(SCREAMING_SNAKE_CASE_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(SCREAMING_SNAKE_CASE_ ): # linear layer __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) __lowerCAmelCase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) return flax_key_tuple, flax_tensor def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ): if "metadata" in layer: __lowerCAmelCase = layer.split("metadata" ) __lowerCAmelCase = "".join(split_layer[0] )[:-1] __lowerCAmelCase = [tuple(("metadata" + split_layer[1]).split("/" ) )] elif "kvstore" in layer: __lowerCAmelCase = layer.split("kvstore" ) __lowerCAmelCase = "".join(split_layer[0] )[:-1] __lowerCAmelCase = [tuple(("kvstore" + split_layer[1]).split("/" ) )] else: __lowerCAmelCase = layer.split("/" ) __lowerCAmelCase = "/".join(split_layer[:-1] ) __lowerCAmelCase = (split_layer[-1],) if "kvstore/path" in layer: __lowerCAmelCase = F"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: __lowerCAmelCase = "file" else: __lowerCAmelCase = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = rename_keys(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = {} for k, v in current_block.items(): __lowerCAmelCase = v __lowerCAmelCase = new_current_block torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str = WEIGHTS_NAME ): __lowerCAmelCase = convert_file_size_to_int(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = [] __lowerCAmelCase = {} __lowerCAmelCase = 0 __lowerCAmelCase = 0 os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp: __lowerCAmelCase = serialization.msgpack_restore(fp.read() )["optimizer"]["target"] __lowerCAmelCase = flatten_dict(SCREAMING_SNAKE_CASE_ , sep="/" ) __lowerCAmelCase = {} for layer in checkpoint_info.keys(): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = get_key_and_tensorstore_dict( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if curr_real_layer_name in all_layers: __lowerCAmelCase = content else: __lowerCAmelCase = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowerCAmelCase = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowerCAmelCase = torch.tensor(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowerCAmelCase , __lowerCAmelCase = rename_base_flax_keys(tuple(key.split("/" ) ) , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = "/".join(SCREAMING_SNAKE_CASE_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowerCAmelCase = os.path.join( SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{len(SCREAMING_SNAKE_CASE_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowerCAmelCase = {} __lowerCAmelCase = 0 __lowerCAmelCase = raw_weights.to(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{len(SCREAMING_SNAKE_CASE_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(SCREAMING_SNAKE_CASE_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowerCAmelCase = {} __lowerCAmelCase = {} for idx, shard in enumerate(SCREAMING_SNAKE_CASE_ ): __lowerCAmelCase = weights_name.replace( ".bin" , F"""-{idx+1:05d}-of-{len(SCREAMING_SNAKE_CASE_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(SCREAMING_SNAKE_CASE_ , os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) __lowerCAmelCase = shard for key in shard: __lowerCAmelCase = shard_file # Add the metadata __lowerCAmelCase = {"total_size": total_size} __lowerCAmelCase = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , "w" , encoding="utf-8" ) as f: __lowerCAmelCase = json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ ) + "\n" f.write(SCREAMING_SNAKE_CASE_ ) return metadata, index if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) UpperCamelCase__ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def _a ( ): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowerCAmelCase = SwitchTransformersConfig.from_pretrained("google/switch-base-8" ) config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" ) __lowerCAmelCase = SwitchTransformersForConditionalGeneration.from_pretrained( "/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" ) __lowerCAmelCase = TaTokenizer.from_pretrained("t5-small" ) __lowerCAmelCase = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>." __lowerCAmelCase = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="pt" ).input_ids __lowerCAmelCase = model.generate(SCREAMING_SNAKE_CASE_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
92
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class lowerCAmelCase__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = None lowerCAmelCase_ = None _lowercase : Optional[int] = namedtuple("CoinsDistribResult", "moves excess") def snake_case_ ( __SCREAMING_SNAKE_CASE : TreeNode | None ): """simple docstring""" if root is None: return 0 # Validation def count_nodes(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(__SCREAMING_SNAKE_CASE ) != count_coins(__SCREAMING_SNAKE_CASE ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(__SCREAMING_SNAKE_CASE : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowercase_ , lowercase_ : Tuple = get_distrib(node.left ) lowercase_ , lowercase_ : Dict = get_distrib(node.right ) lowercase_ : Dict = 1 - left_distrib_excess lowercase_ : Optional[int] = 1 - right_distrib_excess lowercase_ : Tuple = ( left_distrib_moves + right_distrib_moves + abs(__SCREAMING_SNAKE_CASE ) + abs(__SCREAMING_SNAKE_CASE ) ) lowercase_ : int = node.data - coins_to_left - coins_to_right return CoinsDistribResult(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return get_distrib(__SCREAMING_SNAKE_CASE )[0] if __name__ == "__main__": import doctest doctest.testmod()
93
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = 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__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : str = logging.get_logger(__name__) snake_case : Optional[int] = { '''microsoft/markuplm-base''': '''https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json''', '''microsoft/markuplm-large''': '''https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json''', } class _snake_case ( _snake_case ): SCREAMING_SNAKE_CASE__ = 'markuplm' def __init__( self , _lowerCamelCase=3_0522 , _lowerCamelCase=768 , _lowerCamelCase=12 , _lowerCamelCase=12 , _lowerCamelCase=3072 , _lowerCamelCase="gelu" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=512 , _lowerCamelCase=2 , _lowerCamelCase=0.02 , _lowerCamelCase=1e-12 , _lowerCamelCase=0 , _lowerCamelCase=0 , _lowerCamelCase=2 , _lowerCamelCase=256 , _lowerCamelCase=1024 , _lowerCamelCase=216 , _lowerCamelCase=1001 , _lowerCamelCase=32 , _lowerCamelCase=50 , _lowerCamelCase="absolute" , _lowerCamelCase=True , _lowerCamelCase=None , **_lowerCamelCase , ): super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase , ) a :Optional[Any] = vocab_size a :int = hidden_size a :List[Any] = num_hidden_layers a :str = num_attention_heads a :Tuple = hidden_act a :Any = intermediate_size a :Optional[int] = hidden_dropout_prob a :Optional[Any] = attention_probs_dropout_prob a :Any = max_position_embeddings a :Union[str, Any] = type_vocab_size a :Optional[int] = initializer_range a :Any = layer_norm_eps a :Any = position_embedding_type a :Optional[Any] = use_cache a :Optional[Any] = classifier_dropout # additional properties a :Optional[int] = max_depth a :int = max_xpath_tag_unit_embeddings a :Optional[Any] = max_xpath_subs_unit_embeddings a :Union[str, Any] = tag_pad_id a :str = subs_pad_id a :List[str] = xpath_unit_hidden_size
94
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : List[str] = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off UpperCAmelCase : Optional[Any] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] UpperCAmelCase : Tuple = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class __lowerCAmelCase ( UpperCamelCase__): _lowercase : List[str] = """whisper""" _lowercase : List[Any] = ["""past_key_values"""] _lowercase : str = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase__=5_1_8_6_5 , lowerCAmelCase__=8_0 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=1_5_3_6 , lowerCAmelCase__=1_5_3_6 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=5_0_2_5_7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__="gelu" , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=False , lowerCAmelCase__=1_5_0_0 , lowerCAmelCase__=4_4_8 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=5_0_2_5_6 , lowerCAmelCase__=None , lowerCAmelCase__=[2_2_0, 5_0_2_5_6] , lowerCAmelCase__=False , lowerCAmelCase__=2_5_6 , lowerCAmelCase__=False , lowerCAmelCase__=0.05 , lowerCAmelCase__=1_0 , lowerCAmelCase__=2 , lowerCAmelCase__=0.0 , lowerCAmelCase__=1_0 , lowerCAmelCase__=0 , lowerCAmelCase__=7 , **lowerCAmelCase__ , ) -> Any: '''simple docstring''' a__ : Optional[Any] =vocab_size a__ : List[str] =num_mel_bins a__ : List[str] =d_model a__ : Optional[Any] =encoder_layers a__ : Union[str, Any] =encoder_attention_heads a__ : List[Any] =decoder_layers a__ : Dict =decoder_attention_heads a__ : str =decoder_ffn_dim a__ : int =encoder_ffn_dim a__ : Tuple =dropout a__ : Optional[Any] =attention_dropout a__ : List[str] =activation_dropout a__ : str =activation_function a__ : Dict =init_std a__ : List[str] =encoder_layerdrop a__ : Optional[Any] =decoder_layerdrop a__ : Optional[Any] =use_cache a__ : Tuple =encoder_layers a__ : int =scale_embedding # scale factor will be sqrt(d_model) if True a__ : Union[str, Any] =max_source_positions a__ : Union[str, Any] =max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. a__ : List[Any] =classifier_proj_size a__ : int =use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a__ : str =apply_spec_augment a__ : Union[str, Any] =mask_time_prob a__ : Dict =mask_time_length a__ : int =mask_time_min_masks a__ : Optional[int] =mask_feature_prob a__ : List[Any] =mask_feature_length a__ : Tuple =mask_feature_min_masks a__ : List[str] =median_filter_width super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , suppress_tokens=lowerCAmelCase__ , begin_suppress_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) class __lowerCAmelCase ( UpperCamelCase__): @property def _lowercase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' a__ : List[str] =OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: a__ : str ={0: "batch"} else: a__ : List[str] ={0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase__ , direction="inputs" ) return common_inputs def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = -1 , lowerCAmelCase__ = -1 , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = 2_2_0_5_0 , lowerCAmelCase__ = 5.0 , lowerCAmelCase__ = 2_2_0 , ) -> Mapping[str, Any]: '''simple docstring''' a__ : str =OrderedDict() a__ : Optional[int] =OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowerCAmelCase__ , framework=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , time_duration=lowerCAmelCase__ , frequency=lowerCAmelCase__ , ) a__ : Optional[Any] =encoder_inputs["input_features"].shape[2] a__ : Dict =encoder_sequence_length // 2 if self.use_past else seq_length a__ : List[str] =super().generate_dummy_inputs( preprocessor.tokenizer , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[Any] =encoder_inputs.pop("input_features" ) a__ : Optional[Any] =decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: a__ : List[Any] =decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def _lowercase ( self ) -> float: '''simple docstring''' return 1E-3
95
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ = logging.get_logger(__name__) lowercase__ = {"""ctrl""": """https://huggingface.co/ctrl/resolve/main/config.json"""} class lowerCAmelCase__ ( lowercase ): '''simple docstring''' lowerCamelCase__ = """ctrl""" lowerCamelCase__ = ["""past_key_values"""] lowerCamelCase__ = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , lowercase=246534 , lowercase=256 , lowercase=1280 , lowercase=8192 , lowercase=48 , lowercase=16 , lowercase=0.1 , lowercase=0.1 , lowercase=1E-6 , lowercase=0.02 , lowercase=True , **lowercase , ): _lowerCamelCase : Any = vocab_size _lowerCamelCase : Dict = n_positions _lowerCamelCase : Optional[int] = n_embd _lowerCamelCase : str = n_layer _lowerCamelCase : Union[str, Any] = n_head _lowerCamelCase : Any = dff _lowerCamelCase : int = resid_pdrop _lowerCamelCase : Dict = embd_pdrop _lowerCamelCase : Union[str, Any] = layer_norm_epsilon _lowerCamelCase : Tuple = initializer_range _lowerCamelCase : str = use_cache super().__init__(**lowercase )
96
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
'''simple docstring''' from __future__ import annotations from decimal import Decimal from numpy import array def a ( __a ) -> list[list[float]]: '''simple docstring''' UpperCamelCase__ :List[str] = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(__a ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix UpperCamelCase__ :Optional[int] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creates a copy of the matrix with swapped positions of the elements UpperCamelCase__ :List[Any] = [[0.0, 0.0], [0.0, 0.0]] UpperCamelCase__ , UpperCamelCase__ :int = matrix[1][1], matrix[0][0] UpperCamelCase__ , UpperCamelCase__ :Union[str, Any] = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(__a ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(__a ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule UpperCamelCase__ :Tuple = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError('''This matrix has no inverse.''' ) # Creating cofactor matrix UpperCamelCase__ :Any = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] UpperCamelCase__ :int = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) UpperCamelCase__ :Union[str, Any] = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) UpperCamelCase__ :Tuple = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) UpperCamelCase__ :Any = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) UpperCamelCase__ :Dict = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) UpperCamelCase__ :Tuple = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) UpperCamelCase__ :List[Any] = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) UpperCamelCase__ :str = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) UpperCamelCase__ :Tuple = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) UpperCamelCase__ :Optional[int] = array(__a ) for i in range(3 ): for j in range(3 ): UpperCamelCase__ :Optional[int] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix UpperCamelCase__ :str = array(__a ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(__a ) # Calculate the inverse of the matrix return [[float(d(__a ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError('''Please provide a matrix of size 2x2 or 3x3.''' )
97
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
"""simple docstring""" import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : """simple docstring""" def __init__( self : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Any=8 ,lowerCamelCase__ : Tuple=True ,lowerCamelCase__ : Optional[Any]=True ,lowerCamelCase__ : str=True ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : Tuple=99 ,lowerCamelCase__ : List[Any]=16 ,lowerCamelCase__ : Union[str, Any]=5 ,lowerCamelCase__ : Tuple=2 ,lowerCamelCase__ : Optional[int]=36 ,lowerCamelCase__ : Optional[Any]="gelu" ,lowerCamelCase__ : Dict=0.0 ,lowerCamelCase__ : Any=0.0 ,lowerCamelCase__ : Optional[Any]=512 ,lowerCamelCase__ : Tuple=16 ,lowerCamelCase__ : int=2 ,lowerCamelCase__ : str=0.0_2 ,lowerCamelCase__ : str=3 ,lowerCamelCase__ : Optional[Any]=4 ,lowerCamelCase__ : Tuple=None ,): UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = seq_length UpperCAmelCase__ = is_training UpperCAmelCase__ = use_input_mask UpperCAmelCase__ = use_token_type_ids UpperCAmelCase__ = use_labels UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = type_sequence_label_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = num_labels UpperCAmelCase__ = num_choices UpperCAmelCase__ = scope def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) UpperCAmelCase__ = None if self.use_input_mask: UpperCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase__ = None if self.use_token_type_ids: UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) UpperCAmelCase__ = None UpperCAmelCase__ = None UpperCAmelCase__ = None if self.use_labels: UpperCAmelCase__ = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) UpperCAmelCase__ = ids_tensor([self.batch_size] ,self.num_choices ) UpperCAmelCase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : int ): return MraConfig( 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=lowerCamelCase__ ,initializer_range=self.initializer_range ,) def __lowerCAmelCase ( self : Union[str, Any] ): UpperCAmelCase__ = self.get_config() UpperCAmelCase__ = 300 return config def __lowerCAmelCase ( self : Optional[int] ): ( ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ) = self.prepare_config_and_inputs() UpperCAmelCase__ = True UpperCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) UpperCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __lowerCAmelCase ( self : List[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : str ,lowerCamelCase__ : Dict ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[str] ): UpperCAmelCase__ = MraModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) UpperCAmelCase__ = model(lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) UpperCAmelCase__ = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : Tuple ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any] ,): UpperCAmelCase__ = True UpperCAmelCase__ = MraModel(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,encoder_attention_mask=lowerCamelCase__ ,) UpperCAmelCase__ = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,) UpperCAmelCase__ = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : Optional[int] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : str ,lowerCamelCase__ : Any ): UpperCAmelCase__ = MraForMaskedLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : int ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Any ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int ): UpperCAmelCase__ = MraForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,start_positions=lowerCamelCase__ ,end_positions=lowerCamelCase__ ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : List[str] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[Any] ): UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = MraForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : Union[str, Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : int ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : int ,lowerCamelCase__ : int ): UpperCAmelCase__ = self.num_labels UpperCAmelCase__ = MraForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : int ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : List[str] ): UpperCAmelCase__ = self.num_choices UpperCAmelCase__ = MraForMultipleChoice(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() UpperCAmelCase__ = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() UpperCAmelCase__ = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() UpperCAmelCase__ = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() UpperCAmelCase__ = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,token_type_ids=lowerCamelCase__ ,labels=lowerCamelCase__ ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = self.prepare_config_and_inputs() ( ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ( UpperCAmelCase__ ) , ) = config_and_inputs UpperCAmelCase__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" snake_case__ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = () def __lowerCAmelCase ( self : Dict ): UpperCAmelCase__ = MraModelTester(self ) UpperCAmelCase__ = ConfigTester(self ,config_class=lowerCamelCase__ ,hidden_size=37 ) def __lowerCAmelCase ( self : Any ): self.config_tester.run_common_tests() def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase__ = type self.model_tester.create_and_check_model(*lowerCamelCase__ ) def __lowerCAmelCase ( self : List[str] ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ ) def __lowerCAmelCase ( self : Tuple ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase__ ) def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__ ) def __lowerCAmelCase ( self : List[Any] ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__ ) def __lowerCAmelCase ( self : int ): UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__ ) @slow def __lowerCAmelCase ( self : Any ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ = MraModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip(reason='MRA does not output attentions' ) def __lowerCAmelCase ( self : List[str] ): return @require_torch class snake_case ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Optional[int] ): UpperCAmelCase__ = MraModel.from_pretrained('uw-madison/mra-base-512-4' ) UpperCAmelCase__ = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCAmelCase__ = model(lowerCamelCase__ )[0] UpperCAmelCase__ = torch.Size((1, 256, 768) ) self.assertEqual(output.shape ,lowerCamelCase__ ) UpperCAmelCase__ = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) ) @slow def __lowerCAmelCase ( self : Tuple ): UpperCAmelCase__ = MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' ) UpperCAmelCase__ = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): UpperCAmelCase__ = model(lowerCamelCase__ )[0] UpperCAmelCase__ = 50_265 UpperCAmelCase__ = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape ,lowerCamelCase__ ) UpperCAmelCase__ = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 1_1.8_8_1_9], [9.3_8_6_9, -3.2_6_9_3, 1_1.0_9_5_6], [1_1.8_5_2_4, -3.4_9_3_8, 1_3.1_2_1_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) ) @slow def __lowerCAmelCase ( self : Any ): UpperCAmelCase__ = MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' ) UpperCAmelCase__ = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): UpperCAmelCase__ = model(lowerCamelCase__ )[0] UpperCAmelCase__ = 50_265 UpperCAmelCase__ = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape ,lowerCamelCase__ ) UpperCAmelCase__ = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) )
98
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
import os import sys lowercase : List[str] = os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) lowercase : Optional[int] = [ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def A_ ( *A__ , **A__ ) -> str: return AutoConfig.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def A_ ( *A__ , **A__ ) -> Tuple: return AutoTokenizer.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoModel.__doc__ ) def A_ ( *A__ , **A__ ) -> Any: return AutoModel.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def A_ ( *A__ , **A__ ) -> Tuple: return AutoModelForCausalLM.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def A_ ( *A__ , **A__ ) -> Optional[Any]: return AutoModelForMaskedLM.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def A_ ( *A__ , **A__ ) -> Dict: return AutoModelForSequenceClassification.from_pretrained(*A__ , **A__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def A_ ( *A__ , **A__ ) -> Dict: return AutoModelForQuestionAnswering.from_pretrained(*A__ , **A__ )
99
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
"""simple docstring""" # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __magic_name__ = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") __magic_name__ = ( subprocess.check_output(F"""git diff --diff-filter=d --name-only {fork_point_sha}""".split()).decode("utf-8").split() ) __magic_name__ = "|".join(sys.argv[1:]) __magic_name__ = re.compile(RF"""^({joined_dirs}).*?\.py$""") __magic_name__ = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
100
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase__ :int = { "configuration_blenderbot": [ "BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotConfig", "BlenderbotOnnxConfig", ], "tokenization_blenderbot": ["BlenderbotTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Optional[int] = ["BlenderbotTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :List[str] = [ "BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotForCausalLM", "BlenderbotForConditionalGeneration", "BlenderbotModel", "BlenderbotPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Any = [ "TFBlenderbotForConditionalGeneration", "TFBlenderbotModel", "TFBlenderbotPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Union[str, Any] = [ "FlaxBlenderbotForConditionalGeneration", "FlaxBlenderbotModel", "FlaxBlenderbotPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys lowercase__ :Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
101
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) class _UpperCAmelCase ( __snake_case ): '''simple docstring''' def __init__(self , *a_ , **a_ ): '''simple docstring''' warnings.warn( '''The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use DPTImageProcessor instead.''' , a_ , ) super().__init__(*a_ , **a_ )
102
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ : List[Any] = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Any = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys A__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
103
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
'''simple docstring''' lowerCAmelCase__ = '''Input must be a string of 8 numbers plus letter''' lowerCAmelCase__ = '''TRWAGMYFPDXBNJZSQVHLCKE''' def _A ( A__ ): """simple docstring""" if not isinstance(A__ , A__ ): __lowercase = F"Expected string as input, found {type(A__ ).__name__}" raise TypeError(A__ ) __lowercase = spanish_id.replace('''-''' , '''''' ).upper() if len(A__ ) != 9: raise ValueError(A__ ) try: __lowercase = int(spanish_id_clean[0:8] ) __lowercase = spanish_id_clean[8] except ValueError as ex: raise ValueError(A__ ) from ex if letter.isdigit(): raise ValueError(A__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
104
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __UpperCamelCase ( a__ ): lowerCamelCase : Optional[Any] =(DDIMParallelScheduler,) lowerCamelCase : Optional[int] =(("""eta""", 0.0), ("""num_inference_steps""", 50)) def __a ( self , **lowerCAmelCase__ ) -> Optional[int]: a : Any = { "num_train_timesteps": 1000, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**lowerCAmelCase__ ) return config def __a ( self , **lowerCAmelCase__ ) -> List[Any]: a : List[Any] = self.scheduler_classes[0] a : Any = self.get_scheduler_config(**lowerCAmelCase__ ) a : Optional[int] = scheduler_class(**lowerCAmelCase__ ) a, a : Dict = 10, 0.0 a : Optional[int] = self.dummy_model() a : Dict = self.dummy_sample_deter scheduler.set_timesteps(lowerCAmelCase__ ) for t in scheduler.timesteps: a : List[Any] = model(lowerCAmelCase__ , lowerCAmelCase__ ) a : int = scheduler.step(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ).prev_sample return sample def __a ( self ) -> List[str]: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=lowerCAmelCase__ ) def __a ( self ) -> Optional[Any]: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowerCAmelCase__ ) a : Dict = self.scheduler_classes[0] a : str = self.get_scheduler_config(steps_offset=1 ) a : Any = scheduler_class(**lowerCAmelCase__ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def __a ( self ) -> Optional[Any]: for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowerCAmelCase__ , beta_end=lowerCAmelCase__ ) def __a ( self ) -> int: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCAmelCase__ ) def __a ( self ) -> Any: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCAmelCase__ ) def __a ( self ) -> Any: for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCAmelCase__ ) def __a ( self ) -> Optional[Any]: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowerCAmelCase__ ) def __a ( self ) -> str: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowerCAmelCase__ ) def __a ( self ) -> str: self.check_over_configs(thresholding=lowerCAmelCase__ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowerCAmelCase__ , prediction_type=lowerCAmelCase__ , sample_max_value=lowerCAmelCase__ , ) def __a ( self ) -> List[str]: for t in [1, 10, 49]: self.check_over_forward(time_step=lowerCAmelCase__ ) def __a ( self ) -> Optional[Any]: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=lowerCAmelCase__ , num_inference_steps=lowerCAmelCase__ ) def __a ( self ) -> List[Any]: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=lowerCAmelCase__ , eta=lowerCAmelCase__ ) def __a ( self ) -> Union[str, Any]: a : List[str] = self.scheduler_classes[0] a : Tuple = self.get_scheduler_config() a : Tuple = scheduler_class(**lowerCAmelCase__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def __a ( self ) -> Tuple: a : Optional[Any] = self.scheduler_classes[0] a : Tuple = self.get_scheduler_config() a : str = scheduler_class(**lowerCAmelCase__ ) a, a : str = 10, 0.0 scheduler.set_timesteps(lowerCAmelCase__ ) a : Tuple = self.dummy_model() a : str = self.dummy_sample_deter a : Dict = self.dummy_sample_deter + 0.1 a : Tuple = self.dummy_sample_deter - 0.1 a : int = samplea.shape[0] a : str = torch.stack([samplea, samplea, samplea] , dim=0 ) a : Any = torch.arange(lowerCAmelCase__ )[0:3, None].repeat(1 , lowerCAmelCase__ ) a : Any = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) a : List[Any] = scheduler.batch_step_no_noise(lowerCAmelCase__ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , lowerCAmelCase__ ) a : Optional[Any] = torch.sum(torch.abs(lowerCAmelCase__ ) ) a : Optional[Any] = torch.mean(torch.abs(lowerCAmelCase__ ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1E-2 assert abs(result_mean.item() - 0.4_982 ) < 1E-3 def __a ( self ) -> Optional[Any]: a : List[str] = self.full_loop() a : Any = torch.sum(torch.abs(lowerCAmelCase__ ) ) a : str = torch.mean(torch.abs(lowerCAmelCase__ ) ) assert abs(result_sum.item() - 172.0_067 ) < 1E-2 assert abs(result_mean.item() - 0.223_967 ) < 1E-3 def __a ( self ) -> Dict: a : Dict = self.full_loop(prediction_type="v_prediction" ) a : Optional[int] = torch.sum(torch.abs(lowerCAmelCase__ ) ) a : List[str] = torch.mean(torch.abs(lowerCAmelCase__ ) ) assert abs(result_sum.item() - 52.5_302 ) < 1E-2 assert abs(result_mean.item() - 0.0_684 ) < 1E-3 def __a ( self ) -> Any: # We specify different beta, so that the first alpha is 0.99 a : Dict = self.full_loop(set_alpha_to_one=lowerCAmelCase__ , beta_start=0.01 ) a : Optional[Any] = torch.sum(torch.abs(lowerCAmelCase__ ) ) a : List[Any] = torch.mean(torch.abs(lowerCAmelCase__ ) ) assert abs(result_sum.item() - 149.8_295 ) < 1E-2 assert abs(result_mean.item() - 0.1_951 ) < 1E-3 def __a ( self ) -> Dict: # We specify different beta, so that the first alpha is 0.99 a : Optional[int] = self.full_loop(set_alpha_to_one=lowerCAmelCase__ , beta_start=0.01 ) a : List[str] = torch.sum(torch.abs(lowerCAmelCase__ ) ) a : Any = torch.mean(torch.abs(lowerCAmelCase__ ) ) assert abs(result_sum.item() - 149.0_784 ) < 1E-2 assert abs(result_mean.item() - 0.1_941 ) < 1E-3
105
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
"""simple docstring""" import math def __SCREAMING_SNAKE_CASE ( A_ , A_ ): lowerCAmelCase__ : List[Any] = len(A_ ) lowerCAmelCase__ : List[str] = int(math.floor(math.sqrt(A_ ) ) ) lowerCAmelCase__ : str = 0 while arr[min(A_ , A_ ) - 1] < x: lowerCAmelCase__ : Any = step step += int(math.floor(math.sqrt(A_ ) ) ) if prev >= n: return -1 while arr[prev] < x: lowerCAmelCase__ : List[Any] = prev + 1 if prev == min(A_ , A_ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __UpperCamelCase : Union[str, Any] = input('''Enter numbers separated by a comma:\n''').strip() __UpperCamelCase : Optional[int] = [int(item) for item in user_input.split(''',''')] __UpperCamelCase : Dict = int(input('''Enter the number to be searched:\n''')) __UpperCamelCase : Optional[int] = jump_search(arr, x) if res == -1: print('''Number not found!''') else: print(F'''Number {x} is at index {res}''')
106
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCAmelCase : str = logging.get_logger(__name__) __lowerCAmelCase : Dict = { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json', 'umberto-commoncrawl-cased-v1': ( 'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json' ), 'umberto-wikipedia-uncased-v1': ( 'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json' ), } class snake_case__ (_UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = """camembert""" def __init__( self : Any , __lowerCamelCase : Tuple=3_05_22 , __lowerCamelCase : Optional[Any]=7_68 , __lowerCamelCase : Tuple=12 , __lowerCamelCase : Any=12 , __lowerCamelCase : Any=30_72 , __lowerCamelCase : str="gelu" , __lowerCamelCase : int=0.1 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Optional[Any]=5_12 , __lowerCamelCase : Any=2 , __lowerCamelCase : str=0.02 , __lowerCamelCase : Optional[Any]=1e-12 , __lowerCamelCase : int=1 , __lowerCamelCase : Union[str, Any]=0 , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Tuple="absolute" , __lowerCamelCase : List[str]=True , __lowerCamelCase : Dict=None , **__lowerCamelCase : Dict , ) -> Tuple: super().__init__(pad_token_id=__lowerCamelCase , bos_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , **__lowerCamelCase ) a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = initializer_range a = layer_norm_eps a = position_embedding_type a = use_cache a = classifier_dropout class snake_case__ (_UpperCamelCase ): """simple docstring""" @property def __UpperCAmelCase ( self : Dict ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": a = {0: "batch", 1: "choice", 2: "sequence"} else: a = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
107
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class SCREAMING_SNAKE_CASE__ ( lowercase ): """simple docstring""" a : Optional[int] ="ctrl" a : Dict =["past_key_values"] a : Any ={ "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , snake_case__=246_534 , snake_case__=256 , snake_case__=1_280 , snake_case__=8_192 , snake_case__=48 , snake_case__=16 , snake_case__=0.1 , snake_case__=0.1 , snake_case__=1e-6 , snake_case__=0.02 , snake_case__=True , **snake_case__ , ): """simple docstring""" lowerCAmelCase : str = vocab_size lowerCAmelCase : str = n_positions lowerCAmelCase : Dict = n_embd lowerCAmelCase : List[Any] = n_layer lowerCAmelCase : Tuple = n_head lowerCAmelCase : Optional[Any] = dff lowerCAmelCase : List[str] = resid_pdrop lowerCAmelCase : List[str] = embd_pdrop lowerCAmelCase : Union[str, Any] = layer_norm_epsilon lowerCAmelCase : Dict = initializer_range lowerCAmelCase : Union[str, Any] = use_cache super().__init__(**snake_case__ )
108
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def _snake_case ( UpperCamelCase : Optional[int] , UpperCamelCase : Optional[Any] , UpperCamelCase : List[str]=1e-1_2 ): UpperCAmelCase : Optional[int] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(UpperCamelCase , axis=1 ) , a_min=UpperCamelCase ) ).T UpperCAmelCase : List[Any] = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(UpperCamelCase , axis=1 ) , a_min=UpperCamelCase ) ).T return jnp.matmul(UpperCamelCase , norm_emb_a.T ) class SCREAMING_SNAKE_CASE__ ( nn.Module ): __lowerCAmelCase : CLIPConfig __lowerCAmelCase : jnp.dtype = jnp.floataa def SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' UpperCAmelCase : str = FlaxCLIPVisionModule(self.config.vision_config ) UpperCAmelCase : Dict = nn.Dense(self.config.projection_dim , use_bias=_SCREAMING_SNAKE_CASE , dtype=self.dtype ) UpperCAmelCase : Optional[int] = self.param("""concept_embeds""" , jax.nn.initializers.ones , (17, self.config.projection_dim) ) UpperCAmelCase : int = self.param( """special_care_embeds""" , jax.nn.initializers.ones , (3, self.config.projection_dim) ) UpperCAmelCase : Optional[int] = self.param("""concept_embeds_weights""" , jax.nn.initializers.ones , (17,) ) UpperCAmelCase : Any = self.param("""special_care_embeds_weights""" , jax.nn.initializers.ones , (3,) ) def __call__( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: '''simple docstring''' UpperCAmelCase : Optional[Any] = self.vision_model(_SCREAMING_SNAKE_CASE )[1] UpperCAmelCase : Optional[int] = self.visual_projection(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : List[str] = jax_cosine_distance(_SCREAMING_SNAKE_CASE , self.special_care_embeds ) UpperCAmelCase : Optional[Any] = jax_cosine_distance(_SCREAMING_SNAKE_CASE , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs UpperCAmelCase : int = 0.0 UpperCAmelCase : List[Any] = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment UpperCAmelCase : Tuple = jnp.round(_SCREAMING_SNAKE_CASE , 3 ) UpperCAmelCase : List[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=_SCREAMING_SNAKE_CASE ) # Use a lower threshold if an image has any special care concept UpperCAmelCase : Dict = is_special_care * 0.01 UpperCAmelCase : Optional[Any] = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment UpperCAmelCase : Optional[int] = jnp.round(_SCREAMING_SNAKE_CASE , 3 ) UpperCAmelCase : Optional[int] = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : Dict = CLIPConfig __lowerCAmelCase : Optional[int] = 'clip_input' __lowerCAmelCase : Optional[Any] = FlaxStableDiffusionSafetyCheckerModule def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = jnp.floataa , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> str: '''simple docstring''' if input_shape is None: UpperCAmelCase : Any = (1, 224, 224, 3) UpperCAmelCase : Optional[int] = self.module_class(config=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , input_shape=_SCREAMING_SNAKE_CASE , seed=_SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE , _do_init=_do_init ) def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> FrozenDict: '''simple docstring''' UpperCAmelCase : Optional[Any] = jax.random.normal(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCAmelCase , UpperCAmelCase : Dict = jax.random.split(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : str = {"""params""": params_rng, """dropout""": dropout_rng} UpperCAmelCase : Union[str, Any] = self.module.init(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )["""params"""] return random_params def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase : Tuple = jnp.transpose(_SCREAMING_SNAKE_CASE , (0, 2, 3, 1) ) return self.module.apply( {"""params""": params or self.params} , jnp.array(_SCREAMING_SNAKE_CASE , dtype=jnp.floataa ) , rngs={} , )
109
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def _a ( SCREAMING_SNAKE_CASE ): """simple docstring""" if "img_encoder.pos_embed" in name: lowercase__ = name.replace('''img_encoder.pos_embed''' , '''vision_model.embeddings.position_embeddings''' ) if "img_encoder.patch_embed.proj" in name: lowercase__ = name.replace('''img_encoder.patch_embed.proj''' , '''vision_model.embeddings.patch_embeddings.projection''' ) if "img_encoder.patch_embed.norm" in name: lowercase__ = name.replace('''img_encoder.patch_embed.norm''' , '''vision_model.embeddings.layernorm''' ) if "img_encoder.layers" in name: lowercase__ = name.replace('''img_encoder.layers''' , '''vision_model.encoder.stages''' ) if "blocks" in name and "res" not in name: lowercase__ = name.replace('''blocks''' , '''layers''' ) if "attn" in name and "pre_assign" not in name: lowercase__ = name.replace('''attn''' , '''self_attn''' ) if "proj" in name and "self_attn" in name and "text" not in name: lowercase__ = name.replace('''proj''' , '''out_proj''' ) if "pre_assign_attn.attn.proj" in name: lowercase__ = name.replace('''pre_assign_attn.attn.proj''' , '''pre_assign_attn.attn.out_proj''' ) if "norm1" in name: lowercase__ = name.replace('''norm1''' , '''layer_norm1''' ) if "norm2" in name and "pre_assign" not in name: lowercase__ = name.replace('''norm2''' , '''layer_norm2''' ) if "img_encoder.norm" in name: lowercase__ = name.replace('''img_encoder.norm''' , '''vision_model.layernorm''' ) # text encoder if "text_encoder.token_embedding" in name: lowercase__ = name.replace('''text_encoder.token_embedding''' , '''text_model.embeddings.token_embedding''' ) if "text_encoder.positional_embedding" in name: lowercase__ = name.replace('''text_encoder.positional_embedding''' , '''text_model.embeddings.position_embedding.weight''' ) if "text_encoder.transformer.resblocks." in name: lowercase__ = name.replace('''text_encoder.transformer.resblocks.''' , '''text_model.encoder.layers.''' ) if "ln_1" in name: lowercase__ = name.replace('''ln_1''' , '''layer_norm1''' ) if "ln_2" in name: lowercase__ = name.replace('''ln_2''' , '''layer_norm2''' ) if "c_fc" in name: lowercase__ = name.replace('''c_fc''' , '''fc1''' ) if "c_proj" in name: lowercase__ = name.replace('''c_proj''' , '''fc2''' ) if "text_encoder" in name: lowercase__ = name.replace('''text_encoder''' , '''text_model''' ) if "ln_final" in name: lowercase__ = name.replace('''ln_final''' , '''final_layer_norm''' ) # projection layers if "img_projector.linear_hidden." in name: lowercase__ = name.replace('''img_projector.linear_hidden.''' , '''visual_projection.''' ) if "img_projector.linear_out." in name: lowercase__ = name.replace('''img_projector.linear_out.''' , '''visual_projection.3.''' ) if "text_projector.linear_hidden" in name: lowercase__ = name.replace('''text_projector.linear_hidden''' , '''text_projection''' ) if "text_projector.linear_out" in name: lowercase__ = name.replace('''text_projector.linear_out''' , '''text_projection.3''' ) return name def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): """simple docstring""" for key in orig_state_dict.copy().keys(): lowercase__ = orig_state_dict.pop(SCREAMING_SNAKE_CASE ) 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 lowercase__ = key.split('''.''' ) lowercase__ , lowercase__ = int(key_split[2] ), int(key_split[4] ) lowercase__ = config.vision_config.hidden_size if "weight" in key: lowercase__ = val[:dim, :] lowercase__ = val[dim : dim * 2, :] lowercase__ = val[-dim:, :] else: lowercase__ = val[:dim] lowercase__ = val[dim : dim * 2] lowercase__ = 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 lowercase__ = key.split('''.''' ) lowercase__ = int(key_split[3] ) lowercase__ = config.text_config.hidden_size if "weight" in key: lowercase__ = val[:dim, :] lowercase__ = val[ dim : dim * 2, : ] lowercase__ = val[-dim:, :] else: lowercase__ = val[:dim] lowercase__ = val[dim : dim * 2] lowercase__ = val[-dim:] else: lowercase__ = rename_key(SCREAMING_SNAKE_CASE ) # 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 ): lowercase__ = val.squeeze_() else: lowercase__ = val return orig_state_dict def _a ( ): """simple docstring""" lowercase__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE , stream=SCREAMING_SNAKE_CASE ).raw ) return im @torch.no_grad() def _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE="groupvit-gcc-yfcc" , SCREAMING_SNAKE_CASE=False ): """simple docstring""" lowercase__ = GroupViTConfig() lowercase__ = GroupViTModel(SCREAMING_SNAKE_CASE ).eval() lowercase__ = torch.load(SCREAMING_SNAKE_CASE , map_location='''cpu''' )['''model'''] lowercase__ = convert_state_dict(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) lowercase__ , lowercase__ = model.load_state_dict(SCREAMING_SNAKE_CASE , strict=SCREAMING_SNAKE_CASE ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(SCREAMING_SNAKE_CASE ) == 0) # verify result lowercase__ = CLIPProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) lowercase__ = prepare_img() lowercase__ = processor(text=['''a photo of a cat''', '''a photo of a dog'''] , images=SCREAMING_SNAKE_CASE , padding=SCREAMING_SNAKE_CASE , return_tensors='''pt''' ) with torch.no_grad(): lowercase__ = model(**SCREAMING_SNAKE_CASE ) if model_name == "groupvit-gcc-yfcc": lowercase__ = torch.tensor([[13.3_523, 6.3_629]] ) elif model_name == "groupvit-gcc-redcaps": lowercase__ = 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 , SCREAMING_SNAKE_CASE , atol=1E-3 ) processor.save_pretrained(SCREAMING_SNAKE_CASE ) model.save_pretrained(SCREAMING_SNAKE_CASE ) print('''Successfully saved processor and model to''' , SCREAMING_SNAKE_CASE ) if push_to_hub: print('''Pushing to the hub...''' ) processor.push_to_hub(SCREAMING_SNAKE_CASE , organization='''nielsr''' ) model.push_to_hub(SCREAMING_SNAKE_CASE , organization='''nielsr''' ) if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.' ) parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint') parser.add_argument( '--model_name', default='groupvit-gccy-fcc', type=str, help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.', ) lowerCAmelCase = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
110
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''caidas/swin2sr-classicalsr-x2-64''': ( '''https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json''' ), } class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : int = '''swin2sr''' __snake_case : Dict = { '''hidden_size''': '''embed_dim''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self: Tuple , UpperCAmelCase_: Union[str, Any]=64 , UpperCAmelCase_: Union[str, Any]=1 , UpperCAmelCase_: Optional[Any]=3 , UpperCAmelCase_: Union[str, Any]=180 , UpperCAmelCase_: Tuple=[6, 6, 6, 6, 6, 6] , UpperCAmelCase_: Tuple=[6, 6, 6, 6, 6, 6] , UpperCAmelCase_: Optional[Any]=8 , UpperCAmelCase_: Any=2.0 , UpperCAmelCase_: str=True , UpperCAmelCase_: Union[str, Any]=0.0 , UpperCAmelCase_: Optional[Any]=0.0 , UpperCAmelCase_: Tuple=0.1 , UpperCAmelCase_: Any="gelu" , UpperCAmelCase_: Dict=False , UpperCAmelCase_: Dict=0.02 , UpperCAmelCase_: Any=1E-5 , UpperCAmelCase_: Dict=2 , UpperCAmelCase_: Union[str, Any]=1.0 , UpperCAmelCase_: str="1conv" , UpperCAmelCase_: List[str]="pixelshuffle" , **UpperCAmelCase_: Any , ): '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = embed_dim _SCREAMING_SNAKE_CASE = depths _SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = num_heads _SCREAMING_SNAKE_CASE = window_size _SCREAMING_SNAKE_CASE = mlp_ratio _SCREAMING_SNAKE_CASE = qkv_bias _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = drop_path_rate _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = use_absolute_embeddings _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = upscale _SCREAMING_SNAKE_CASE = img_range _SCREAMING_SNAKE_CASE = resi_connection _SCREAMING_SNAKE_CASE = upsampler
306
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
from manim import * class snake_case ( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple) -> Optional[Any]: """simple docstring""" _snake_case : List[str] = Rectangle(height=0.5 , width=0.5) _snake_case : Optional[int] = Rectangle(height=0.46 , width=0.46).set_stroke(width=0) _snake_case : Dict = [mem.copy() for i in range(6)] _snake_case : List[Any] = [mem.copy() for i in range(6)] _snake_case : Dict = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0) _snake_case : Optional[Any] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0) _snake_case : Any = VGroup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0) _snake_case : Union[str, Any] = Text("""CPU""" , font_size=24) _snake_case : Union[str, Any] = Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__) cpu.move_to([-2.5, -0.5, 0]) self.add(SCREAMING_SNAKE_CASE__) _snake_case : str = [mem.copy() for i in range(1)] _snake_case : Optional[Any] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0) _snake_case : int = Text("""GPU""" , font_size=24) _snake_case : Union[str, Any] = Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__) gpu.align_to(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) gpu.set_x(gpu.get_x() - 1) self.add(SCREAMING_SNAKE_CASE__) _snake_case : Tuple = [mem.copy() for i in range(6)] _snake_case : List[str] = VGroup(*SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0) _snake_case : int = Text("""Model""" , font_size=24) _snake_case : Dict = Group(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__).arrange(SCREAMING_SNAKE_CASE__ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE__) model.move_to([3, -1.0, 0]) self.play( Create(SCREAMING_SNAKE_CASE__ , run_time=1) , Create(SCREAMING_SNAKE_CASE__ , run_time=1) , Create(SCREAMING_SNAKE_CASE__ , run_time=1) , ) _snake_case : List[Any] = MarkupText( F'''First, an empty model skeleton is loaded\ninto <span fgcolor=\'{YELLOW}\'>memory</span> without using much RAM.''' , font_size=24 , ) _snake_case : Tuple = Square(side_length=2.2) key.move_to([-5, 2, 0]) _snake_case : Any = MarkupText( F'''<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model''' , font_size=18 , ) key_text.move_to([-5, 2.4, 0]) step_a.move_to([2, 2, 0]) self.play(Write(SCREAMING_SNAKE_CASE__ , run_time=2.5) , Write(SCREAMING_SNAKE_CASE__) , Write(SCREAMING_SNAKE_CASE__)) self.add(SCREAMING_SNAKE_CASE__) _snake_case : Optional[Any] = [] _snake_case : List[str] = [] _snake_case : Tuple = [] for i, rect in enumerate(SCREAMING_SNAKE_CASE__): _snake_case : Optional[int] = Rectangle(height=0.46 , width=0.46).set_stroke(width=0.0).set_fill(SCREAMING_SNAKE_CASE__ , opacity=0.7) cpu_target.move_to(SCREAMING_SNAKE_CASE__) cpu_target.generate_target() _snake_case : Optional[Any] = 0.46 / 4 _snake_case : Tuple = 0.46 / 3 if i == 0: cpu_target.target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT) , buff=0.02 , direction=SCREAMING_SNAKE_CASE__) cpu_target.target.set_x(cpu_target.target.get_x() + 0.1) elif i == 3: cpu_target.target.next_to(cpu_targs[0].target , direction=SCREAMING_SNAKE_CASE__ , buff=0.0) else: cpu_target.target.next_to(cpu_targs[i - 1].target , direction=SCREAMING_SNAKE_CASE__ , buff=0.0) cpu_targs.append(SCREAMING_SNAKE_CASE__) first_animations.append(rect.animate(run_time=0.5).set_stroke(SCREAMING_SNAKE_CASE__)) second_animations.append(MoveToTarget(SCREAMING_SNAKE_CASE__ , run_time=1.5)) self.play(*SCREAMING_SNAKE_CASE__) self.play(*SCREAMING_SNAKE_CASE__) self.wait()
317
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' def __lowercase ( __lowercase ) -> int: '''simple docstring''' if not isinstance(lowerCamelCase__ , lowerCamelCase__ ): raise ValueError("Input must be an integer" ) if input_num <= 0: raise ValueError("Input must be positive" ) return sum( divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 ) if __name__ == "__main__": import doctest doctest.testmod()
79
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase): @property def _snake_case ( self )-> List[str]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _snake_case ( self )-> int: lowerCamelCase_ =ort.SessionOptions() lowerCamelCase_ =False return options def _snake_case ( self )-> str: lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) lowerCamelCase_ =load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) lowerCamelCase_ =load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy""" ) # using the PNDM scheduler by default lowerCamelCase_ =OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( """CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ ='A red cat sitting on a park bench' lowerCamelCase_ =np.random.RandomState(0 ) lowerCamelCase_ =pipe( prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , mask_image=SCREAMING_SNAKE_CASE__ , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=15 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) lowerCamelCase_ =output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1E-2
154
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
"""simple docstring""" import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } lowerCAmelCase__ = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def snake_case_ ( A_ : str, A_ : Any, A_ : Any, A_ : int, A_ : Union[str, Any] ): '''simple docstring''' for attribute in key.split('''.''' ): _lowerCamelCase : Any = getattr(lowerCamelCase__, lowerCamelCase__ ) if weight_type is not None: _lowerCamelCase : Any = getattr(lowerCamelCase__, lowerCamelCase__ ).shape else: _lowerCamelCase : List[str] = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": _lowerCamelCase : int = value elif weight_type == "weight_g": _lowerCamelCase : str = value elif weight_type == "weight_v": _lowerCamelCase : Dict = value elif weight_type == "bias": _lowerCamelCase : int = value else: _lowerCamelCase : Dict = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def snake_case_ ( A_ : Union[str, Any], A_ : str ): '''simple docstring''' _lowerCamelCase : List[Any] = [] _lowerCamelCase : Optional[Any] = fairseq_model.state_dict() _lowerCamelCase : Optional[int] = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight _lowerCamelCase : Optional[Any] = None for name, value in fairseq_dict.items(): _lowerCamelCase : Optional[int] = False if "conv_layers" in name: load_conv_layer( lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, hf_model.config.feat_extract_norm == '''group''', ) _lowerCamelCase : Tuple = True elif name.split('''.''' )[0] == "proj": _lowerCamelCase : Tuple = fairseq_model.proj _lowerCamelCase : Any = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: _lowerCamelCase : Any = True if "*" in mapped_key: _lowerCamelCase : Tuple = name.split(lowerCamelCase__ )[0].split('''.''' )[-2] _lowerCamelCase : Optional[Any] = mapped_key.replace('''*''', lowerCamelCase__ ) if "weight_g" in name: _lowerCamelCase : int = 'weight_g' elif "weight_v" in name: _lowerCamelCase : List[Any] = 'weight_v' elif "bias" in name: _lowerCamelCase : List[str] = 'bias' elif "weight" in name: _lowerCamelCase : List[Any] = 'weight' else: _lowerCamelCase : Tuple = None set_recursively(lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, lowerCamelCase__ ) continue if not is_used: unused_weights.append(lowerCamelCase__ ) logger.warning(F'''Unused weights: {unused_weights}''' ) return proj_weight def snake_case_ ( A_ : List[Any], A_ : Dict, A_ : Optional[int], A_ : List[str], A_ : Tuple ): '''simple docstring''' _lowerCamelCase : Dict = full_name.split('''conv_layers.''' )[-1] _lowerCamelCase : int = name.split('''.''' ) _lowerCamelCase : Tuple = int(items[0] ) _lowerCamelCase : Any = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) _lowerCamelCase : int = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) _lowerCamelCase : Optional[int] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) _lowerCamelCase : List[str] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) _lowerCamelCase : Union[str, Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowerCamelCase__ ) def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' _lowerCamelCase : List[Any] = emb.weight.shape _lowerCamelCase : Optional[Any] = nn.Linear(lowerCamelCase__, lowerCamelCase__, bias=lowerCamelCase__ ) _lowerCamelCase : Tuple = emb.weight.data return lin_layer def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' with open(lowerCamelCase__, '''r''', encoding='''utf-8''' ) as f: _lowerCamelCase : str = f.readlines() _lowerCamelCase : int = [line.split(''' ''' )[0] for line in lines] _lowerCamelCase : List[Any] = len(lowerCamelCase__ ) _lowerCamelCase : List[str] = { '<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3, } vocab_dict.update(dict(zip(lowerCamelCase__, range(4, num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def snake_case_ ( A_ : List[str], A_ : List[Any], A_ : Optional[Any], A_ : Tuple, A_ : str, A_ : int, A_ : Any, ): '''simple docstring''' _lowerCamelCase : Optional[int] = WavaVecaConfig.from_pretrained(lowerCamelCase__ ) _lowerCamelCase : Union[str, Any] = SpeechaTextaConfig.from_pretrained( lowerCamelCase__, vocab_size=lowerCamelCase__, decoder_layers=lowerCamelCase__, do_stable_layer_norm=lowerCamelCase__ ) _lowerCamelCase : Dict = WavaVecaFeatureExtractor( feature_size=1, sampling_rate=1_60_00, padding_value=0, do_normalize=lowerCamelCase__, return_attention_mask=lowerCamelCase__, ) _lowerCamelCase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) _lowerCamelCase : Dict = model[0].eval() # set weights for wav2vec2 encoder _lowerCamelCase : Optional[int] = WavaVecaModel(lowerCamelCase__ ) _lowerCamelCase : Optional[Any] = recursively_load_weights_wavaveca(model.encoder, lowerCamelCase__ ) _lowerCamelCase : List[str] = SpeechaTextaForCausalLM(lowerCamelCase__ ) _lowerCamelCase : Tuple = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=lowerCamelCase__ ) # set output linear layer unexpected_keys.remove('''embed_out''' ) _lowerCamelCase : Tuple = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(F'''The following keys are missing when loading the decoder weights: {missing_keys}''' ) logger.warning(F'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' ) _lowerCamelCase : Union[str, Any] = SpeechEncoderDecoderModel(encoder=lowerCamelCase__, decoder=lowerCamelCase__ ) _lowerCamelCase : Union[str, Any] = False # add projection layer _lowerCamelCase : Any = nn.Parameter(projection_layer.weight ) _lowerCamelCase : Tuple = nn.Parameter(projection_layer.bias ) _lowerCamelCase : List[Any] = create_vocab_dict(lowerCamelCase__ ) with open(os.path.join(lowerCamelCase__, '''vocab.json''' ), '''w''' ) as fp: json.dump(lowerCamelCase__, lowerCamelCase__ ) _lowerCamelCase : Optional[Any] = SpeechaTextaTokenizer(os.path.join(lowerCamelCase__, '''vocab.json''' ) ) tokenizer.save_pretrained(lowerCamelCase__ ) _lowerCamelCase : str = hf_wavavec.config.to_dict() _lowerCamelCase : str = tokenizer.pad_token_id _lowerCamelCase : Union[str, Any] = tokenizer.bos_token_id _lowerCamelCase : Dict = tokenizer.eos_token_id _lowerCamelCase : Dict = 'speech_to_text_2' _lowerCamelCase : Tuple = 'wav2vec2' _lowerCamelCase : List[str] = SpeechEncoderDecoderConfig.from_dict(lowerCamelCase__ ) hf_wavavec.save_pretrained(lowerCamelCase__ ) feature_extractor.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument( '''--encoder_config_path''', default='''facebook/wav2vec2-large-lv60''', type=str, help='''Path to hf encoder wav2vec2 checkpoint config''', ) parser.add_argument( '''--decoder_config_path''', default='''facebook/s2t-small-mustc-en-fr-st''', type=str, help='''Path to hf decoder s2t checkpoint config''', ) parser.add_argument('''--vocab_size''', default=10224, type=int, help='''Vocab size of decoder''') parser.add_argument('''--num_decoder_layers''', default=7, type=int, help='''Number of decoder layers''') lowerCAmelCase__ = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
72
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = 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__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case = { '''configuration_lxmert''': ['''LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LxmertConfig'''], '''tokenization_lxmert''': ['''LxmertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''LxmertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''LxmertEncoder''', '''LxmertForPreTraining''', '''LxmertForQuestionAnswering''', '''LxmertModel''', '''LxmertPreTrainedModel''', '''LxmertVisualFeatureEncoder''', '''LxmertXLayer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ '''TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFLxmertForPreTraining''', '''TFLxmertMainLayer''', '''TFLxmertModel''', '''TFLxmertPreTrainedModel''', '''TFLxmertVisualFeatureEncoder''', ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy lowerCAmelCase_ = logging.get_logger(__name__) class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ , __magic_name__ , __magic_name__ , **__magic_name__ ) -> str: '''simple docstring''' snake_case_ : List[str] = feature_size snake_case_ : Optional[int] = sampling_rate snake_case_ : Dict = padding_value snake_case_ : Any = kwargs.pop('''padding_side''' , '''right''' ) snake_case_ : int = kwargs.pop('''return_attention_mask''' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = True , __magic_name__ = None , __magic_name__ = False , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , ) -> str: '''simple docstring''' if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): snake_case_ : Tuple = { key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( '''You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`''' F''' to this method that includes {self.model_input_names[0]}, but you provided''' F''' {list(processed_features.keys() )}''' ) snake_case_ : str = processed_features[self.model_input_names[0]] snake_case_ : Any = ( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: snake_case_ : List[str] = [] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch snake_case_ : Optional[Any] = required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. snake_case_ : List[str] = 0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): snake_case_ : Tuple = required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): snake_case_ : Any = 'tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): snake_case_ : Union[str, Any] = 'pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): snake_case_ : Union[str, Any] = 'np' else: raise ValueError( F'''type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ''' '''Should be one of a python, numpy, pytorch or tensorflow object.''' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): snake_case_ : Union[str, Any] = to_numpy(SCREAMING_SNAKE_CASE__ ) else: snake_case_ : Dict = [to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy snake_case_ : Tuple = self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) snake_case_ : Union[str, Any] = processed_features[self.model_input_names[0]] snake_case_ : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('''Some items in the output dictionary have a different batch size than others.''' ) snake_case_ : Any = [] for i in range(SCREAMING_SNAKE_CASE__ ): snake_case_ : int = {k: v[i] for k, v in processed_features.items()} # truncation snake_case_ : Union[str, Any] = self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length snake_case_ : Any = max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) snake_case_ : Optional[Any] = PaddingStrategy.MAX_LENGTH snake_case_ : Optional[Any] = {} for i in range(SCREAMING_SNAKE_CASE__ ): # padding snake_case_ : List[str] = self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: snake_case_ : Union[str, Any] = [] if value.dtype is np.dtype(np.floataa ): snake_case_ : Any = value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = PaddingStrategy.DO_NOT_PAD , __magic_name__ = None , __magic_name__ = None , ) -> str: '''simple docstring''' snake_case_ : Optional[int] = processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: snake_case_ : int = len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): snake_case_ : List[Any] = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of snake_case_ : Dict = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: snake_case_ : int = np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: snake_case_ : List[Any] = max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: snake_case_ : Any = np.pad( processed_features['''attention_mask'''] , (0, difference) ) snake_case_ : str = ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) snake_case_ : Tuple = np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''constant''' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: snake_case_ : List[Any] = np.pad( processed_features['''attention_mask'''] , (difference, 0) ) snake_case_ : Any = ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) snake_case_ : Union[str, Any] = np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''constant''' , constant_values=self.padding_value ) else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return processed_features def lowerCamelCase (self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , ) -> List[Any]: '''simple docstring''' if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('''When setting ``truncation=True``, make sure that ``max_length`` is defined.''' ) snake_case_ : Union[str, Any] = processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): snake_case_ : Tuple = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of snake_case_ : Optional[int] = len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: snake_case_ : Dict = processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: snake_case_ : Optional[Any] = processed_features['attention_mask'][:max_length] return processed_features def lowerCamelCase (self , __magic_name__=False , __magic_name__=None ) -> List[str]: '''simple docstring''' if padding is not False: if padding is True: snake_case_ : Any = PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ : Optional[int] = PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): snake_case_ : Optional[Any] = padding else: snake_case_ : Union[str, Any] = PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( F'''When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined''' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( '''Asking to pad but the feature_extractor does not have a padding value. Please select a value to use''' ''' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.''' ) return padding_strategy
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class a__ ( __A ): """simple docstring""" __UpperCamelCase : torch.FloatTensor class a__ ( __A , __A ): """simple docstring""" @register_to_config def __init__(self , __lowercase = 16 , __lowercase = 88 , __lowercase = None , __lowercase = None , __lowercase = 1 , __lowercase = 0.0 , __lowercase = 32 , __lowercase = None , __lowercase = False , __lowercase = None , __lowercase = "geglu" , __lowercase = True , __lowercase = True , ): super().__init__() __lowerCAmelCase = num_attention_heads __lowerCAmelCase = attention_head_dim __lowerCAmelCase = num_attention_heads * attention_head_dim __lowerCAmelCase = in_channels __lowerCAmelCase = torch.nn.GroupNorm(num_groups=SCREAMING_SNAKE_CASE__ , num_channels=SCREAMING_SNAKE_CASE__ , eps=1e-6 , affine=SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 3. Define transformers blocks __lowerCAmelCase = nn.ModuleList( [ BasicTransformerBlock( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , cross_attention_dim=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , attention_bias=SCREAMING_SNAKE_CASE__ , double_self_attention=SCREAMING_SNAKE_CASE__ , norm_elementwise_affine=SCREAMING_SNAKE_CASE__ , ) for d in range(SCREAMING_SNAKE_CASE__ ) ] ) __lowerCAmelCase = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _snake_case (self , __lowercase , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase=1 , __lowercase=None , __lowercase = True , ): __lowerCAmelCase = hidden_states.shape __lowerCAmelCase = batch_frames // num_frames __lowerCAmelCase = hidden_states __lowerCAmelCase = hidden_states[None, :].reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) __lowerCAmelCase = self.norm(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = self.proj_in(SCREAMING_SNAKE_CASE__ ) # 2. Blocks for block in self.transformer_blocks: __lowerCAmelCase = block( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , timestep=SCREAMING_SNAKE_CASE__ , cross_attention_kwargs=SCREAMING_SNAKE_CASE__ , class_labels=SCREAMING_SNAKE_CASE__ , ) # 3. Output __lowerCAmelCase = self.proj_out(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = ( hidden_states[None, None, :] .reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) __lowerCAmelCase = hidden_states.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=SCREAMING_SNAKE_CASE__ )
174
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer snake_case_ : Dict = logging.get_logger(__name__) snake_case_ : Union[str, Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} snake_case_ : Optional[Any] = { "vocab_file": { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt", "bert-base-multilingual-uncased": ( "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt" ), "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt", "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt" ), "bert-base-cased-finetuned-mrpc": ( "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt" ), "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt", "bert-base-german-dbmdz-uncased": ( "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt" ), "wietsedv/bert-base-dutch-cased": ( "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json", "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json", "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json", "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json", "bert-base-multilingual-uncased": ( "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json" ), "bert-base-multilingual-cased": ( "https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json" ), "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json", "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json", "bert-large-uncased-whole-word-masking": ( "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json" ), "bert-large-cased-whole-word-masking": ( "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json" ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json" ), "bert-large-cased-whole-word-masking-finetuned-squad": ( "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json" ), "bert-base-cased-finetuned-mrpc": ( "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json" ), "bert-base-german-dbmdz-cased": ( "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json" ), "bert-base-german-dbmdz-uncased": ( "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json" ), "TurkuNLP/bert-base-finnish-cased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json" ), "TurkuNLP/bert-base-finnish-uncased-v1": ( "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json" ), "wietsedv/bert-base-dutch-cased": ( "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json" ), }, } snake_case_ : Tuple = { "bert-base-uncased": 512, "bert-large-uncased": 512, "bert-base-cased": 512, "bert-large-cased": 512, "bert-base-multilingual-uncased": 512, "bert-base-multilingual-cased": 512, "bert-base-chinese": 512, "bert-base-german-cased": 512, "bert-large-uncased-whole-word-masking": 512, "bert-large-cased-whole-word-masking": 512, "bert-large-uncased-whole-word-masking-finetuned-squad": 512, "bert-large-cased-whole-word-masking-finetuned-squad": 512, "bert-base-cased-finetuned-mrpc": 512, "bert-base-german-dbmdz-cased": 512, "bert-base-german-dbmdz-uncased": 512, "TurkuNLP/bert-base-finnish-cased-v1": 512, "TurkuNLP/bert-base-finnish-uncased-v1": 512, "wietsedv/bert-base-dutch-cased": 512, } snake_case_ : Tuple = { "bert-base-uncased": {"do_lower_case": True}, "bert-large-uncased": {"do_lower_case": True}, "bert-base-cased": {"do_lower_case": False}, "bert-large-cased": {"do_lower_case": False}, "bert-base-multilingual-uncased": {"do_lower_case": True}, "bert-base-multilingual-cased": {"do_lower_case": False}, "bert-base-chinese": {"do_lower_case": False}, "bert-base-german-cased": {"do_lower_case": False}, "bert-large-uncased-whole-word-masking": {"do_lower_case": True}, "bert-large-cased-whole-word-masking": {"do_lower_case": False}, "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True}, "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False}, "bert-base-cased-finetuned-mrpc": {"do_lower_case": False}, "bert-base-german-dbmdz-cased": {"do_lower_case": False}, "bert-base-german-dbmdz-uncased": {"do_lower_case": True}, "TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False}, "TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True}, "wietsedv/bert-base-dutch-cased": {"do_lower_case": False}, } class __snake_case ( a ): UpperCAmelCase__ : Optional[int] = VOCAB_FILES_NAMES UpperCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : List[str] = PRETRAINED_INIT_CONFIGURATION UpperCAmelCase__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : str = BertTokenizer def __init__( self : Any , _snake_case : List[Any]=None , _snake_case : Union[str, Any]=None , _snake_case : str=True , _snake_case : Optional[Any]="[UNK]" , _snake_case : List[str]="[SEP]" , _snake_case : str="[PAD]" , _snake_case : Optional[Any]="[CLS]" , _snake_case : str="[MASK]" , _snake_case : Optional[Any]=True , _snake_case : str=None , **_snake_case : List[Any] , ): """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) UpperCAmelCase_ = json.loads(self.backend_tokenizer.normalizer.__getstate__()) if ( normalizer_state.get('''lowercase''' , SCREAMING_SNAKE_CASE__) != do_lower_case or normalizer_state.get('''strip_accents''' , SCREAMING_SNAKE_CASE__) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , SCREAMING_SNAKE_CASE__) != tokenize_chinese_chars ): UpperCAmelCase_ = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('''type''')) UpperCAmelCase_ = do_lower_case UpperCAmelCase_ = strip_accents UpperCAmelCase_ = tokenize_chinese_chars UpperCAmelCase_ = normalizer_class(**SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = do_lower_case def lowerCamelCase ( self : Dict , _snake_case : Dict , _snake_case : Tuple=None): """simple docstring""" UpperCAmelCase_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCamelCase ( self : Union[str, Any] , _snake_case : List[int] , _snake_case : Optional[List[int]] = None): """simple docstring""" UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCamelCase ( self : Tuple , _snake_case : str , _snake_case : Optional[str] = None): """simple docstring""" UpperCAmelCase_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__) return tuple(SCREAMING_SNAKE_CASE__)
51
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
class lowercase__ : def __init__( self : Any , UpperCAmelCase_ : list[int] ): SCREAMING_SNAKE_CASE__ = len(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ = [0] * len_array if len_array > 0: SCREAMING_SNAKE_CASE__ = array[0] for i in range(1 , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ = self.prefix_sum[i - 1] + array[i] def A_ ( self : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int ): if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def A_ ( self : int , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(SCREAMING_SNAKE_CASE__ ) return False if __name__ == "__main__": import doctest doctest.testmod()
176
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
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 LevitImageProcessor class snake_case__ (unittest.TestCase ): """simple docstring""" def __init__( self : int , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any]=7 , __lowerCamelCase : Union[str, Any]=3 , __lowerCamelCase : str=18 , __lowerCamelCase : Optional[int]=30 , __lowerCamelCase : List[str]=4_00 , __lowerCamelCase : Any=True , __lowerCamelCase : int=None , __lowerCamelCase : Tuple=True , __lowerCamelCase : str=None , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : List[str]=[0.5, 0.5, 0.5] , __lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , ) -> Tuple: a = size if size is not None else {'shortest_edge': 18} a = crop_size if crop_size is not None else {'height': 18, 'width': 18} a = parent a = batch_size a = num_channels a = image_size a = min_resolution a = max_resolution a = do_resize a = size a = do_center_crop a = crop_size a = do_normalize a = image_mean a = image_std def __UpperCAmelCase ( self : List[str] ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "do_center_crop": self.do_center_crop, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class snake_case__ (_UpperCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[Any] = LevitImageProcessor if is_vision_available() else None def __UpperCAmelCase ( self : int ) -> Dict: a = LevitImageProcessingTester(self ) @property def __UpperCAmelCase ( self : int ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def __UpperCAmelCase ( self : List[str] ) -> Any: a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_mean" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "image_std" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_normalize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_resize" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "do_center_crop" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , "size" ) ) def __UpperCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: a = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) a = 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 __UpperCAmelCase ( self : Any ) -> int: pass def __UpperCAmelCase ( self : List[str] ) -> Union[str, Any]: # Initialize image_processing a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a = image_processing(SCREAMING_SNAKE_CASE__ , 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 __UpperCAmelCase ( self : Dict ) -> Optional[int]: # Initialize image_processing a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a = image_processing(SCREAMING_SNAKE_CASE__ , 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 __UpperCAmelCase ( self : str ) -> Any: # Initialize image_processing a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input a = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched a = image_processing(SCREAMING_SNAKE_CASE__ , 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"], ) , )
107
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
from math import sqrt def __lowerCamelCase ( snake_case__ ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 ,int(sqrt(lowerCamelCase__ ) + 1 ) ,6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowerCamelCase ( snake_case__ = 1_00_01 ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 1 while count != nth and number < 3: number += 1 if is_prime(lowerCamelCase__ ): count += 1 while count != nth: number += 2 if is_prime(lowerCamelCase__ ): count += 1 return number if __name__ == "__main__": print(f"{solution() = }")
306
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class snake_case : '''simple docstring''' def __init__( self : List[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any]=13 , lowerCAmelCase : Dict=10 , lowerCAmelCase : List[str]=3 , lowerCAmelCase : int=2 , lowerCAmelCase : List[Any]=2 , lowerCAmelCase : Union[str, Any]=2 , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : Any=True , lowerCAmelCase : Optional[Any]=32 , lowerCAmelCase : str=5 , lowerCAmelCase : Optional[Any]=4 , lowerCAmelCase : Tuple=37 , lowerCAmelCase : List[Any]="gelu" , lowerCAmelCase : int=0.1 , lowerCAmelCase : List[Any]=0.1 , lowerCAmelCase : Any=10 , lowerCAmelCase : Union[str, Any]=0.02 , lowerCAmelCase : Dict=0.9 , lowerCAmelCase : str=None , ) -> List[str]: """simple docstring""" _snake_case : Any = parent _snake_case : List[str] = batch_size _snake_case : List[Any] = image_size _snake_case : Union[str, Any] = num_channels _snake_case : Optional[Any] = patch_size _snake_case : int = tubelet_size _snake_case : Optional[Any] = num_frames _snake_case : List[str] = is_training _snake_case : str = use_labels _snake_case : str = hidden_size _snake_case : int = num_hidden_layers _snake_case : int = num_attention_heads _snake_case : Tuple = intermediate_size _snake_case : int = hidden_act _snake_case : Union[str, Any] = hidden_dropout_prob _snake_case : Tuple = attention_probs_dropout_prob _snake_case : List[Any] = type_sequence_label_size _snake_case : List[Any] = initializer_range _snake_case : Tuple = mask_ratio _snake_case : List[str] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame _snake_case : Optional[Any] = (image_size // patch_size) ** 2 _snake_case : Union[str, Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos _snake_case : Any = int(mask_ratio * self.seq_length) def UpperCamelCase_ ( self : Tuple) -> Dict: """simple docstring""" _snake_case : Any = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]) _snake_case : Optional[int] = None if self.use_labels: _snake_case : int = ids_tensor([self.batch_size] , self.type_sequence_label_size) _snake_case : List[Any] = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Optional[int]) -> List[Any]: """simple docstring""" return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self : Dict , lowerCAmelCase : str , lowerCAmelCase : Any , lowerCAmelCase : Tuple) -> str: """simple docstring""" _snake_case : List[str] = VideoMAEModel(config=SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() _snake_case : Optional[int] = model(SCREAMING_SNAKE_CASE__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase_ ( self : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[str]) -> Dict: """simple docstring""" _snake_case : Optional[int] = VideoMAEForPreTraining(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch _snake_case : int = torch.ones((self.num_masks,)) _snake_case : List[str] = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0))]) _snake_case : Optional[int] = mask.expand(self.batch_size , -1).bool() _snake_case : Optional[Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # model only returns predictions for masked patches _snake_case : Union[str, Any] = mask.sum().item() _snake_case : str = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels)) def UpperCamelCase_ ( self : Tuple) -> List[str]: """simple docstring""" _snake_case : Dict = self.prepare_config_and_inputs() _snake_case : List[str] = config_and_inputs _snake_case : Any = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ): '''simple docstring''' snake_case_ : Any = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) snake_case_ : Dict = ( {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification} if is_torch_available() else {} ) snake_case_ : Optional[Any] = False snake_case_ : str = False snake_case_ : Optional[int] = False snake_case_ : Optional[int] = False def UpperCamelCase_ ( self : Any) -> Optional[int]: """simple docstring""" _snake_case : str = VideoMAEModelTester(self) _snake_case : Union[str, Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37) def UpperCamelCase_ ( self : Optional[Any] , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Tuple , lowerCAmelCase : Optional[int]=False) -> List[Any]: """simple docstring""" _snake_case : Union[str, Any] = copy.deepcopy(SCREAMING_SNAKE_CASE__) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch _snake_case : str = torch.ones((self.model_tester.num_masks,)) _snake_case : List[Any] = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0))]) _snake_case : int = mask.expand(self.model_tester.batch_size , -1).bool() _snake_case : str = bool_masked_pos.to(SCREAMING_SNAKE_CASE__) if return_labels: if model_class in [ *get_values(SCREAMING_SNAKE_CASE__), ]: _snake_case : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__) return inputs_dict def UpperCamelCase_ ( self : Dict) -> int: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""VideoMAE does not use inputs_embeds""") def UpperCamelCase_ ( self : Any) -> Optional[int]: """simple docstring""" pass def UpperCamelCase_ ( self : Dict) -> List[Any]: """simple docstring""" _snake_case : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Dict = model_class(SCREAMING_SNAKE_CASE__) self.assertIsInstance(model.get_input_embeddings() , (nn.Module)) _snake_case : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear)) def UpperCamelCase_ ( self : Any) -> Union[str, Any]: """simple docstring""" _snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : str = model_class(SCREAMING_SNAKE_CASE__) _snake_case : Union[str, Any] = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case : str = [*signature.parameters.keys()] _snake_case : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__) def UpperCamelCase_ ( self : Optional[int]) -> Optional[Any]: """simple docstring""" _snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__) def UpperCamelCase_ ( self : int) -> str: """simple docstring""" _snake_case : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*SCREAMING_SNAKE_CASE__) @slow def UpperCamelCase_ ( self : int) -> Any: """simple docstring""" for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _snake_case : Optional[Any] = VideoMAEModel.from_pretrained(SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) def UpperCamelCase_ ( self : Tuple) -> Union[str, Any]: """simple docstring""" if not self.has_attentions: pass else: _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() _snake_case : Any = True for model_class in self.all_model_classes: _snake_case : int = self.model_tester.seq_length - self.model_tester.num_masks _snake_case : int = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) _snake_case : Any = True _snake_case : str = False _snake_case : Union[str, Any] = True _snake_case : str = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): _snake_case : str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)) _snake_case : str = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) , self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] _snake_case : List[str] = True _snake_case : int = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): _snake_case : List[str] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)) _snake_case : Any = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _snake_case : Dict = len(SCREAMING_SNAKE_CASE__) # Check attention is always last and order is fine _snake_case : Dict = True _snake_case : List[str] = True _snake_case : Tuple = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): _snake_case : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__)) _snake_case : List[Any] = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__) , self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def UpperCamelCase_ ( self : str) -> str: """simple docstring""" def check_hidden_states_output(lowerCAmelCase : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Union[str, Any]): _snake_case : str = model_class(SCREAMING_SNAKE_CASE__) model.to(SCREAMING_SNAKE_CASE__) model.eval() with torch.no_grad(): _snake_case : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__)) _snake_case : List[str] = outputs.hidden_states _snake_case : Tuple = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE__) _snake_case : Dict = self.model_tester.seq_length - self.model_tester.num_masks _snake_case : Optional[Any] = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:]) , [seq_length, self.model_tester.hidden_size] , ) _snake_case : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Optional[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _snake_case : Optional[Any] = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""") def UpperCamelCase_ ( self : Tuple) -> List[Any]: """simple docstring""" pass def lowercase ( ) -> Dict: _snake_case : Dict = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" ) _snake_case : int = np.load(lowerCamelCase__ ) return list(lowerCamelCase__ ) @require_torch @require_vision class snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[Any]) -> List[str]: """simple docstring""" return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5]) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : int) -> int: """simple docstring""" _snake_case : Dict = VideoMAEForVideoClassification.from_pretrained("""MCG-NJU/videomae-base-finetuned-kinetics""").to( SCREAMING_SNAKE_CASE__) _snake_case : str = self.default_image_processor _snake_case : int = prepare_video() _snake_case : str = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE__) # forward pass with torch.no_grad(): _snake_case : Union[str, Any] = model(**SCREAMING_SNAKE_CASE__) # verify the logits _snake_case : Union[str, Any] = torch.Size((1, 400)) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__) _snake_case : Tuple = torch.tensor([0.3_669, -0.0_688, -0.2_421]).to(SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4)) @slow def UpperCamelCase_ ( self : Optional[Any]) -> List[str]: """simple docstring""" _snake_case : Dict = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""").to(SCREAMING_SNAKE_CASE__) _snake_case : Any = self.default_image_processor _snake_case : List[str] = prepare_video() _snake_case : List[Any] = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""").to(SCREAMING_SNAKE_CASE__) # add boolean mask, indicating which patches to mask _snake_case : str = hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""" , filename="""bool_masked_pos.pt""") _snake_case : Dict = torch.load(SCREAMING_SNAKE_CASE__) # forward pass with torch.no_grad(): _snake_case : Optional[Any] = model(**SCREAMING_SNAKE_CASE__) # verify the logits _snake_case : Any = torch.Size([1, 1408, 1536]) _snake_case : Optional[int] = torch.tensor( [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] , device=SCREAMING_SNAKE_CASE__) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `True`) _snake_case : Any = torch.tensor([0.5_142] , device=SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.loss , SCREAMING_SNAKE_CASE__ , atol=1E-4)) # verify the loss (`config.norm_pix_loss` = `False`) _snake_case : List[Any] = VideoMAEForPreTraining.from_pretrained("""MCG-NJU/videomae-base-short""" , norm_pix_loss=SCREAMING_SNAKE_CASE__).to( SCREAMING_SNAKE_CASE__) with torch.no_grad(): _snake_case : Optional[int] = model(**SCREAMING_SNAKE_CASE__) _snake_case : Optional[Any] = torch.tensor(torch.tensor([0.6_469]) , device=SCREAMING_SNAKE_CASE__) self.assertTrue(torch.allclose(outputs.loss , SCREAMING_SNAKE_CASE__ , atol=1E-4))
317
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' import math import flax.linen as nn import jax.numpy as jnp def __lowercase ( __lowercase , __lowercase , __lowercase = 1 , __lowercase = 1 , __lowercase = 1.0e4 , __lowercase = False , __lowercase = 1.0 , ) -> jnp.ndarray: '''simple docstring''' assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' _A = float(embedding_dim // 2 ) _A = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) _A = min_timescale * jnp.exp(jnp.arange(lowerCamelCase__ , dtype=jnp.floataa ) * -log_timescale_increment ) _A = jnp.expand_dims(lowerCamelCase__ , 1 ) * jnp.expand_dims(lowerCamelCase__ , 0 ) # scale embeddings _A = scale * emb if flip_sin_to_cos: _A = jnp.concatenate([jnp.cos(lowerCamelCase__ ), jnp.sin(lowerCamelCase__ )] , axis=1 ) else: _A = jnp.concatenate([jnp.sin(lowerCamelCase__ ), jnp.cos(lowerCamelCase__ )] , axis=1 ) _A = jnp.reshape(lowerCamelCase__ , [jnp.shape(lowerCamelCase__ )[0], embedding_dim] ) return signal class _UpperCAmelCase ( nn.Module ): """simple docstring""" snake_case = 32 snake_case = jnp.floataa @nn.compact def __call__( self : Union[str, Any] , __UpperCAmelCase : List[Any] ): '''simple docstring''' _A = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(SCREAMING_SNAKE_CASE__ ) _A = nn.silu(SCREAMING_SNAKE_CASE__ ) _A = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(SCREAMING_SNAKE_CASE__ ) return temb class _UpperCAmelCase ( nn.Module ): """simple docstring""" snake_case = 32 snake_case = False snake_case = 1 @nn.compact def __call__( self : Union[str, Any] , __UpperCAmelCase : List[str] ): '''simple docstring''' return get_sinusoidal_embeddings( SCREAMING_SNAKE_CASE__ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
79
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __A : str = logging.get_logger(__name__) __A : List[str] = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Union[str, Any] = '''mgp-str''' def __init__( self , _SCREAMING_SNAKE_CASE=[32, 128] , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=27 , _SCREAMING_SNAKE_CASE=38 , _SCREAMING_SNAKE_CASE=5_0257 , _SCREAMING_SNAKE_CASE=3_0522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1E-5 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.0_2 , **_SCREAMING_SNAKE_CASE , )-> Optional[Any]: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =image_size lowerCamelCase_ =patch_size lowerCamelCase_ =num_channels lowerCamelCase_ =max_token_length lowerCamelCase_ =num_character_labels lowerCamelCase_ =num_bpe_labels lowerCamelCase_ =num_wordpiece_labels lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_attention_heads lowerCamelCase_ =mlp_ratio lowerCamelCase_ =distilled lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =drop_rate lowerCamelCase_ =qkv_bias lowerCamelCase_ =attn_drop_rate lowerCamelCase_ =drop_path_rate lowerCamelCase_ =output_aa_attentions lowerCamelCase_ =initializer_range
154
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available lowerCAmelCase__ = { '''configuration_gpt_neo''': ['''GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoConfig''', '''GPTNeoOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoForCausalLM''', '''GPTNeoForQuestionAnswering''', '''GPTNeoForSequenceClassification''', '''GPTNeoForTokenClassification''', '''GPTNeoModel''', '''GPTNeoPreTrainedModel''', '''load_tf_weights_in_gpt_neo''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''FlaxGPTNeoForCausalLM''', '''FlaxGPTNeoModel''', '''FlaxGPTNeoPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
72
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowercase ( A__ ): """simple docstring""" _a = ['''image_processor''', '''tokenizer'''] _a = '''Pix2StructImageProcessor''' _a = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self , UpperCamelCase_=None , UpperCamelCase_ = None , UpperCamelCase_ = True , UpperCamelCase_ = False , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = 2048 , UpperCamelCase_ = 0 , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = True , UpperCamelCase_ = None , **UpperCamelCase_ , ): '''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 and not self.image_processor.is_vqa: UpperCamelCase__ :Tuple = self.tokenizer UpperCamelCase__ :Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) return text_encoding if not self.image_processor.is_vqa: # add pixel_values UpperCamelCase__ :List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_patches=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # add pixel_values and bbox UpperCamelCase__ :List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None and not self.image_processor.is_vqa: UpperCamelCase__ :List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if "attention_mask" in text_encoding: UpperCamelCase__ :List[Any] = text_encoding.pop('''attention_mask''' ) if "input_ids" in text_encoding: UpperCamelCase__ :Dict = text_encoding.pop('''input_ids''' ) else: UpperCamelCase__ :Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__ ) return encoding_image_processor def lowerCAmelCase__ ( self , *UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase__ ( self , *UpperCamelCase_ , **UpperCamelCase_ ): '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Dict = self.tokenizer.model_input_names UpperCamelCase__ :int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
97
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
from __future__ import annotations from random import random class __lowerCAmelCase : def __init__(self , __magic_name__ = None ) -> Tuple: '''simple docstring''' snake_case_ : Union[str, Any] = value snake_case_ : int = random() snake_case_ : Node | None = None snake_case_ : Node | None = None def __repr__(self ) -> Any: '''simple docstring''' from pprint import pformat if self.left is None and self.right is None: return F'''\'{self.value}: {self.prior:.5}\'''' else: return pformat( {F'''{self.value}: {self.prior:.5}''': (self.left, self.right)} , indent=1 ) def __str__(self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = str(self.value ) + ' ' snake_case_ : Optional[Any] = str(self.left or '''''' ) snake_case_ : List[Any] = str(self.right or '''''' ) return value + left + right def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> tuple[Node | None, Node | None]: """simple docstring""" if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: snake_case_ : Union[str, Any] = split(root.left , lowerCamelCase__ ) return left, root else: snake_case_ : List[str] = split(root.right , lowerCamelCase__ ) return root, right def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Node | None: """simple docstring""" if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: snake_case_ : Optional[Any] = merge(left.right , lowerCamelCase__ ) return left else: snake_case_ : List[str] = merge(lowerCamelCase__ , right.left ) return right def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Node | None: """simple docstring""" snake_case_ : List[Any] = Node(lowerCamelCase__ ) snake_case_ : Optional[int] = split(lowerCamelCase__ , lowerCamelCase__ ) return merge(merge(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Node | None: """simple docstring""" snake_case_ : List[str] = split(lowerCamelCase__ , value - 1 ) snake_case_ : Any = split(lowerCamelCase__ , lowerCamelCase__ ) return merge(lowerCamelCase__ , lowerCamelCase__ ) def lowerCamelCase_ ( _UpperCamelCase ) -> None: """simple docstring""" if not root: # None return else: inorder(root.left ) print(root.value , end=''',''' ) inorder(root.right ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Node | None: """simple docstring""" for arg in args.split(): if arg[0] == "+": snake_case_ : str = insert(lowerCamelCase__ , int(arg[1:] ) ) elif arg[0] == "-": snake_case_ : List[Any] = erase(lowerCamelCase__ , int(arg[1:] ) ) else: print('''Unknown command''' ) return root def lowerCamelCase_ ( ) -> None: """simple docstring""" snake_case_ : int = None print( '''enter numbers to create a tree, + value to add value into treap, ''' '''- value to erase all nodes with value. \'q\' to quit. ''' ) snake_case_ : Optional[int] = input() while args != "q": snake_case_ : Optional[int] = interact_treap(lowerCamelCase__ , lowerCamelCase__ ) print(lowerCamelCase__ ) snake_case_ : int = input() print('''good by!''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
279
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL _UpperCAmelCase : Dict = logging.get_logger(__name__) class a__ ( __A ): """simple docstring""" __UpperCamelCase : Optional[Any] = ['''pixel_values'''] def __init__(self , __lowercase = True , __lowercase = None , __lowercase = PIL.Image.BICUBIC , __lowercase = True , __lowercase = None , __lowercase = 1 / 2_55 , __lowercase = True , __lowercase = True , __lowercase = None , __lowercase = None , **__lowercase , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = size if size is not None else {'height': 2_56, 'width': 2_56} __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24} __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='''crop_size''' ) __lowerCAmelCase = do_resize __lowerCAmelCase = size __lowerCAmelCase = resample __lowerCAmelCase = do_center_crop __lowerCAmelCase = crop_size __lowerCAmelCase = do_rescale __lowerCAmelCase = rescale_factor __lowerCAmelCase = do_normalize __lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowerCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def _snake_case (self , __lowercase , __lowercase , __lowercase = PIL.Image.BICUBIC , __lowercase = None , **__lowercase , ): __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return resize( SCREAMING_SNAKE_CASE__ , size=(size['''height'''], size['''width''']) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _snake_case (self , __lowercase , __lowercase , __lowercase = None , **__lowercase , ): __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _snake_case (self , __lowercase , __lowercase , __lowercase = None , **__lowercase , ): return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _snake_case (self , __lowercase , __lowercase , __lowercase , __lowercase = None , **__lowercase , ): return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _snake_case (self , __lowercase , __lowercase = None , __lowercase = None , __lowercase=None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = ChannelDimension.FIRST , **__lowercase , ): __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_center_crop if do_center_crop is not None else self.do_center_crop __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_normalize if do_normalize is not None else self.do_normalize __lowerCAmelCase = image_mean if image_mean is not None else self.image_mean __lowerCAmelCase = image_std if image_std is not None else self.image_std __lowerCAmelCase = size if size is not None else self.size __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) __lowerCAmelCase = crop_size if crop_size is not None else self.crop_size __lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='''crop_size''' ) __lowerCAmelCase = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __lowerCAmelCase = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: __lowerCAmelCase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: __lowerCAmelCase = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: __lowerCAmelCase = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: __lowerCAmelCase = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] __lowerCAmelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] __lowerCAmelCase = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
174
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin snake_case_ : Optional[Any] = get_tests_dir("fixtures/spiece.model") @require_sentencepiece @require_tokenizers class __snake_case ( a , unittest.TestCase ): UpperCAmelCase__ : int = DebertaVaTokenizer UpperCAmelCase__ : int = DebertaVaTokenizerFast UpperCAmelCase__ : Tuple = True UpperCAmelCase__ : Tuple = True def lowerCamelCase ( self : Optional[int]): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , unk_token='''<unk>''') tokenizer.save_pretrained(self.tmpdirname) def lowerCamelCase ( self : Dict , _snake_case : Dict): """simple docstring""" UpperCAmelCase_ = 'this is a test' UpperCAmelCase_ = 'this is a test' return input_text, output_text def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = '<pad>' UpperCAmelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__) , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<pad>''') self.assertEqual(vocab_keys[1] , '''<unk>''') self.assertEqual(vocab_keys[-1] , '''[PAD]''') self.assertEqual(len(SCREAMING_SNAKE_CASE__) , 30001) def lowerCamelCase ( self : List[Any]): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 30000) def lowerCamelCase ( self : Dict): """simple docstring""" UpperCAmelCase_ = ' \tHeLLo!how \n Are yoU? ' UpperCAmelCase_ = ['▁hello', '!', 'how', '▁are', '▁you', '?'] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''') def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" pass @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''') def lowerCamelCase ( self : int): """simple docstring""" pass def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : List[Any]): """simple docstring""" UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = ['▁i', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : Tuple): """simple docstring""" UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', '▁', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '▁', '.', ] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = ' \tHeLLo!how \n Are yoU? ' UpperCAmelCase_ = ['▁', '<unk>', 'e', '<unk>', 'o', '!', 'how', '▁', '<unk>', 're', '▁yo', '<unk>', '?'] # fmt: on UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , split_by_punct=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : int): """simple docstring""" UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__)) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : Dict): """simple docstring""" UpperCAmelCase_ = 'This is a test' UpperCAmelCase_ = [13, 1, 4398, 25, 21, 1289] UpperCAmelCase_ = ['▁', 'T', 'his', '▁is', '▁a', '▁test'] UpperCAmelCase_ = ['▁', '<unk>', 'his', '▁is', '▁a', '▁test'] UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = DebertaVaTokenizerFast(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) # fmt: off UpperCAmelCase_ = 'I was born in 92000, and this is falsé.' UpperCAmelCase_ = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] UpperCAmelCase_ = ['▁', 'I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', 'é', '.', ] UpperCAmelCase_ = ['▁', '<unk>', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and', '▁this', '▁is', '▁fal', 's', '<unk>', '.', ] # fmt: on UpperCAmelCase_ = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.tokenize(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = rust_tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = DebertaVaTokenizer(SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.encode('''sequence builders''') UpperCAmelCase_ = tokenizer.encode('''multi-sequence build''') UpperCAmelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE__) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , SCREAMING_SNAKE_CASE__ , ) @slow def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = {'input_ids': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
51
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class lowercase__ ( unittest.TestCase ): @slow def A_ ( self : Any ): SCREAMING_SNAKE_CASE__ = TFCamembertModel.from_pretrained('jplu/tf-camembert-base' ) SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ = model(SCREAMING_SNAKE_CASE__ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor( [[[-0.0_254, 0.0_235, 0.1_027], [0.0_606, -0.1_811, -0.0_418], [-0.1_561, -0.1_127, 0.2_687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
176
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available __lowerCAmelCase : 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: __lowerCAmelCase : Union[str, Any] = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase : List[str] = ['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 __lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
107
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : Union[str, Any] = ['''image_processor''', '''tokenizer'''] __snake_case : Dict = '''BlipImageProcessor''' __snake_case : List[str] = '''AutoTokenizer''' def __init__( self: str , UpperCAmelCase_: List[str] , UpperCAmelCase_: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = False super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = self.image_processor def __call__( self: Dict , UpperCAmelCase_: ImageInput = None , UpperCAmelCase_: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase_: bool = True , UpperCAmelCase_: Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_: Union[bool, str, TruncationStrategy] = None , UpperCAmelCase_: Optional[int] = None , UpperCAmelCase_: int = 0 , UpperCAmelCase_: Optional[int] = None , UpperCAmelCase_: Optional[bool] = None , UpperCAmelCase_: bool = False , UpperCAmelCase_: bool = False , UpperCAmelCase_: bool = False , UpperCAmelCase_: bool = False , UpperCAmelCase_: bool = False , UpperCAmelCase_: bool = True , UpperCAmelCase_: Optional[Union[str, TensorType]] = None , **UpperCAmelCase_: List[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: _SCREAMING_SNAKE_CASE = self.tokenizer _SCREAMING_SNAKE_CASE = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) return text_encoding # add pixel_values _SCREAMING_SNAKE_CASE = self.image_processor(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) if text is not None: _SCREAMING_SNAKE_CASE = self.tokenizer( text=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) else: _SCREAMING_SNAKE_CASE = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__ ) return encoding_image_processor def UpperCamelCase ( self: str , *UpperCAmelCase_: Tuple , **UpperCAmelCase_: Any ): '''simple docstring''' return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: int , *UpperCAmelCase_: List[str] , **UpperCAmelCase_: Tuple ): '''simple docstring''' return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.tokenizer.model_input_names _SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
306
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
from math import factorial, radians def lowercase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] = 18 , SCREAMING_SNAKE_CASE__ : int = 10 ) -> float: _snake_case : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 3_6_0.0) * 3_6_0.0) # Converting from degrees to radians _snake_case : Any = radians(lowerCamelCase__ ) _snake_case : List[Any] = angle_in_radians _snake_case : Dict = 3 _snake_case : List[Any] = -1 for _ in range(lowerCamelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCamelCase__ ) _snake_case : List[Any] = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": __import__("""doctest""").testmod()
317
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCamelCase_ = 16 lowerCamelCase_ = 32 def __lowercase ( __lowercase , __lowercase = 16 ) -> Optional[int]: '''simple docstring''' _A = AutoTokenizer.from_pretrained("bert-base-cased" ) _A = load_dataset("glue" , "mrpc" ) def tokenize_function(__lowercase ): # max_length=None => use the model max length (it's actually the default) _A = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCamelCase__ , max_length=lowerCamelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _A = datasets.map( lowerCamelCase__ , batched=lowerCamelCase__ , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _A = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(__lowercase ): # On TPU it's best to pad everything to the same length or training will be very slow. _A = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _A = 16 elif accelerator.mixed_precision != "no": _A = 8 else: _A = None return tokenizer.pad( lowerCamelCase__ , padding="longest" , max_length=lowerCamelCase__ , pad_to_multiple_of=lowerCamelCase__ , return_tensors="pt" , ) # Instantiate dataloaders. _A = DataLoader( tokenized_datasets["train"] , shuffle=lowerCamelCase__ , collate_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ ) _A = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCamelCase__ , collate_fn=lowerCamelCase__ , batch_size=lowerCamelCase__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCamelCase_ = mocked_dataloaders # noqa: F811 def __lowercase ( __lowercase , __lowercase ) -> Any: '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCamelCase__ ) == "1": _A = 2 # Initialize accelerator _A = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _A = config['lr'] _A = int(config["num_epochs"] ) _A = int(config["seed"] ) _A = int(config["batch_size"] ) _A = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCamelCase__ ) def inner_training_loop(__lowercase ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _A = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCamelCase__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _A = model.to(accelerator.device ) # Instantiate optimizer _A = AdamW(params=model.parameters() , lr=lowerCamelCase__ ) _A = get_dataloaders(lowerCamelCase__ , lowerCamelCase__ ) # Instantiate scheduler _A = get_linear_schedule_with_warmup( optimizer=lowerCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(lowerCamelCase__ ) * num_epochs) , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _A = accelerator.prepare( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Now we train the model for epoch in range(lowerCamelCase__ ): model.train() for step, batch in enumerate(lowerCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _A = model(**lowerCamelCase__ ) _A = outputs.loss accelerator.backward(lowerCamelCase__ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _A = model(**lowerCamelCase__ ) _A = outputs.logits.argmax(dim=-1 ) _A = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCamelCase__ , references=lowerCamelCase__ , ) _A = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , lowerCamelCase__ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def __lowercase ( ) -> Union[str, Any]: '''simple docstring''' _A = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCamelCase__ , default=lowerCamelCase__ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) _A = parser.parse_args() _A = {'lr': 2e-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(lowerCamelCase__ , lowerCamelCase__ ) if __name__ == "__main__": main()
79
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : Tuple = {'vocab_file': 'vocab.txt'} __A : int = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } __A : str = { 'openbmb/cpm-ant-10b': 10_24, } def __UpperCamelCase ( _A : Any ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =collections.OrderedDict() with open(lowerCamelCase__ , """r""" , encoding="""utf-8""" ) as reader: lowerCamelCase_ =reader.readlines() for index, token in enumerate(lowerCamelCase__ ): lowerCamelCase_ =token.rstrip("""\n""" ) lowerCamelCase_ =index return vocab class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE=200 )-> List[Any]: lowerCamelCase_ =vocab lowerCamelCase_ =unk_token lowerCamelCase_ =max_input_chars_per_word def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: lowerCamelCase_ =list(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > self.max_input_chars_per_word: return [self.unk_token] lowerCamelCase_ =0 lowerCamelCase_ =[] while start < len(SCREAMING_SNAKE_CASE__ ): lowerCamelCase_ =len(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =None while start < end: lowerCamelCase_ =''.join(chars[start:end] ) if substr in self.vocab: lowerCamelCase_ =substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =end return sub_tokens class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:List[Any] = VOCAB_FILES_NAMES _UpperCamelCase:int = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase:str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase:str = ['''input_ids''', '''attention_mask'''] _UpperCamelCase:Union[str, Any] = False def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="<d>" , _SCREAMING_SNAKE_CASE="</d>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="</n>" , _SCREAMING_SNAKE_CASE="</_>" , _SCREAMING_SNAKE_CASE="left" , **_SCREAMING_SNAKE_CASE , )-> Union[str, Any]: requires_backends(self , ["""jieba"""] ) super().__init__( bod_token=SCREAMING_SNAKE_CASE__ , eod_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , line_token=SCREAMING_SNAKE_CASE__ , space_token=SCREAMING_SNAKE_CASE__ , padding_side=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCamelCase_ =bod_token lowerCamelCase_ =eod_token lowerCamelCase_ =load_vocab(SCREAMING_SNAKE_CASE__ ) lowerCamelCase_ =self.encoder[space_token] lowerCamelCase_ =self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] lowerCamelCase_ =collections.OrderedDict(sorted(self.encoder.items() , key=lambda _SCREAMING_SNAKE_CASE : x[1] ) ) lowerCamelCase_ ={v: k for k, v in self.encoder.items()} lowerCamelCase_ =WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def _snake_case ( self )-> str: return self.encoder[self.bod_token] @property def _snake_case ( self )-> Union[str, Any]: return self.encoder[self.eod_token] @property def _snake_case ( self )-> Dict: return self.encoder["\n"] @property def _snake_case ( self )-> int: return len(self.encoder ) def _snake_case ( self )-> Dict: return dict(self.encoder , **self.added_tokens_encoder ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =[] for x in jieba.cut(SCREAMING_SNAKE_CASE__ , cut_all=SCREAMING_SNAKE_CASE__ ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) ) return output_tokens def _snake_case ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> Dict: lowerCamelCase_ =[i for i in token_ids if i >= 0] lowerCamelCase_ =[ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]: return token in self.encoder def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> str: return "".join(SCREAMING_SNAKE_CASE__ ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]: return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Optional[int]: if os.path.isdir(SCREAMING_SNAKE_CASE__ ): lowerCamelCase_ =os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) else: lowerCamelCase_ =(filename_prefix + '-' if filename_prefix else '') + save_directory lowerCamelCase_ =0 if " " in self.encoder: lowerCamelCase_ =self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: lowerCamelCase_ =self.encoder['\n'] del self.encoder["\n"] lowerCamelCase_ =collections.OrderedDict(sorted(self.encoder.items() , key=lambda _SCREAMING_SNAKE_CASE : x[1] ) ) with open(SCREAMING_SNAKE_CASE__ , """w""" , encoding="""utf-8""" ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.' """ Please check that the vocabulary is not corrupted!""" ) lowerCamelCase_ =token_index writer.write(token + """\n""" ) index += 1 return (vocab_file,) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> str: if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> Dict: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ ))
154
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = [ ('''bert.bert''', '''visual_bert'''), ('''bert.cls''', '''cls'''), ('''bert.classifier''', '''cls'''), ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''), ('''position_embeddings_visual''', '''visual_position_embeddings'''), ('''projection''', '''visual_projection'''), ] lowerCAmelCase__ = [ '''nlvr2_coco_pre_trained.th''', '''nlvr2_fine_tuned.th''', '''nlvr2_pre_trained.th''', '''vcr_coco_pre_train.th''', '''vcr_fine_tune.th''', '''vcr_pre_train.th''', '''vqa_coco_pre_trained.th''', '''vqa_fine_tuned.th''', '''vqa_pre_trained.th''', ] def snake_case_ ( A_ : List[Any] ): '''simple docstring''' _lowerCamelCase : int = torch.load(lowerCamelCase__, map_location='''cpu''' ) return sd def snake_case_ ( A_ : str, A_ : Union[str, Any], A_ : Union[str, Any]=rename_keys_prefix ): '''simple docstring''' _lowerCamelCase : Tuple = OrderedDict() _lowerCamelCase : int = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue _lowerCamelCase : List[Any] = key for name_pair in rename_keys_prefix: _lowerCamelCase : Optional[Any] = new_key.replace(name_pair[0], name_pair[1] ) _lowerCamelCase : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately _lowerCamelCase : str = new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case_ ( A_ : int, A_ : int ): '''simple docstring''' assert ( checkpoint_path.split('''/''' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: _lowerCamelCase : Optional[Any] = 'pretraining' if "vcr" in checkpoint_path: _lowerCamelCase : Any = {'visual_embedding_dim': 5_12} elif "vqa_advanced" in checkpoint_path: _lowerCamelCase : List[str] = {'visual_embedding_dim': 20_48} elif "vqa" in checkpoint_path: _lowerCamelCase : Tuple = {'visual_embedding_dim': 20_48} elif "nlvr" in checkpoint_path: _lowerCamelCase : List[Any] = {'visual_embedding_dim': 10_24} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: _lowerCamelCase : Tuple = {'visual_embedding_dim': 5_12} _lowerCamelCase : Any = 'multichoice' elif "vqa_advanced" in checkpoint_path: _lowerCamelCase : Tuple = {'visual_embedding_dim': 20_48} _lowerCamelCase : List[Any] = 'vqa_advanced' elif "vqa" in checkpoint_path: _lowerCamelCase : List[Any] = {'visual_embedding_dim': 20_48, 'num_labels': 31_29} _lowerCamelCase : Optional[int] = 'vqa' elif "nlvr" in checkpoint_path: _lowerCamelCase : Optional[Any] = { 'visual_embedding_dim': 10_24, 'num_labels': 2, } _lowerCamelCase : Any = 'nlvr' _lowerCamelCase : Any = VisualBertConfig(**lowerCamelCase__ ) # Load State Dict _lowerCamelCase : Dict = load_state_dict(lowerCamelCase__ ) _lowerCamelCase : Optional[Any] = get_new_dict(lowerCamelCase__, lowerCamelCase__ ) if model_type == "pretraining": _lowerCamelCase : Union[str, Any] = VisualBertForPreTraining(lowerCamelCase__ ) elif model_type == "vqa": _lowerCamelCase : str = VisualBertForQuestionAnswering(lowerCamelCase__ ) elif model_type == "nlvr": _lowerCamelCase : Dict = VisualBertForVisualReasoning(lowerCamelCase__ ) elif model_type == "multichoice": _lowerCamelCase : Union[str, Any] = VisualBertForMultipleChoice(lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) # Save Checkpoints Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) model.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase__ = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
72
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = 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__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' from __future__ import annotations import time __snake_case = list[tuple[int, int]] __snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Tuple = pos_x UpperCamelCase__ :List[str] = pos_y UpperCamelCase__ :str = (pos_y, pos_x) UpperCamelCase__ :str = goal_x UpperCamelCase__ :int = goal_y UpperCamelCase__ :List[Any] = parent class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Any = Node(start[1] , start[0] , goal[1] , goal[0] , SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :List[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Union[str, Any] = [self.start] UpperCamelCase__ :List[str] = False def lowerCAmelCase__ ( self ): '''simple docstring''' while self.node_queue: UpperCamelCase__ :Any = self.node_queue.pop(0 ) if current_node.pos == self.target.pos: UpperCamelCase__ :Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Tuple = self.get_successors(SCREAMING_SNAKE_CASE__ ) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__ ) if not self.reached: return [self.start.pos] return None def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = [] for action in delta: UpperCamelCase__ :Optional[Any] = parent.pos_x + action[1] UpperCamelCase__ :Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.target.pos_y , self.target.pos_x , SCREAMING_SNAKE_CASE__ ) ) return successors def lowerCAmelCase__ ( self , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = node UpperCamelCase__ :int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) UpperCamelCase__ :int = current_node.parent path.reverse() return path class lowercase : """simple docstring""" def __init__( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[Any] = False def lowerCAmelCase__ ( self ): '''simple docstring''' while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: UpperCamelCase__ :Any = self.fwd_bfs.node_queue.pop(0 ) UpperCamelCase__ :Any = self.bwd_bfs.node_queue.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: UpperCamelCase__ :List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :Optional[Any] = current_bwd_node UpperCamelCase__ :int = current_fwd_node UpperCamelCase__ :str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__ ), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__ ), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__ ) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ :List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__ ) UpperCamelCase__ :str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__ ) bwd_path.pop() bwd_path.reverse() UpperCamelCase__ :List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() __snake_case = (0, 0) __snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __snake_case = time.time() __snake_case = BreadthFirstSearch(init, goal) __snake_case = bfs.search() __snake_case = time.time() - start_bfs_time print('''Unidirectional BFS computation time : ''', bfs_time) __snake_case = time.time() __snake_case = BidirectionalBreadthFirstSearch(init, goal) __snake_case = bd_bfs.search() __snake_case = time.time() - start_bd_bfs_time print('''Bidirectional BFS computation time : ''', bd_bfs_time)
97
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0
import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=13 , __magic_name__=32 , __magic_name__=2 , __magic_name__=3 , __magic_name__=16 , __magic_name__=[1, 2, 1] , __magic_name__=[2, 2, 4] , __magic_name__=2 , __magic_name__=2.0 , __magic_name__=True , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.1 , __magic_name__="gelu" , __magic_name__=False , __magic_name__=True , __magic_name__=0.02 , __magic_name__=1e-5 , __magic_name__=True , __magic_name__=None , __magic_name__=True , __magic_name__=10 , __magic_name__=8 , ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = parent snake_case_ : Union[str, Any] = batch_size snake_case_ : List[Any] = image_size snake_case_ : Optional[Any] = patch_size snake_case_ : int = num_channels snake_case_ : Dict = embed_dim snake_case_ : List[Any] = depths snake_case_ : Optional[Any] = num_heads snake_case_ : Tuple = window_size snake_case_ : Tuple = mlp_ratio snake_case_ : Dict = qkv_bias snake_case_ : int = hidden_dropout_prob snake_case_ : List[Any] = attention_probs_dropout_prob snake_case_ : Tuple = drop_path_rate snake_case_ : str = hidden_act snake_case_ : Optional[Any] = use_absolute_embeddings snake_case_ : str = patch_norm snake_case_ : Optional[int] = layer_norm_eps snake_case_ : Optional[Any] = initializer_range snake_case_ : int = is_training snake_case_ : str = scope snake_case_ : int = use_labels snake_case_ : int = type_sequence_label_size snake_case_ : int = encoder_stride def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' snake_case_ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ : int = None if self.use_labels: snake_case_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ : Union[str, Any] = self.get_config() return config, pixel_values, labels def lowerCamelCase (self ) -> List[str]: '''simple docstring''' return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : Tuple = SwinvaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case_ : Tuple = model(SCREAMING_SNAKE_CASE__ ) snake_case_ : Any = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case_ : List[str] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> int: '''simple docstring''' snake_case_ : List[str] = SwinvaForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case_ : Optional[int] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images snake_case_ : Tuple = 1 snake_case_ : Union[str, Any] = SwinvaForMaskedImageModeling(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case_ : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ : Dict = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[Any] = self.type_sequence_label_size snake_case_ : Optional[int] = SwinvaForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() snake_case_ : int = model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' snake_case_ : Any = self.prepare_config_and_inputs() snake_case_ : Union[str, Any] = config_and_inputs snake_case_ : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase ( _a, _a, unittest.TestCase ): lowerCamelCase_ : Optional[Any] = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase_ : Tuple = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ : Dict = False lowerCamelCase_ : List[Any] = False lowerCamelCase_ : Union[str, Any] = False lowerCamelCase_ : Any = False def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[Any] = SwinvaModelTester(self ) snake_case_ : Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , embed_dim=37 ) def lowerCamelCase (self ) -> int: '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''' ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' pass @unittest.skip(reason='''Swinv2 does not use inputs_embeds''' ) def lowerCamelCase (self ) -> List[Any]: '''simple docstring''' pass def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Optional[Any] = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case_ : List[str] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ : Optional[Any] = model_class(SCREAMING_SNAKE_CASE__ ) snake_case_ : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ : Optional[Any] = [*signature.parameters.keys()] snake_case_ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ : Tuple = True for model_class in self.all_model_classes: snake_case_ : str = True snake_case_ : List[str] = False snake_case_ : List[str] = True snake_case_ : List[str] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): snake_case_ : Union[str, Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) snake_case_ : Optional[Any] = outputs.attentions snake_case_ : Tuple = len(self.model_tester.depths ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case_ : Dict = True snake_case_ : int = config.window_size**2 snake_case_ : List[str] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): snake_case_ : str = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) snake_case_ : Optional[Any] = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) snake_case_ : Dict = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine snake_case_ : Optional[Any] = True snake_case_ : List[Any] = True snake_case_ : Tuple = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): snake_case_ : Tuple = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if hasattr(self.model_tester , '''num_hidden_states_types''' ): snake_case_ : int = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states snake_case_ : List[str] = 2 self.assertEqual(out_len + added_hidden_states , len(SCREAMING_SNAKE_CASE__ ) ) snake_case_ : Optional[Any] = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def lowerCamelCase (self , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) -> List[str]: '''simple docstring''' snake_case_ : int = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): snake_case_ : Dict = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) snake_case_ : Dict = outputs.hidden_states snake_case_ : List[str] = getattr( self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) # Swinv2 has a different seq_length snake_case_ : Optional[Any] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ : int = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) snake_case_ : int = outputs.reshaped_hidden_states self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) snake_case_ : Tuple = reshaped_hidden_states[0].shape snake_case_ : Union[str, Any] = ( reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def lowerCamelCase (self ) -> Optional[Any]: '''simple docstring''' snake_case_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ : int = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: snake_case_ : List[Any] = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ : Optional[int] = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ : int = 3 snake_case_ : List[str] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) snake_case_ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case_ : List[Any] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case_ : Optional[int] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case_ : str = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case_ : List[Any] = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , (padded_height, padded_width) ) def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> Any: '''simple docstring''' snake_case_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def lowerCamelCase (self ) -> Any: '''simple docstring''' for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ : Optional[int] = SwinvaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' snake_case_ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ : int = _config_zero_init(SCREAMING_SNAKE_CASE__ ) for model_class in self.all_model_classes: snake_case_ : List[Any] = model_class(config=SCREAMING_SNAKE_CASE__ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class __lowerCAmelCase ( unittest.TestCase ): @cached_property def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return ( AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ) if is_vision_available() else None ) @slow def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : List[str] = SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to( SCREAMING_SNAKE_CASE__ ) snake_case_ : List[Any] = self.default_image_processor snake_case_ : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) snake_case_ : List[str] = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): snake_case_ : List[str] = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits snake_case_ : Tuple = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[Any] = torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
279
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue_model_parallelism.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''roberta-large''', '''instance_type''': '''ml.p3dn.24xlarge''', '''results''': {'''train_runtime''': 1_600, '''eval_accuracy''': 0.3, '''eval_loss''': 1.2}, }, ] ) class A_ ( unittest.TestCase ): def lowerCAmelCase ( self : Union[str, Any]): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() ,encoding='utf-8' ,check=SCREAMING_SNAKE_CASE__ ,) assert hasattr(self ,'env') def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : int): # configuration for running training on smdistributed Model Parallel __lowerCamelCase : Any = { 'enabled': True, 'processes_per_host': 8, } __lowerCamelCase : List[Any] = { 'enabled': True, 'parameters': { 'microbatches': 4, 'placement_strategy': 'spread', 'pipeline': 'interleaved', 'optimize': 'speed', 'partitions': 4, 'ddp': True, }, } __lowerCamelCase : str = {'smdistributed': {'modelparallel': smp_options}, 'mpi': mpi_options} __lowerCamelCase : List[str] = 'trainer' if self.script == 'run_glue.py' else 'smtrainer' # creates estimator return HuggingFace( entry_point=self.script ,source_dir=self.env.test_path ,role=self.env.role ,image_uri=self.env.image_uri ,base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" ,instance_count=SCREAMING_SNAKE_CASE__ ,instance_type=self.instance_type ,debugger_hook_config=SCREAMING_SNAKE_CASE__ ,hyperparameters={ **self.env.hyperparameters, 'model_name_or_path': self.model_name_or_path, 'max_steps': 5_0_0, } ,metric_definitions=self.env.metric_definitions ,distribution=SCREAMING_SNAKE_CASE__ ,py_version='py36' ,) def lowerCAmelCase ( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Any): TrainingJobAnalytics(SCREAMING_SNAKE_CASE__).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv") @parameterized.expand([(1,)]) def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Any]): # create estimator __lowerCamelCase : str = self.create_estimator(SCREAMING_SNAKE_CASE__) # run training estimator.fit() # result dataframe __lowerCamelCase : List[str] = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() # extract kpis __lowerCamelCase : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == 'eval_accuracy']['value']) __lowerCamelCase : Any = list(result_metrics_df[result_metrics_df.metric_name == 'eval_loss']['value']) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase : str = ( Session().describe_training_job(estimator.latest_training_job.name).get('TrainingTimeInSeconds' ,9_9_9_9_9_9) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['eval_accuracy'] for t in eval_accuracy) assert all(t <= self.results['eval_loss'] for t in eval_loss) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" ,'w') as outfile: json.dump({'train_time': train_runtime, 'eval_accuracy': eval_accuracy, 'eval_loss': eval_loss} ,SCREAMING_SNAKE_CASE__)
73
0
'''simple docstring''' import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def __magic_name__( ): __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''-m''', '''--pretrained_model_name_or_path''', type=lowerCamelCase__, default=lowerCamelCase__, required=lowerCamelCase__, help='''Path to pretrained model or model identifier from huggingface.co/models.''', ) parser.add_argument( '''-c''', '''--caption''', type=lowerCamelCase__, default='''robotic cat with wings''', help='''Text used to generate images.''', ) parser.add_argument( '''-n''', '''--images_num''', type=lowerCamelCase__, default=4, help='''How much images to generate.''', ) parser.add_argument( '''-s''', '''--seed''', type=lowerCamelCase__, default=4_2, help='''Seed for random process.''', ) parser.add_argument( '''-ci''', '''--cuda_id''', type=lowerCamelCase__, default=0, help='''cuda_id.''', ) __lowerCAmelCase = parser.parse_args() return args def __magic_name__( lowerCamelCase, lowerCamelCase, lowerCamelCase): if not len(lowerCamelCase__) == rows * cols: raise ValueError('''The specified number of rows and columns are not correct.''') __lowerCAmelCase = imgs[0].size __lowerCAmelCase = Image.new('''RGB''', size=(cols * w, rows * h)) __lowerCAmelCase = grid.size for i, img in enumerate(lowerCamelCase__): grid.paste(lowerCamelCase__, box=(i % cols * w, i // cols * h)) return grid def __magic_name__( lowerCamelCase, lowerCamelCase="robotic cat with wings", lowerCamelCase=7.5, lowerCamelCase=5_0, lowerCamelCase=1, lowerCamelCase=4_2, ): __lowerCAmelCase = torch.Generator(pipeline.device).manual_seed(lowerCamelCase__) __lowerCAmelCase = pipeline( lowerCamelCase__, guidance_scale=lowerCamelCase__, num_inference_steps=lowerCamelCase__, generator=lowerCamelCase__, num_images_per_prompt=lowerCamelCase__, ).images __lowerCAmelCase = int(math.sqrt(lowerCamelCase__)) __lowerCAmelCase = image_grid(lowerCamelCase__, rows=_rows, cols=num_images_per_prompt // _rows) return grid, images _UpperCAmelCase : Tuple = parse_args() # Load models and create wrapper for stable diffusion _UpperCAmelCase : List[str] = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder="""tokenizer""") _UpperCAmelCase : Any = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""text_encoder""") _UpperCAmelCase : str = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="""vae""") _UpperCAmelCase : List[str] = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="""unet""") _UpperCAmelCase : Any = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) _UpperCAmelCase : Optional[int] = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, """best_model.pt""")): _UpperCAmelCase : Any = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, """unet""", unet) else: _UpperCAmelCase : int = unet.to(torch.device("""cuda""", args.cuda_id)) _UpperCAmelCase : Dict = pipeline.to(unet.device) _UpperCAmelCase ,_UpperCAmelCase : Dict = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, """{}.png""".format("""_""".join(args.caption.split())))) _UpperCAmelCase : Optional[Any] = os.path.join(args.pretrained_model_name_or_path, """_""".join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, """{}.png""".format(idx + 1)))
174
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class A_ ( unittest.TestCase ): def __init__( self : Tuple ,SCREAMING_SNAKE_CASE__ : List[str] ,SCREAMING_SNAKE_CASE__ : Any=1_3 ,SCREAMING_SNAKE_CASE__ : int=7 ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : Dict=True ,SCREAMING_SNAKE_CASE__ : List[Any]=9_9 ,SCREAMING_SNAKE_CASE__ : List[Any]=3_2 ,SCREAMING_SNAKE_CASE__ : int=5 ,SCREAMING_SNAKE_CASE__ : List[Any]=4 ,SCREAMING_SNAKE_CASE__ : Optional[Any]=3_7 ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="gelu" ,SCREAMING_SNAKE_CASE__ : int=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 ,SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 ,SCREAMING_SNAKE_CASE__ : Dict=1_6 ,SCREAMING_SNAKE_CASE__ : Dict=2 ,SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 ,SCREAMING_SNAKE_CASE__ : Dict=4 ,): __lowerCamelCase : int = parent __lowerCamelCase : Dict = batch_size __lowerCamelCase : Union[str, Any] = seq_length __lowerCamelCase : List[Any] = is_training __lowerCamelCase : Tuple = use_attention_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : Any = use_labels __lowerCamelCase : List[str] = vocab_size __lowerCamelCase : Any = hidden_size __lowerCamelCase : Tuple = num_hidden_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : int = hidden_dropout_prob __lowerCamelCase : int = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : Union[str, Any] = type_vocab_size __lowerCamelCase : List[str] = type_sequence_label_size __lowerCamelCase : Tuple = initializer_range __lowerCamelCase : Optional[int] = num_choices def lowerCAmelCase ( self : Union[str, Any]): __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Any = random_attention_mask([self.batch_size, self.seq_length]) __lowerCamelCase : str = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=SCREAMING_SNAKE_CASE__ ,) return config, input_ids, attention_mask def lowerCAmelCase ( self : List[Any]): __lowerCamelCase : List[str] = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = config_and_inputs __lowerCamelCase : Any = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class A_ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): _UpperCAmelCase : Dict = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Tuple = FlaxDistilBertModelTester(self) @slow def lowerCAmelCase ( self : int): for model_class_name in self.all_model_classes: __lowerCamelCase : List[Any] = model_class_name.from_pretrained('distilbert-base-uncased') __lowerCamelCase : List[str] = model(np.ones((1, 1))) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) @require_flax class A_ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : str): __lowerCamelCase : Union[str, Any] = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased') __lowerCamelCase : str = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]) __lowerCamelCase : List[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) __lowerCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ,attention_mask=SCREAMING_SNAKE_CASE__)[0] __lowerCamelCase : Optional[int] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,SCREAMING_SNAKE_CASE__ ,atol=1E-4))
73
0
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() snake_case_ : Optional[int] = logging.get_logger(__name__) def A (__A : Any , __A : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F"""encoder.deit.blocks.{i}.norm1.weight""", F"""encoder.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""encoder.deit.blocks.{i}.norm1.bias""", F"""encoder.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.attn.proj.weight""", F"""encoder.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.attn.proj.bias""", F"""encoder.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.norm2.weight""", F"""encoder.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""encoder.deit.blocks.{i}.norm2.bias""", F"""encoder.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.mlp.fc1.weight""", F"""encoder.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.mlp.fc1.bias""", F"""encoder.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append( (F"""encoder.deit.blocks.{i}.mlp.fc2.weight""", F"""encoder.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""encoder.deit.blocks.{i}.mlp.fc2.bias""", F"""encoder.encoder.layer.{i}.output.dense.bias""") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ('''encoder.deit.cls_token''', '''encoder.embeddings.cls_token'''), ('''encoder.deit.pos_embed''', '''encoder.embeddings.position_embeddings'''), ('''encoder.deit.patch_embed.proj.weight''', '''encoder.embeddings.patch_embeddings.projection.weight'''), ('''encoder.deit.patch_embed.proj.bias''', '''encoder.embeddings.patch_embeddings.projection.bias'''), ('''encoder.deit.norm.weight''', '''encoder.layernorm.weight'''), ('''encoder.deit.norm.bias''', '''encoder.layernorm.bias'''), ] ) return rename_keys def A (__A : Optional[int] , __A : Union[str, Any] ) -> Dict: """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) UpperCAmelCase_ = state_dict.pop(F"""encoder.deit.blocks.{i}.attn.qkv.weight""" ) UpperCAmelCase_ = in_proj_weight[ : encoder_config.hidden_size, : ] UpperCAmelCase_ = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] UpperCAmelCase_ = in_proj_weight[ -encoder_config.hidden_size :, : ] def A (__A : Optional[int] , __A : Optional[Any] , __A : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ = dct.pop(lowerCamelCase__ ) UpperCAmelCase_ = val def A (__A : Optional[Any] ) -> List[str]: """simple docstring""" if "handwritten" in checkpoint_url: UpperCAmelCase_ = 'https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg' # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCAmelCase_ = 'https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg' UpperCAmelCase_ = Image.open(requests.get(lowerCamelCase__ , stream=lowerCamelCase__ ).raw ).convert('''RGB''' ) return im @torch.no_grad() def A (__A : Optional[Any] , __A : Optional[int] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ = ViTConfig(image_size=384 , qkv_bias=lowerCamelCase__ ) UpperCAmelCase_ = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: UpperCAmelCase_ = 768 elif "large" in checkpoint_url: # use ViT-large encoder UpperCAmelCase_ = 1024 UpperCAmelCase_ = 4096 UpperCAmelCase_ = 24 UpperCAmelCase_ = 16 UpperCAmelCase_ = 1024 else: raise ValueError('''Should either find \'base\' or \'large\' in checkpoint URL''' ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: UpperCAmelCase_ = False UpperCAmelCase_ = 'relu' UpperCAmelCase_ = 1024 UpperCAmelCase_ = True UpperCAmelCase_ = False UpperCAmelCase_ = False # load HuggingFace model UpperCAmelCase_ = ViTModel(lowerCamelCase__ , add_pooling_layer=lowerCamelCase__ ) UpperCAmelCase_ = TrOCRForCausalLM(lowerCamelCase__ ) UpperCAmelCase_ = VisionEncoderDecoderModel(encoder=lowerCamelCase__ , decoder=lowerCamelCase__ ) model.eval() # load state_dict of original model, rename some keys UpperCAmelCase_ = torch.hub.load_state_dict_from_url(lowerCamelCase__ , map_location='''cpu''' , check_hash=lowerCamelCase__ )['model'] UpperCAmelCase_ = create_rename_keys(lowerCamelCase__ , lowerCamelCase__ ) for src, dest in rename_keys: rename_key(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) read_in_q_k_v(lowerCamelCase__ , lowerCamelCase__ ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): UpperCAmelCase_ = state_dict.pop(lowerCamelCase__ ) if key.startswith('''decoder''' ) and "output_projection" not in key: UpperCAmelCase_ = val else: UpperCAmelCase_ = val # load state dict model.load_state_dict(lowerCamelCase__ ) # Check outputs on an image UpperCAmelCase_ = ViTImageProcessor(size=encoder_config.image_size ) UpperCAmelCase_ = RobertaTokenizer.from_pretrained('''roberta-large''' ) UpperCAmelCase_ = TrOCRProcessor(lowerCamelCase__ , lowerCamelCase__ ) UpperCAmelCase_ = processor(images=prepare_img(lowerCamelCase__ ) , return_tensors='''pt''' ).pixel_values # verify logits UpperCAmelCase_ = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) UpperCAmelCase_ = model(pixel_values=lowerCamelCase__ , decoder_input_ids=lowerCamelCase__ ) UpperCAmelCase_ = outputs.logits UpperCAmelCase_ = torch.Size([1, 1, 50265] ) if "trocr-base-handwritten" in checkpoint_url: UpperCAmelCase_ = torch.tensor( [-1.4_502, -4.6_683, -0.5_347, -2.9_291, 9.1_435, -3.0_571, 8.9_764, 1.7_560, 8.7_358, -1.5_311] ) elif "trocr-large-handwritten" in checkpoint_url: UpperCAmelCase_ = torch.tensor( [-2.6_437, -1.3_129, -2.2_596, -5.3_455, 6.3_539, 1.7_604, 5.4_991, 1.4_702, 5.6_113, 2.0_170] ) elif "trocr-base-printed" in checkpoint_url: UpperCAmelCase_ = torch.tensor( [-5.6_816, -5.8_388, 1.1_398, -6.9_034, 6.8_505, -2.4_393, 1.2_284, -1.0_232, -1.9_661, -3.9_210] ) elif "trocr-large-printed" in checkpoint_url: UpperCAmelCase_ = torch.tensor( [-6.0_162, -7.0_959, 4.4_155, -5.1_063, 7.0_468, -3.1_631, 2.6_466, -0.3_081, -0.8_106, -1.7_535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , lowerCamelCase__ , atol=1E-3 ), "First elements of logits not as expected" Path(lowerCamelCase__ ).mkdir(exist_ok=lowerCamelCase__ ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCamelCase__ ) print(F"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": snake_case_ : List[Any] = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt", 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." ) snake_case_ : Union[str, Any] = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
51
import csv import tweepy # Twitter API credentials a ="""""" a ="""""" a ="""""" a ="""""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: # authorize twitter, initialize tweepy __lowerCamelCase : Tuple = tweepy.OAuthHandler(lowerCamelCase__ , lowerCamelCase__ ) auth.set_access_token(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Optional[int] = tweepy.API(lowerCamelCase__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : str = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : Union[str, Any] = api.user_timeline(screen_name=lowerCamelCase__ , count=2_0_0 ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # save the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(lowerCamelCase__ ) > 0: print(F"getting tweets before {oldest}" ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : str = api.user_timeline( screen_name=lowerCamelCase__ , count=2_0_0 , max_id=lowerCamelCase__ ) # save most recent tweets alltweets.extend(lowerCamelCase__ ) # update the id of the oldest tweet less one __lowerCamelCase : Optional[int] = alltweets[-1].id - 1 print(F"...{len(lowerCamelCase__ )} tweets downloaded so far" ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : str = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] # write the csv with open(F"new_{screen_name}_tweets.csv" , 'w' ) as f: __lowerCamelCase : Any = csv.writer(lowerCamelCase__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(lowerCamelCase__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets("""FirePing32""")
73
0
import numpy as np import datasets __snake_case = """ Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ __snake_case = """\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ __snake_case = """ Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase__ ( datasets.Metric ): def A_ ( self : List[str] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'X': datasets.Sequence(datasets.Value('float' , id='sequence' ) , id='X' ), } ) , ) def A_ ( self : Union[str, Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : List[Any] ): # convert to numpy arrays SCREAMING_SNAKE_CASE__ = np.array(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ = np.array(SCREAMING_SNAKE_CASE__ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('Expected `X` to be a 2D vector' ) if len(reference_distribution.shape ) != 2: raise ValueError('Expected `reference_distribution` to be a 2D vector' ) if reference_distribution.shape[0] < 2: raise ValueError( 'Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension' ) # Get mahalanobis distance for each prediction SCREAMING_SNAKE_CASE__ = X - np.mean(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ = np.cov(reference_distribution.T ) try: SCREAMING_SNAKE_CASE__ = np.linalg.inv(SCREAMING_SNAKE_CASE__ ) except np.linalg.LinAlgError: SCREAMING_SNAKE_CASE__ = np.linalg.pinv(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ = np.dot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ = np.dot(SCREAMING_SNAKE_CASE__ , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
176
import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets a ="""\ @inproceedings{kakwani2020indicnlpsuite, title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}}, author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, year={2020}, booktitle={Findings of EMNLP}, } """ a ="""\ IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te. """ a =""" Compute IndicGLUE evaluation metric associated to each IndicGLUE dataset. Args: predictions: list of predictions to score (as int64), except for 'cvit-mkb-clsr' where each prediction is a vector (of float32). references: list of ground truth labels corresponding to the predictions (as int64), except for 'cvit-mkb-clsr' where each reference is a vector (of float32). Returns: depending on the IndicGLUE subset, one or several of: \"accuracy\": Accuracy \"f1\": F1 score \"precision\": Precision@10 Examples: >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"] >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'accuracy': 1.0, 'f1': 1.0} >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr') >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]] >>> results = indic_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {'precision@10': 1.0} """ def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return float((preds == labels).mean() ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: __lowerCamelCase : Optional[Any] = simple_accuracy(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Tuple = float(fa_score(y_true=lowerCamelCase__ , y_pred=lowerCamelCase__ ) ) return { "accuracy": acc, "f1": fa, } def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[Any]: __lowerCamelCase : Any = np.array(lowerCamelCase__ ) __lowerCamelCase : List[Any] = np.array(lowerCamelCase__ ) __lowerCamelCase : Any = en_sentvecs.shape[0] # mean centering __lowerCamelCase : Union[str, Any] = en_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Dict = in_sentvecs - np.mean(lowerCamelCase__ , axis=0 ) __lowerCamelCase : Optional[int] = cdist(lowerCamelCase__ , lowerCamelCase__ , 'cosine' ) __lowerCamelCase : Optional[Any] = np.array(range(lowerCamelCase__ ) ) __lowerCamelCase : Dict = sim.argsort(axis=1 )[:, :1_0] __lowerCamelCase : Optional[int] = np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): def lowerCAmelCase ( self : Optional[Any]): if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]') return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), 'references': datasets.Value('int64') if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32')), }) ,codebase_urls=[] ,reference_urls=[] ,format='numpy' if self.config_name != 'cvit-mkb-clsr' else None ,) def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : Tuple ,SCREAMING_SNAKE_CASE__ : Optional[Any]): if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} elif self.config_name in ["wiki-ner"]: return acc_and_fa(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]')
73
0
__lowerCAmelCase : Optional[Any] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
107
from __future__ import annotations from scipy.special import comb # type: ignore class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : list[tuple[float, float]]): __lowerCamelCase : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. __lowerCamelCase : int = len(SCREAMING_SNAKE_CASE__) - 1 def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree ,SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) ,5) == 1 return output_values def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : float): assert 0 <= t <= 1, "Time t must be between 0 and 1." __lowerCamelCase : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = 0.0 __lowerCamelCase : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def lowerCAmelCase ( self : int ,SCREAMING_SNAKE_CASE__ : float = 0.01): from matplotlib import pyplot as plt # type: ignore __lowerCamelCase : list[float] = [] # x coordinates of points to plot __lowerCamelCase : list[float] = [] # y coordinates of points to plot __lowerCamelCase : Any = 0.0 while t <= 1: __lowerCamelCase : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size __lowerCamelCase : Optional[Any] = [i[0] for i in self.list_of_points] __lowerCamelCase : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='blue' ,label='Curve of Degree ' + str(self.degree) ,) plt.scatter(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,color='red' ,label='Control Points') plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
73
0
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def __lowerCamelCase ( snake_case__ ) -> Optional[int]: """simple docstring""" if "cls_token" in name: _SCREAMING_SNAKE_CASE = name.replace("""cls_token""" ,"""vit.embeddings.cls_token""" ) if "mask_token" in name: _SCREAMING_SNAKE_CASE = name.replace("""mask_token""" ,"""decoder.mask_token""" ) if "decoder_pos_embed" in name: _SCREAMING_SNAKE_CASE = name.replace("""decoder_pos_embed""" ,"""decoder.decoder_pos_embed""" ) if "pos_embed" in name and "decoder" not in name: _SCREAMING_SNAKE_CASE = name.replace("""pos_embed""" ,"""vit.embeddings.position_embeddings""" ) if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" ,"""vit.embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: _SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" ,"""vit.embeddings.norm""" ) if "decoder_blocks" in name: _SCREAMING_SNAKE_CASE = name.replace("""decoder_blocks""" ,"""decoder.decoder_layers""" ) if "blocks" in name: _SCREAMING_SNAKE_CASE = name.replace("""blocks""" ,"""vit.encoder.layer""" ) if "attn.proj" in name: _SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" ,"""attention.output.dense""" ) if "attn" in name: _SCREAMING_SNAKE_CASE = name.replace("""attn""" ,"""attention.self""" ) if "norm1" in name: _SCREAMING_SNAKE_CASE = name.replace("""norm1""" ,"""layernorm_before""" ) if "norm2" in name: _SCREAMING_SNAKE_CASE = name.replace("""norm2""" ,"""layernorm_after""" ) if "mlp.fc1" in name: _SCREAMING_SNAKE_CASE = name.replace("""mlp.fc1""" ,"""intermediate.dense""" ) if "mlp.fc2" in name: _SCREAMING_SNAKE_CASE = name.replace("""mlp.fc2""" ,"""output.dense""" ) if "decoder_embed" in name: _SCREAMING_SNAKE_CASE = name.replace("""decoder_embed""" ,"""decoder.decoder_embed""" ) if "decoder_norm" in name: _SCREAMING_SNAKE_CASE = name.replace("""decoder_norm""" ,"""decoder.decoder_norm""" ) if "decoder_pred" in name: _SCREAMING_SNAKE_CASE = name.replace("""decoder_pred""" ,"""decoder.decoder_pred""" ) if "norm.weight" in name and "decoder" not in name: _SCREAMING_SNAKE_CASE = name.replace("""norm.weight""" ,"""vit.layernorm.weight""" ) if "norm.bias" in name and "decoder" not in name: _SCREAMING_SNAKE_CASE = name.replace("""norm.bias""" ,"""vit.layernorm.bias""" ) return name def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> List[Any]: """simple docstring""" for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE = orig_state_dict.pop(lowerCamelCase__ ) if "qkv" in key: _SCREAMING_SNAKE_CASE = key.split(""".""" ) _SCREAMING_SNAKE_CASE = int(key_split[1] ) if "decoder_blocks" in key: _SCREAMING_SNAKE_CASE = config.decoder_hidden_size _SCREAMING_SNAKE_CASE = 'decoder.decoder_layers.' if "weight" in key: _SCREAMING_SNAKE_CASE = val[:dim, :] _SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] _SCREAMING_SNAKE_CASE = val[-dim:, :] elif "bias" in key: _SCREAMING_SNAKE_CASE = val[:dim] _SCREAMING_SNAKE_CASE = val[dim : dim * 2] _SCREAMING_SNAKE_CASE = val[-dim:] else: _SCREAMING_SNAKE_CASE = config.hidden_size _SCREAMING_SNAKE_CASE = 'vit.encoder.layer.' if "weight" in key: _SCREAMING_SNAKE_CASE = val[:dim, :] _SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] _SCREAMING_SNAKE_CASE = val[-dim:, :] elif "bias" in key: _SCREAMING_SNAKE_CASE = val[:dim] _SCREAMING_SNAKE_CASE = val[dim : dim * 2] _SCREAMING_SNAKE_CASE = val[-dim:] else: _SCREAMING_SNAKE_CASE = val return orig_state_dict def __lowerCamelCase ( snake_case__ ,snake_case__ ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = ViTMAEConfig() if "large" in checkpoint_url: _SCREAMING_SNAKE_CASE = 10_24 _SCREAMING_SNAKE_CASE = 40_96 _SCREAMING_SNAKE_CASE = 24 _SCREAMING_SNAKE_CASE = 16 elif "huge" in checkpoint_url: _SCREAMING_SNAKE_CASE = 14 _SCREAMING_SNAKE_CASE = 12_80 _SCREAMING_SNAKE_CASE = 51_20 _SCREAMING_SNAKE_CASE = 32 _SCREAMING_SNAKE_CASE = 16 _SCREAMING_SNAKE_CASE = ViTMAEForPreTraining(lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(lowerCamelCase__ ,map_location="""cpu""" )['model'] _SCREAMING_SNAKE_CASE = ViTMAEImageProcessor(size=config.image_size ) _SCREAMING_SNAKE_CASE = convert_state_dict(lowerCamelCase__ ,lowerCamelCase__ ) model.load_state_dict(lowerCamelCase__ ) model.eval() _SCREAMING_SNAKE_CASE = 'https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg' _SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCamelCase__ ,stream=lowerCamelCase__ ).raw ) _SCREAMING_SNAKE_CASE = ViTMAEImageProcessor(size=config.image_size ) _SCREAMING_SNAKE_CASE = image_processor(images=lowerCamelCase__ ,return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _SCREAMING_SNAKE_CASE = model(**lowerCamelCase__ ) _SCREAMING_SNAKE_CASE = outputs.logits if "large" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [[-0.7_309, -0.7_128, -1.0_169], [-1.0_161, -0.9_058, -1.1_878], [-1.0_478, -0.9_411, -1.1_911]] ) elif "huge" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor( [[-1.1_599, -0.9_199, -1.2_221], [-1.1_952, -0.9_269, -1.2_307], [-1.2_143, -0.9_337, -1.2_262]] ) else: _SCREAMING_SNAKE_CASE = torch.tensor( [[-0.9_192, -0.8_481, -1.1_259], [-1.1_349, -1.0_034, -1.2_599], [-1.1_757, -1.0_429, -1.2_726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCamelCase__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) UpperCamelCase = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
306
from __future__ import annotations import time a =list[tuple[int, int]] a =[ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] a =[[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right class A_ : def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : int ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : Tuple = pos_x __lowerCamelCase : List[str] = pos_y __lowerCamelCase : str = (pos_y, pos_x) __lowerCamelCase : str = goal_x __lowerCamelCase : int = goal_y __lowerCamelCase : List[Any] = parent class A_ : def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : tuple[int, int] ,SCREAMING_SNAKE_CASE__ : tuple[int, int]): __lowerCamelCase : Any = Node(start[1] ,start[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = Node(goal[1] ,goal[0] ,goal[1] ,goal[0] ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = [self.start] __lowerCamelCase : List[str] = False def lowerCAmelCase ( self : List[Any]): while self.node_queue: __lowerCamelCase : Any = self.node_queue.pop(0) if current_node.pos == self.target.pos: __lowerCamelCase : Dict = True return self.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = self.get_successors(SCREAMING_SNAKE_CASE__) for node in successors: self.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : Union[str, Any] = [] for action in delta: __lowerCamelCase : Optional[Any] = parent.pos_x + action[1] __lowerCamelCase : Optional[int] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,self.target.pos_y ,self.target.pos_x ,SCREAMING_SNAKE_CASE__)) return successors def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Node | None): __lowerCamelCase : List[Any] = node __lowerCamelCase : int = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x)) __lowerCamelCase : int = current_node.parent path.reverse() return path class A_ : def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : int = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = BreadthFirstSearch(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = False def lowerCAmelCase ( self : str): while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue: __lowerCamelCase : Any = self.fwd_bfs.node_queue.pop(0) __lowerCamelCase : Any = self.bwd_bfs.node_queue.pop(0) if current_bwd_node.pos == current_fwd_node.pos: __lowerCamelCase : List[str] = True return self.retrace_bidirectional_path( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[Any] = current_bwd_node __lowerCamelCase : int = current_fwd_node __lowerCamelCase : str = { self.fwd_bfs: self.fwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), self.bwd_bfs: self.bwd_bfs.get_successors(SCREAMING_SNAKE_CASE__), } for bfs in [self.fwd_bfs, self.bwd_bfs]: for node in successors[bfs]: bfs.node_queue.append(SCREAMING_SNAKE_CASE__) if not self.reached: return [self.fwd_bfs.start.pos] return None def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Node ,SCREAMING_SNAKE_CASE__ : Node): __lowerCamelCase : List[Any] = self.fwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = self.bwd_bfs.retrace_path(SCREAMING_SNAKE_CASE__) bwd_path.pop() bwd_path.reverse() __lowerCamelCase : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] import doctest doctest.testmod() a =(0, 0) a =(len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) a =time.time() a =BreadthFirstSearch(init, goal) a =bfs.search() a =time.time() - start_bfs_time print("""Unidirectional BFS computation time : """, bfs_time) a =time.time() a =BidirectionalBreadthFirstSearch(init, goal) a =bd_bfs.search() a =time.time() - start_bd_bfs_time print("""Bidirectional BFS computation time : """, bd_bfs_time)
73
0
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ = """ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = \"A Call for Clarity in Reporting {BLEU} Scores\", author = \"Post, Matt\", booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\", month = oct, year = \"2018\", address = \"Belgium, Brussels\", publisher = \"Association for Computational Linguistics\", url = \"https://www.aclweb.org/anthology/W18-6319\", pages = \"186--191\", } """ a__ = """\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. """ a__ = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=[\"About 95 species are currently accepted .\"] >>> predictions=[\"About 95 you now get in .\"] >>> references=[[\"About 95 species are currently known .\"]] >>> wiki_split = datasets.load_metric(\"wiki_split\") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0} """ def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: def remove_articles(SCREAMING_SNAKE_CASE__ : int ): _snake_case : Dict = re.compile(R"""\b(a|an|the)\b""" , re.UNICODE ) return re.sub(lowerCamelCase__ , """ """ , lowerCamelCase__ ) def white_space_fix(SCREAMING_SNAKE_CASE__ : List[Any] ): return " ".join(text.split() ) def remove_punc(SCREAMING_SNAKE_CASE__ : Dict ): _snake_case : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(SCREAMING_SNAKE_CASE__ : List[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__ ) ) ) ) def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: return int(normalize_answer(lowerCamelCase__ ) == normalize_answer(lowerCamelCase__ ) ) def lowercase ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: _snake_case : Union[str, Any] = [any(compute_exact(lowerCamelCase__ , lowerCamelCase__ ) for ref in refs ) for pred, refs in zip(lowerCamelCase__ , lowerCamelCase__ )] return (sum(lowerCamelCase__ ) / len(lowerCamelCase__ )) * 100 def lowercase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str ) -> str: _snake_case : List[str] = [rgram for rgrams in rgramslist for rgram in rgrams] _snake_case : Any = Counter(lowerCamelCase__ ) _snake_case : Optional[int] = Counter(lowerCamelCase__ ) _snake_case : List[str] = Counter() for sgram, scount in sgramcounter.items(): _snake_case : Any = scount * numref _snake_case : Union[str, Any] = Counter(lowerCamelCase__ ) _snake_case : Optional[int] = Counter() for cgram, ccount in cgramcounter.items(): _snake_case : List[str] = ccount * numref # KEEP _snake_case : Optional[Any] = sgramcounter_rep & cgramcounter_rep _snake_case : List[Any] = keepgramcounter_rep & rgramcounter _snake_case : int = sgramcounter_rep & rgramcounter _snake_case : int = 0 _snake_case : Optional[int] = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _snake_case : Optional[int] = 1 _snake_case : Optional[Any] = 1 if len(lowerCamelCase__ ) > 0: _snake_case : Tuple = keeptmpscorea / len(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) _snake_case : Tuple = keeptmpscorea / sum(keepgramcounterall_rep.values() ) _snake_case : Dict = 0 if keepscore_precision > 0 or keepscore_recall > 0: _snake_case : List[str] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION _snake_case : str = sgramcounter_rep - cgramcounter_rep _snake_case : Tuple = delgramcounter_rep - rgramcounter _snake_case : Tuple = sgramcounter_rep - rgramcounter _snake_case : Union[str, Any] = 0 _snake_case : int = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _snake_case : Any = 1 if len(lowerCamelCase__ ) > 0: _snake_case : List[Any] = deltmpscorea / len(lowerCamelCase__ ) # ADDITION _snake_case : str = set(lowerCamelCase__ ) - set(lowerCamelCase__ ) _snake_case : Optional[int] = set(lowerCamelCase__ ) & set(lowerCamelCase__ ) _snake_case : str = set(lowerCamelCase__ ) - set(lowerCamelCase__ ) _snake_case : List[str] = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. _snake_case : int = 1 _snake_case : List[str] = 1 if len(lowerCamelCase__ ) > 0: _snake_case : Any = addtmpscore / len(lowerCamelCase__ ) if len(lowerCamelCase__ ) > 0: _snake_case : Optional[int] = addtmpscore / len(lowerCamelCase__ ) _snake_case : Optional[Any] = 0 if addscore_precision > 0 or addscore_recall > 0: _snake_case : List[Any] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int ) -> Dict: _snake_case : int = len(lowerCamelCase__ ) _snake_case : int = ssent.split(""" """ ) _snake_case : Optional[Any] = csent.split(""" """ ) _snake_case : int = [] _snake_case : Union[str, Any] = [] _snake_case : Optional[Any] = [] _snake_case : Tuple = [] _snake_case : str = [] _snake_case : Optional[int] = [] _snake_case : List[Any] = [] _snake_case : List[Any] = [] _snake_case : Union[str, Any] = [] _snake_case : Dict = [] for rsent in rsents: _snake_case : str = rsent.split(""" """ ) _snake_case : List[Any] = [] _snake_case : List[Any] = [] _snake_case : Union[str, Any] = [] ragramslist.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: _snake_case : List[str] = ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: _snake_case : List[Any] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: _snake_case : List[str] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) ragramslist.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: _snake_case : Any = sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: _snake_case : Optional[int] = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: _snake_case : Any = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(lowerCamelCase__ ) for i in range(0 , len(lowerCamelCase__ ) - 1 ): if i < len(lowerCamelCase__ ) - 1: _snake_case : Any = cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 2: _snake_case : str = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(lowerCamelCase__ ) if i < len(lowerCamelCase__ ) - 3: _snake_case : Tuple = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(lowerCamelCase__ ) (_snake_case) : Dict = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) (_snake_case) : Union[str, Any] = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) (_snake_case) : Union[str, Any] = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) (_snake_case) : str = SARIngram(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) _snake_case : Union[str, Any] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 _snake_case : Optional[int] = sum([delascore, delascore, delascore, delascore] ) / 4 _snake_case : str = sum([addascore, addascore, addascore, addascore] ) / 4 _snake_case : List[str] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def lowercase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple = True , SCREAMING_SNAKE_CASE__ : Union[str, Any] = "13a" , SCREAMING_SNAKE_CASE__ : List[Any] = True ) -> Any: # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: _snake_case : Optional[Any] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: _snake_case : int = sacrebleu.metrics.bleu._get_tokenizer(lowerCamelCase__ )()(lowerCamelCase__ ) else: _snake_case : str = sacrebleu.TOKENIZERS[tokenizer]()(lowerCamelCase__ ) elif tokenizer == "moses": _snake_case : Optional[Any] = sacremoses.MosesTokenizer().tokenize(lowerCamelCase__ , return_str=lowerCamelCase__ , escape=lowerCamelCase__ ) elif tokenizer == "penn": _snake_case : Tuple = sacremoses.MosesTokenizer().penn_tokenize(lowerCamelCase__ , return_str=lowerCamelCase__ ) else: _snake_case : List[Any] = sentence if not return_str: _snake_case : Optional[int] = normalized_sent.split() return normalized_sent def lowercase ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: if not (len(lowerCamelCase__ ) == len(lowerCamelCase__ ) == len(lowerCamelCase__ )): raise ValueError("""Sources length must match predictions and references lengths.""" ) _snake_case : List[str] = 0 for src, pred, refs in zip(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): sari_score += SARIsent(normalize(lowerCamelCase__ ) , normalize(lowerCamelCase__ ) , [normalize(lowerCamelCase__ ) for sent in refs] ) _snake_case : int = sari_score / len(lowerCamelCase__ ) return 100 * sari_score def lowercase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str]="exp" , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Optional[int]=False , ) -> int: _snake_case : Tuple = len(references[0] ) if any(len(lowerCamelCase__ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) _snake_case : Optional[int] = [[refs[i] for refs in references] for i in range(lowerCamelCase__ )] _snake_case : Dict = sacrebleu.corpus_bleu( lowerCamelCase__ , lowerCamelCase__ , smooth_method=lowerCamelCase__ , smooth_value=lowerCamelCase__ , force=lowerCamelCase__ , lowercase=lowerCamelCase__ , use_effective_order=lowerCamelCase__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : str) -> Any: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence"""), """references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""") , id="""references"""), }) , codebase_urls=[ """https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""", """https://github.com/cocoxu/simplification/blob/master/SARI.py""", """https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""", """https://github.com/mjpost/sacreBLEU""", ] , reference_urls=[ """https://www.aclweb.org/anthology/Q16-1029.pdf""", """https://github.com/mjpost/sacreBLEU""", """https://en.wikipedia.org/wiki/BLEU""", """https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""", ] , ) def UpperCamelCase_ ( self : List[str] , lowerCAmelCase : Optional[int] , lowerCAmelCase : List[Any] , lowerCAmelCase : List[Any]) -> Optional[Any]: """simple docstring""" _snake_case : List[str] = {} result.update({"""sari""": compute_sari(sources=SCREAMING_SNAKE_CASE__ , predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__)}) result.update({"""sacrebleu""": compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__)}) result.update({"""exact""": compute_em(predictions=SCREAMING_SNAKE_CASE__ , references=SCREAMING_SNAKE_CASE__)}) return result
317
import qiskit def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> qiskit.result.counts.Counts: __lowerCamelCase : Optional[int] = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __lowerCamelCase : List[str] = qiskit.QuantumCircuit(lowerCamelCase__ , lowerCamelCase__ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator __lowerCamelCase : List[Any] = qiskit.execute(lowerCamelCase__ , lowerCamelCase__ , shots=1_0_0_0 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCamelCase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")
73
0
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def __lowercase ( __lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' _A = int(lowerCamelCase__ ) assert noofclusters < len(lowerCamelCase__ ) # Find out the dimensionality _A = len(vectors[0] ) # Will help select random centroids from among the available vectors _A = list(range(len(lowerCamelCase__ ) ) ) shuffle(lowerCamelCase__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. _A = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION _A = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points _A = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowerCamelCase__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values _A = tf.placeholder("float64" , [dim] ) _A = [] for centroid in centroids: cent_assigns.append(tf.assign(lowerCamelCase__ , lowerCamelCase__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) _A = [tf.Variable(0 ) for i in range(len(lowerCamelCase__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value _A = tf.placeholder("int32" ) _A = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowerCamelCase__ , lowerCamelCase__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input _A = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors _A = tf.reduce_mean(lowerCamelCase__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input _A = tf.placeholder("float" , [dim] ) _A = tf.placeholder("float" , [dim] ) _A = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowerCamelCase__ , lowerCamelCase__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input _A = tf.placeholder("float" , [noofclusters] ) _A = tf.argmin(lowerCamelCase__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. _A = tf.initialize_all_variables() # Initialize all variables sess.run(lowerCamelCase__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. _A = 100 for _ in range(lowerCamelCase__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowerCamelCase__ ) ): _A = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. _A = [ sess.run(lowerCamelCase__ , feed_dict={va: vect, va: sess.run(lowerCamelCase__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input _A = sess.run( lowerCamelCase__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowerCamelCase__ ): # Collect all the vectors assigned to this cluster _A = [ vectors[i] for i in range(len(lowerCamelCase__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location _A = sess.run( lowerCamelCase__ , feed_dict={mean_input: array(lowerCamelCase__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments _A = sess.run(lowerCamelCase__ ) _A = sess.run(lowerCamelCase__ ) return centroids, assignments
79
import os import sys a =os.path.join(os.path.dirname(__file__), """src""") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a =[ """torch""", """numpy""", """tokenizers""", """filelock""", """requests""", """tqdm""", """regex""", """sentencepiece""", """sacremoses""", """importlib_metadata""", """huggingface_hub""", ] @add_start_docstrings(AutoConfig.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> int: return AutoConfig.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoTokenizer.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Optional[Any]: return AutoTokenizer.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModel.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModel.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Any: return AutoModelForCausalLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> List[str]: return AutoModelForSequenceClassification.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def SCREAMING_SNAKE_CASE__ ( *lowerCamelCase__ , **lowerCamelCase__ ) -> Tuple: return AutoModelForQuestionAnswering.from_pretrained(*lowerCamelCase__ , **lowerCamelCase__ )
73
0
def __UpperCamelCase ( _A : int ) ->"list[int]": """simple docstring""" if upper_limit < 0: raise ValueError("""Limit for the Catalan sequence must be ≥ 0""" ) lowerCamelCase_ =[0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 lowerCamelCase_ =1 if upper_limit > 0: lowerCamelCase_ =1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCamelCase__ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('\n********* Catalan Numbers Using Dynamic Programming ************\n') print('\n*** Enter -1 at any time to quit ***') print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='') try: while True: __A : List[str] = int(input().strip()) if N < 0: print('\n********* Goodbye!! ************') break else: print(F"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print('Try another upper limit for the sequence: ', end='') except (NameError, ValueError): print('\n********* Invalid input, goodbye! ************\n') import doctest doctest.testmod()
154
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None ) -> str: if version.parse(hfh.__version__ ).release < version.parse('0.11.0' ).release: # old versions of hfh don't url-encode the file path __lowerCamelCase : int = quote(lowerCamelCase__ ) return hfh.hf_hub_url(lowerCamelCase__ , lowerCamelCase__ , repo_type='dataset' , revision=lowerCamelCase__ )
73
0
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def snake_case_ ( A_ : int, A_ : List[Any]=False ): '''simple docstring''' try: _lowerCamelCase : int = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _lowerCamelCase : List[Any] = default else: # KEY is set, convert it to True or False. try: _lowerCamelCase : Any = strtobool(lowerCamelCase__ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''' ) return _value lowerCAmelCase__ = parse_flag_from_env('''RUN_SLOW''', default=False) def snake_case_ ( A_ : Dict ): '''simple docstring''' return unittest.skip('''Test was skipped''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests, '''test is slow''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available(), '''test requires only a CPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Any ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available(), '''test requires a GPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Tuple ): '''simple docstring''' return unittest.skipUnless(is_xpu_available(), '''test requires a XPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : str ): '''simple docstring''' return unittest.skipUnless(is_mps_available(), '''test requires a `mps` backend support in `torch`''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available(), '''test requires the Hugging Face suite''' )(lowerCamelCase__ ) def snake_case_ ( A_ : str ): '''simple docstring''' return unittest.skipUnless(is_bnb_available(), '''test requires the bitsandbytes library''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(is_tpu_available(), '''test requires TPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : str ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1, '''test requires a GPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1, '''test requires a XPU''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1, '''test requires multiple GPUs''' )(lowerCamelCase__ ) def snake_case_ ( A_ : str ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1, '''test requires multiple XPUs''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available(), '''test requires safetensors''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available(), '''test requires DeepSpeed''' )(lowerCamelCase__ ) def snake_case_ ( A_ : List[Any] ): '''simple docstring''' return unittest.skipUnless(is_torch_version('''>=''', '''1.12.0''' ), '''test requires torch version >= 1.12.0''' )(lowerCamelCase__ ) def snake_case_ ( A_ : str=None, A_ : Optional[int]=None ): '''simple docstring''' if test_case is None: return partial(lowerCamelCase__, version=lowerCamelCase__ ) return unittest.skipUnless(is_torch_version('''>=''', lowerCamelCase__ ), F'''test requires torch version >= {version}''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available(), '''test requires Tensorboard''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Optional[int] ): '''simple docstring''' return unittest.skipUnless(is_wandb_available(), '''test requires wandb''' )(lowerCamelCase__ ) def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available(), '''test requires comet_ml''' )(lowerCamelCase__ ) lowerCAmelCase__ = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available, '''test requires at least one tracker to be available and for `comet_ml` to not be installed''', )(lowerCamelCase__ ) class __snake_case ( unittest.TestCase): snake_case__ : Union[str, Any] = True @classmethod def SCREAMING_SNAKE_CASE ( cls : int ): """simple docstring""" _lowerCamelCase : List[Any] = tempfile.mkdtemp() @classmethod def SCREAMING_SNAKE_CASE ( cls : int ): """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob('''**/*''' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(SCREAMING_SNAKE_CASE__ ) class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[Any] ): """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class __snake_case ( unittest.TestCase): def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Union[mock.Mock, List[mock.Mock]] ): """simple docstring""" _lowerCamelCase : Tuple = mocks if isinstance(SCREAMING_SNAKE_CASE__ , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def snake_case_ ( A_ : Optional[Any] ): '''simple docstring''' _lowerCamelCase : int = AcceleratorState() _lowerCamelCase : Optional[int] = tensor[None].clone().to(state.device ) _lowerCamelCase : Dict = gather(lowerCamelCase__ ).cpu() _lowerCamelCase : Union[str, Any] = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i], lowerCamelCase__ ): return False return True class __snake_case : def __init__( self : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = returncode _lowerCamelCase : List[str] = stdout _lowerCamelCase : Tuple = stderr async def snake_case_ ( A_ : List[Any], A_ : List[Any] ): '''simple docstring''' while True: _lowerCamelCase : str = await stream.readline() if line: callback(lowerCamelCase__ ) else: break async def snake_case_ ( A_ : Tuple, A_ : List[Any]=None, A_ : Any=None, A_ : List[Any]=None, A_ : str=False, A_ : List[Any]=False ): '''simple docstring''' if echo: print('''\nRunning: ''', ''' '''.join(lowerCamelCase__ ) ) _lowerCamelCase : str = await asyncio.create_subprocess_exec( cmd[0], *cmd[1:], stdin=lowerCamelCase__, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, env=lowerCamelCase__, ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) _lowerCamelCase : int = [] _lowerCamelCase : str = [] def tee(A_ : List[Any], A_ : int, A_ : Union[str, Any], A_ : int="" ): _lowerCamelCase : Any = line.decode('''utf-8''' ).rstrip() sink.append(lowerCamelCase__ ) if not quiet: print(lowerCamelCase__, lowerCamelCase__, file=lowerCamelCase__ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout, lambda A_ : tee(lowerCamelCase__, lowerCamelCase__, sys.stdout, label='''stdout:''' ) ) ), asyncio.create_task(_read_stream(p.stderr, lambda A_ : tee(lowerCamelCase__, lowerCamelCase__, sys.stderr, label='''stderr:''' ) ) ), ], timeout=lowerCamelCase__, ) return _RunOutput(await p.wait(), lowerCamelCase__, lowerCamelCase__ ) def snake_case_ ( A_ : Union[str, Any], A_ : Tuple=None, A_ : Dict=None, A_ : Optional[Any]=1_80, A_ : List[str]=False, A_ : Dict=True ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = asyncio.get_event_loop() _lowerCamelCase : str = loop.run_until_complete( _stream_subprocess(lowerCamelCase__, env=lowerCamelCase__, stdin=lowerCamelCase__, timeout=lowerCamelCase__, quiet=lowerCamelCase__, echo=lowerCamelCase__ ) ) _lowerCamelCase : Union[str, Any] = ' '.join(lowerCamelCase__ ) if result.returncode > 0: _lowerCamelCase : Optional[int] = '\n'.join(result.stderr ) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''' ) return result class __snake_case ( _lowercase): pass def snake_case_ ( A_ : List[str], A_ : Union[str, Any]=False ): '''simple docstring''' try: _lowerCamelCase : List[str] = subprocess.check_output(lowerCamelCase__, stderr=subprocess.STDOUT ) if return_stdout: if hasattr(lowerCamelCase__, '''decode''' ): _lowerCamelCase : str = output.decode('''utf-8''' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F'''Command `{" ".join(lowerCamelCase__ )}` failed with the following error:\n\n{e.output.decode()}''' ) from e
72
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float: __lowerCamelCase : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: __lowerCamelCase : Dict = 1 - (matter_density + radiation_density + dark_energy) __lowerCamelCase : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) __lowerCamelCase : List[Any] = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation a =0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1E-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
73
0
'''simple docstring''' import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def a ( *__a , __a = None , __a=True , __a=2 ) -> List[Any]: '''simple docstring''' from .. import __version__ UpperCamelCase__ :List[Any] = take_from UpperCamelCase__ :int = () if not isinstance(args[0] , lowerCamelCase__ ): UpperCamelCase__ :Tuple = (args,) for attribute, version_name, message in args: if version.parse(version.parse(lowerCamelCase__ ).base_version ) >= version.parse(lowerCamelCase__ ): raise ValueError( f'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' f''' version {__version__} is >= {version_name}''' ) UpperCamelCase__ :Optional[int] = None if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowerCamelCase__ ),) UpperCamelCase__ :int = f'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(lowerCamelCase__ , lowerCamelCase__ ): values += (getattr(lowerCamelCase__ , lowerCamelCase__ ),) UpperCamelCase__ :List[Any] = f'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: UpperCamelCase__ :str = f'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: UpperCamelCase__ :Optional[int] = warning + ' ' if standard_warn else '' warnings.warn(warning + message , lowerCamelCase__ , stacklevel=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) and len(lowerCamelCase__ ) > 0: UpperCamelCase__ :List[str] = inspect.getouterframes(inspect.currentframe() )[1] UpperCamelCase__ :Optional[int] = call_frame.filename UpperCamelCase__ :List[str] = call_frame.lineno UpperCamelCase__ :Union[str, Any] = call_frame.function UpperCamelCase__ :Optional[Any] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(f'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(lowerCamelCase__ ) == 0: return elif len(lowerCamelCase__ ) == 1: return values[0] return values
97
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Optional[Any] = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : Union[str, Any] = '''Pix2StructImageProcessor''' _UpperCAmelCase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[str] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : List[Any] = False super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) def __call__( self : str ,SCREAMING_SNAKE_CASE__ : Any=None ,SCREAMING_SNAKE_CASE__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False ,SCREAMING_SNAKE_CASE__ : Union[bool, str, TruncationStrategy] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[int] = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : int = 0 ,SCREAMING_SNAKE_CASE__ : Optional[int] = None ,SCREAMING_SNAKE_CASE__ : Optional[bool] = None ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): 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 and not self.image_processor.is_vqa: __lowerCamelCase : Tuple = self.tokenizer __lowerCamelCase : Dict = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) return text_encoding if not self.image_processor.is_vqa: # add pixel_values __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) else: # add pixel_values and bbox __lowerCamelCase : List[Any] = self.image_processor( SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,max_patches=SCREAMING_SNAKE_CASE__ ,header_text=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None and not self.image_processor.is_vqa: __lowerCamelCase : List[Any] = self.tokenizer( text=SCREAMING_SNAKE_CASE__ ,add_special_tokens=SCREAMING_SNAKE_CASE__ ,padding=SCREAMING_SNAKE_CASE__ ,truncation=SCREAMING_SNAKE_CASE__ ,max_length=SCREAMING_SNAKE_CASE__ ,stride=SCREAMING_SNAKE_CASE__ ,pad_to_multiple_of=SCREAMING_SNAKE_CASE__ ,return_attention_mask=SCREAMING_SNAKE_CASE__ ,return_overflowing_tokens=SCREAMING_SNAKE_CASE__ ,return_special_tokens_mask=SCREAMING_SNAKE_CASE__ ,return_offsets_mapping=SCREAMING_SNAKE_CASE__ ,return_token_type_ids=SCREAMING_SNAKE_CASE__ ,return_length=SCREAMING_SNAKE_CASE__ ,verbose=SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) if "attention_mask" in text_encoding: __lowerCamelCase : List[Any] = text_encoding.pop('attention_mask') if "input_ids" in text_encoding: __lowerCamelCase : Dict = text_encoding.pop('input_ids') else: __lowerCamelCase : Optional[int] = None if text_encoding is not None: encoding_image_processor.update(SCREAMING_SNAKE_CASE__) return encoding_image_processor def lowerCAmelCase ( self : Dict ,*SCREAMING_SNAKE_CASE__ : str ,**SCREAMING_SNAKE_CASE__ : int): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : List[str] ,*SCREAMING_SNAKE_CASE__ : int ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : int): __lowerCamelCase : Dict = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
73
0
import logging import os import threading import time try: import warnings except ImportError: lowerCAmelCase_ = None try: import msvcrt except ImportError: lowerCAmelCase_ = None try: import fcntl except ImportError: lowerCAmelCase_ = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: lowerCAmelCase_ = OSError # Data # ------------------------------------------------ lowerCAmelCase_ = [ '''Timeout''', '''BaseFileLock''', '''WindowsFileLock''', '''UnixFileLock''', '''SoftFileLock''', '''FileLock''', ] lowerCAmelCase_ = '''3.0.12''' lowerCAmelCase_ = None def lowerCamelCase_ ( ) -> int: """simple docstring""" global _logger snake_case_ : int = _logger or logging.getLogger(__name__ ) return _logger class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ ) -> Optional[int]: '''simple docstring''' snake_case_ : Any = lock_file return None def __str__(self ) -> Optional[Any]: '''simple docstring''' snake_case_ : int = F'''The file lock \'{self.lock_file}\' could not be acquired.''' return temp class __lowerCAmelCase : def __init__(self , __magic_name__ ) -> Tuple: '''simple docstring''' snake_case_ : Optional[Any] = lock return None def __enter__(self ) -> int: '''simple docstring''' return self.lock def __exit__(self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Dict: '''simple docstring''' self.lock.release() return None class __lowerCAmelCase : def __init__(self , __magic_name__ , __magic_name__=-1 , __magic_name__=None ) -> int: '''simple docstring''' snake_case_ : str = max_filename_length if max_filename_length is not None else 255 # Hash the filename if it's too long snake_case_ : Dict = self.hash_filename_if_too_long(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # The path to the lock file. snake_case_ : int = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. snake_case_ : Dict = None # The default timeout value. snake_case_ : List[Any] = timeout # We use this lock primarily for the lock counter. snake_case_ : List[Any] = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. snake_case_ : Any = 0 return None @property def lowerCamelCase (self ) -> Optional[int]: '''simple docstring''' return self._lock_file @property def lowerCamelCase (self ) -> Tuple: '''simple docstring''' return self._timeout @timeout.setter def lowerCamelCase (self , __magic_name__ ) -> Dict: '''simple docstring''' snake_case_ : Union[str, Any] = float(SCREAMING_SNAKE_CASE__ ) return None def lowerCamelCase (self ) -> Union[str, Any]: '''simple docstring''' raise NotImplementedError() def lowerCamelCase (self ) -> Dict: '''simple docstring''' raise NotImplementedError() @property def lowerCamelCase (self ) -> Dict: '''simple docstring''' return self._lock_file_fd is not None def lowerCamelCase (self , __magic_name__=None , __magic_name__=0.05 ) -> Any: '''simple docstring''' if timeout is None: snake_case_ : str = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 snake_case_ : Any = id(self ) snake_case_ : Optional[int] = self._lock_file snake_case_ : str = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}''' ) self._acquire() if self.is_locked: logger().debug(F'''Lock {lock_id} acquired on {lock_filename}''' ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}''' ) raise Timeout(self._lock_file ) else: logger().debug( F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...''' ) time.sleep(SCREAMING_SNAKE_CASE__ ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: snake_case_ : str = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def lowerCamelCase (self , __magic_name__=False ) -> Any: '''simple docstring''' with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: snake_case_ : str = id(self ) snake_case_ : int = self._lock_file logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}''' ) self._release() snake_case_ : Optional[int] = 0 logger().debug(F'''Lock {lock_id} released on {lock_filename}''' ) return None def __enter__(self ) -> Union[str, Any]: '''simple docstring''' self.acquire() return self def __exit__(self , __magic_name__ , __magic_name__ , __magic_name__ ) -> Optional[Any]: '''simple docstring''' self.release() return None def __del__(self ) -> Optional[Any]: '''simple docstring''' self.release(force=SCREAMING_SNAKE_CASE__ ) return None def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> List[Any]: '''simple docstring''' snake_case_ : Optional[Any] = os.path.basename(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > max_length and max_length > 0: snake_case_ : Optional[int] = os.path.dirname(SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[Any] = str(hash(SCREAMING_SNAKE_CASE__ ) ) snake_case_ : str = filename[: max_length - len(SCREAMING_SNAKE_CASE__ ) - 8] + '...' + hashed_filename + '.lock' return os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return path class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ , __magic_name__=-1 , __magic_name__=None ) -> List[Any]: '''simple docstring''' from .file_utils import relative_to_absolute_path super().__init__(SCREAMING_SNAKE_CASE__ , timeout=SCREAMING_SNAKE_CASE__ , max_filename_length=SCREAMING_SNAKE_CASE__ ) snake_case_ : Optional[int] = '\\\\?\\' + relative_to_absolute_path(self.lock_file ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : Tuple = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: snake_case_ : List[Any] = os.open(self._lock_file , SCREAMING_SNAKE_CASE__ ) except OSError: pass else: try: msvcrt.locking(SCREAMING_SNAKE_CASE__ , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(SCREAMING_SNAKE_CASE__ ) else: snake_case_ : Optional[Any] = fd return None def lowerCamelCase (self ) -> int: '''simple docstring''' snake_case_ : List[Any] = self._lock_file_fd snake_case_ : Optional[Any] = None msvcrt.locking(SCREAMING_SNAKE_CASE__ , msvcrt.LK_UNLCK , 1 ) os.close(SCREAMING_SNAKE_CASE__ ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class __lowerCAmelCase ( _a ): def __init__(self , __magic_name__ , __magic_name__=-1 , __magic_name__=None ) -> str: '''simple docstring''' snake_case_ : int = os.statvfs(os.path.dirname(SCREAMING_SNAKE_CASE__ ) ).f_namemax super().__init__(SCREAMING_SNAKE_CASE__ , timeout=SCREAMING_SNAKE_CASE__ , max_filename_length=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase (self ) -> str: '''simple docstring''' snake_case_ : int = os.O_RDWR | os.O_CREAT | os.O_TRUNC snake_case_ : List[str] = os.open(self._lock_file , SCREAMING_SNAKE_CASE__ ) try: fcntl.flock(SCREAMING_SNAKE_CASE__ , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(SCREAMING_SNAKE_CASE__ ) else: snake_case_ : List[Any] = fd return None def lowerCamelCase (self ) -> List[str]: '''simple docstring''' snake_case_ : List[Any] = self._lock_file_fd snake_case_ : Optional[int] = None fcntl.flock(SCREAMING_SNAKE_CASE__ , fcntl.LOCK_UN ) os.close(SCREAMING_SNAKE_CASE__ ) return None class __lowerCAmelCase ( _a ): def lowerCamelCase (self ) -> Dict: '''simple docstring''' snake_case_ : Optional[int] = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: snake_case_ : int = os.open(self._lock_file , SCREAMING_SNAKE_CASE__ ) except OSError: pass else: snake_case_ : Dict = fd return None def lowerCamelCase (self ) -> List[str]: '''simple docstring''' os.close(self._lock_file_fd ) snake_case_ : str = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None lowerCAmelCase_ = None if msvcrt: lowerCAmelCase_ = WindowsFileLock elif fcntl: lowerCAmelCase_ = UnixFileLock else: lowerCAmelCase_ = SoftFileLock if warnings is not None: warnings.warn('''only soft file lock is available''')
279
from bisect import bisect from itertools import accumulate def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Union[str, Any]: __lowerCamelCase : Optional[Any] = sorted(zip(lowerCamelCase__ , lowerCamelCase__ ) , key=lambda lowerCamelCase__ : x[0] / x[1] , reverse=lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase : Any = [i[0] for i in r], [i[1] for i in r] __lowerCamelCase : List[str] = list(accumulate(lowerCamelCase__ ) ) __lowerCamelCase : Union[str, Any] = bisect(lowerCamelCase__ , lowerCamelCase__ ) return ( 0 if k == 0 else sum(vl[:k] ) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) if k != n else sum(vl[:k] ) ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : int = { """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 : int = [ """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 : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
174
from __future__ import annotations import math def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if len(lowerCamelCase__ ) != 2 or len(a[0] ) != 2 or len(lowerCamelCase__ ) != 2 or len(b[0] ) != 2: raise Exception('Matrices are not 2x2' ) __lowerCamelCase : Optional[int] = [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]], ] return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> Optional[int]: return [ [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> List[str]: return [ [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )] for row in range(len(lowerCamelCase__ ) ) ] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[list, list, list, list]: if len(lowerCamelCase__ ) % 2 != 0 or len(a[0] ) % 2 != 0: raise Exception('Odd matrices are not supported!' ) __lowerCamelCase : Tuple = len(lowerCamelCase__ ) __lowerCamelCase : List[Any] = matrix_length // 2 __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : str = [ [a[i][j] for j in range(lowerCamelCase__ , lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ ) ] __lowerCamelCase : Dict = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ )] __lowerCamelCase : Optional[Any] = [[a[i][j] for j in range(lowerCamelCase__ )] for i in range(lowerCamelCase__ , lowerCamelCase__ )] return top_left, top_right, bot_left, bot_right def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> tuple[int, int]: return len(lowerCamelCase__ ), len(matrix[0] ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> None: print('\n'.join(str(lowerCamelCase__ ) for line in matrix ) ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ ) == (2, 2): return default_matrix_multiplication(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = split_matrix(lowerCamelCase__ ) __lowerCamelCase : str = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : List[str] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : List[Any] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = actual_strassen(lowerCamelCase__ , matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Optional[int] = actual_strassen(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Tuple = actual_strassen(matrix_subtraction(lowerCamelCase__ , lowerCamelCase__ ) , matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) ) __lowerCamelCase : Dict = matrix_addition(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) __lowerCamelCase : Tuple = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) __lowerCamelCase : Any = matrix_subtraction(matrix_subtraction(matrix_addition(lowerCamelCase__ , lowerCamelCase__ ) , lowerCamelCase__ ) , lowerCamelCase__ ) # construct the new matrix from our 4 quadrants __lowerCamelCase : List[Any] = [] for i in range(len(lowerCamelCase__ ) ): new_matrix.append(top_left[i] + top_right[i] ) for i in range(len(lowerCamelCase__ ) ): new_matrix.append(bot_left[i] + bot_right[i] ) return new_matrix def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> list: if matrix_dimensions(lowerCamelCase__ )[1] != matrix_dimensions(lowerCamelCase__ )[0]: __lowerCamelCase : Any = ( 'Unable to multiply these matrices, please check the dimensions.\n' F"Matrix A: {matrixa}\n" F"Matrix B: {matrixa}" ) raise Exception(lowerCamelCase__ ) __lowerCamelCase : str = matrix_dimensions(lowerCamelCase__ ) __lowerCamelCase : List[str] = matrix_dimensions(lowerCamelCase__ ) if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]: return [matrixa, matrixa] __lowerCamelCase : str = max(*lowerCamelCase__ , *lowerCamelCase__ ) __lowerCamelCase : List[str] = int(math.pow(2 , math.ceil(math.loga(lowerCamelCase__ ) ) ) ) __lowerCamelCase : Any = matrixa __lowerCamelCase : int = matrixa # Adding zeros to the matrices so that the arrays dimensions are the same and also # power of 2 for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): new_matrixa[i].append(0 ) else: new_matrixa.append([0] * maxim ) __lowerCamelCase : List[str] = actual_strassen(lowerCamelCase__ , lowerCamelCase__ ) # Removing the additional zeros for i in range(0 , lowerCamelCase__ ): if i < dimensiona[0]: for _ in range(dimensiona[1] , lowerCamelCase__ ): final_matrix[i].pop() else: final_matrix.pop() return final_matrix if __name__ == "__main__": a =[ [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 4, 3, 1], [2, 3, 6, 7], [3, 1, 2, 4], [2, 3, 4, 5], [6, 2, 3, 1], ] a =[[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]] print(strassen(matrixa, matrixa))
73
0
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ : Tuple = logging.get_logger(__name__) snake_case_ : Dict = { "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 __snake_case ( a ): UpperCAmelCase__ : List[Any] = '''dpr''' def __init__( self : Any , _snake_case : Tuple=30522 , _snake_case : Any=768 , _snake_case : str=12 , _snake_case : Tuple=12 , _snake_case : Any=3072 , _snake_case : Dict="gelu" , _snake_case : Tuple=0.1 , _snake_case : str=0.1 , _snake_case : int=512 , _snake_case : Union[str, Any]=2 , _snake_case : Optional[int]=0.0_2 , _snake_case : Dict=1e-12 , _snake_case : Dict=0 , _snake_case : List[Any]="absolute" , _snake_case : int = 0 , **_snake_case : Dict , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = hidden_act UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = projection_dim UpperCAmelCase_ = position_embedding_type
51
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
0
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def _lowercase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE__ = AutoConfig.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = FlaxAutoModelForSeqaSeqLM.from_config(config=lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = checkpoints.load_tax_checkpoint(lowerCamelCase__ ) SCREAMING_SNAKE_CASE__ = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": SCREAMING_SNAKE_CASE__ = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": SCREAMING_SNAKE_CASE__ = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": SCREAMING_SNAKE_CASE__ = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): SCREAMING_SNAKE_CASE__ = F'layers_{str(lowerCamelCase__ )}' # Self-Attention SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning SCREAMING_SNAKE_CASE__ = flax_model.params['encoder']['block'][str(lowerCamelCase__ )]['layer'] SCREAMING_SNAKE_CASE__ = tax_attention_key SCREAMING_SNAKE_CASE__ = tax_attention_out SCREAMING_SNAKE_CASE__ = tax_attention_query SCREAMING_SNAKE_CASE__ = tax_attention_value SCREAMING_SNAKE_CASE__ = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": SCREAMING_SNAKE_CASE__ = tax_global_layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE__ = tax_mlp_wi_a SCREAMING_SNAKE_CASE__ = tax_mlp_wi_a else: SCREAMING_SNAKE_CASE__ = tax_mlp_wi SCREAMING_SNAKE_CASE__ = tax_mlp_wo SCREAMING_SNAKE_CASE__ = tax_mlp_layer_norm SCREAMING_SNAKE_CASE__ = flax_model_encoder_layer_block # Only for layer 0: SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T SCREAMING_SNAKE_CASE__ = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T SCREAMING_SNAKE_CASE__ = tax_encoder_global_rel_embedding # Assigning SCREAMING_SNAKE_CASE__ = tax_model['target']['encoder']['encoder_norm']['scale'] SCREAMING_SNAKE_CASE__ = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): SCREAMING_SNAKE_CASE__ = F'layers_{str(lowerCamelCase__ )}' # Self-Attention SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_module['key']['kernel'] SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_module['out']['kernel'] SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_module['query']['kernel'] SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning SCREAMING_SNAKE_CASE__ = flax_model.params['decoder']['block'][str(lowerCamelCase__ )]['layer'] SCREAMING_SNAKE_CASE__ = tax_attention_key SCREAMING_SNAKE_CASE__ = tax_attention_out SCREAMING_SNAKE_CASE__ = tax_attention_query SCREAMING_SNAKE_CASE__ = tax_attention_value SCREAMING_SNAKE_CASE__ = tax_pre_attention_layer_norm SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_key SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_out SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_query SCREAMING_SNAKE_CASE__ = tax_enc_dec_attention_value SCREAMING_SNAKE_CASE__ = tax_cross_layer_norm if split_mlp_wi: SCREAMING_SNAKE_CASE__ = tax_mlp_wi_a SCREAMING_SNAKE_CASE__ = tax_mlp_wi_a else: SCREAMING_SNAKE_CASE__ = tax_mlp_wi SCREAMING_SNAKE_CASE__ = tax_mlp_wo SCREAMING_SNAKE_CASE__ = txa_mlp_layer_norm SCREAMING_SNAKE_CASE__ = flax_model_decoder_layer_block # Decoder Normalization SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder']['decoder_norm']['scale'] SCREAMING_SNAKE_CASE__ = txa_decoder_norm # Only for layer 0: SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T SCREAMING_SNAKE_CASE__ = tax_decoder_rel_embedding # Token Embeddings SCREAMING_SNAKE_CASE__ = tax_model['target']['token_embedder']['embedding'] SCREAMING_SNAKE_CASE__ = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: SCREAMING_SNAKE_CASE__ = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(lowerCamelCase__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path the T5X checkpoint.""" ) parser.add_argument("""--config_name""", default=None, type=str, required=True, help="""Config name of LongT5/T5 model.""") parser.add_argument( """--flax_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output FLAX model.""" ) __snake_case = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
176
import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a =logging.get_logger(__name__) a ={"""vocab_file""": """spiece.model"""} a ={ """vocab_file""": { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""", } } a ={ """albert-base-v1""": 512, """albert-large-v1""": 512, """albert-xlarge-v1""": 512, """albert-xxlarge-v1""": 512, """albert-base-v2""": 512, """albert-large-v2""": 512, """albert-xlarge-v2""": 512, """albert-xxlarge-v2""": 512, } a ="""▁""" class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : List[Any] = VOCAB_FILES_NAMES _UpperCAmelCase : List[str] = PRETRAINED_VOCAB_FILES_MAP _UpperCAmelCase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : str ,SCREAMING_SNAKE_CASE__ : Optional[int] ,SCREAMING_SNAKE_CASE__ : Tuple=True ,SCREAMING_SNAKE_CASE__ : str=True ,SCREAMING_SNAKE_CASE__ : List[str]=False ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" ,SCREAMING_SNAKE_CASE__ : Any="[SEP]" ,SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" ,SCREAMING_SNAKE_CASE__ : Any="[CLS]" ,SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" ,SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None ,**SCREAMING_SNAKE_CASE__ : Dict ,): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __lowerCamelCase : Dict = ( AddedToken(SCREAMING_SNAKE_CASE__ ,lstrip=SCREAMING_SNAKE_CASE__ ,rstrip=SCREAMING_SNAKE_CASE__ ,normalized=SCREAMING_SNAKE_CASE__) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) else mask_token ) __lowerCamelCase : str = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ ,remove_space=SCREAMING_SNAKE_CASE__ ,keep_accents=SCREAMING_SNAKE_CASE__ ,bos_token=SCREAMING_SNAKE_CASE__ ,eos_token=SCREAMING_SNAKE_CASE__ ,unk_token=SCREAMING_SNAKE_CASE__ ,sep_token=SCREAMING_SNAKE_CASE__ ,pad_token=SCREAMING_SNAKE_CASE__ ,cls_token=SCREAMING_SNAKE_CASE__ ,mask_token=SCREAMING_SNAKE_CASE__ ,sp_model_kwargs=self.sp_model_kwargs ,**SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Any = do_lower_case __lowerCamelCase : Union[str, Any] = remove_space __lowerCamelCase : Tuple = keep_accents __lowerCamelCase : Dict = vocab_file __lowerCamelCase : str = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(SCREAMING_SNAKE_CASE__) @property def lowerCAmelCase ( self : Optional[Any]): return len(self.sp_model) def lowerCAmelCase ( self : Optional[Any]): __lowerCamelCase : Optional[int] = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def __getstate__( self : Union[str, Any]): __lowerCamelCase : str = self.__dict__.copy() __lowerCamelCase : Tuple = None return state def __setstate__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : List[str] = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs'): __lowerCamelCase : List[str] = {} __lowerCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(self.vocab_file) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[Any]): if self.remove_space: __lowerCamelCase : Dict = ' '.join(inputs.strip().split()) else: __lowerCamelCase : Optional[Any] = inputs __lowerCamelCase : Tuple = outputs.replace('``' ,'"').replace('\'\'' ,'"') if not self.keep_accents: __lowerCamelCase : List[str] = unicodedata.normalize('NFKD' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = ''.join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__)]) if self.do_lower_case: __lowerCamelCase : Optional[Any] = outputs.lower() return outputs def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : str): __lowerCamelCase : Tuple = self.preprocess_text(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE__ ,out_type=SCREAMING_SNAKE_CASE__) __lowerCamelCase : Tuple = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): __lowerCamelCase : int = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ ,'')) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0]) == 1: __lowerCamelCase : Union[str, Any] = cur_pieces[1:] else: __lowerCamelCase : Dict = cur_pieces[0][1:] cur_pieces.append(piece[-1]) new_pieces.extend(SCREAMING_SNAKE_CASE__) else: new_pieces.append(SCREAMING_SNAKE_CASE__) return new_pieces def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : List[str]): return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : str ,SCREAMING_SNAKE_CASE__ : Any): return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Tuple ,SCREAMING_SNAKE_CASE__ : int): __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = '' __lowerCamelCase : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) + token __lowerCamelCase : List[Any] = True __lowerCamelCase : Any = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__) __lowerCamelCase : List[Any] = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__) return out_string.strip() def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Union[str, Any] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ,SCREAMING_SNAKE_CASE__ : bool = False): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ ,token_ids_a=SCREAMING_SNAKE_CASE__ ,already_has_special_tokens=SCREAMING_SNAKE_CASE__) if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__)) + [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : List[int] ,SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None): __lowerCamelCase : Tuple = [self.sep_token_id] __lowerCamelCase : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep) * [0] return len(cls + token_ids_a + sep) * [0] + len(token_ids_a + sep) * [1] def lowerCAmelCase ( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : Optional[str] = None): if not os.path.isdir(SCREAMING_SNAKE_CASE__): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return __lowerCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE__ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']) if os.path.abspath(self.vocab_file) != os.path.abspath(SCREAMING_SNAKE_CASE__) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file ,SCREAMING_SNAKE_CASE__) elif not os.path.isfile(self.vocab_file): with open(SCREAMING_SNAKE_CASE__ ,'wb') as fi: __lowerCamelCase : str = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__) return (out_vocab_file,)
73
0
def __magic_name__ ( A : Optional[Any] ): '''simple docstring''' if length <= 0 or not isinstance(lowerCamelCase__, lowerCamelCase__ ): raise ValueError("Length must be a positive integer." ) return [n * (2 * n - 1) for n in range(lowerCamelCase__ )] if __name__ == "__main__": print(hexagonal_numbers(length=5)) print(hexagonal_numbers(length=10))
107
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> float: if discount_rate < 0: raise ValueError('Discount rate cannot be negative' ) if not cash_flows: raise ValueError('Cash flows list cannot be empty' ) __lowerCamelCase : int = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase__ ) ) return round(lowerCamelCase__ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
73
0
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase (_UpperCAmelCase ,_UpperCAmelCase ,unittest.TestCase ): __snake_case : Union[str, Any] = CycleDiffusionPipeline __snake_case : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } __snake_case : int = PipelineTesterMixin.required_optional_params - {'''latents'''} __snake_case : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"source_prompt"} ) __snake_case : Union[str, Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS __snake_case : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) _SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="""scaled_linear""" , num_train_timesteps=1_000 , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) _SCREAMING_SNAKE_CASE = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _SCREAMING_SNAKE_CASE = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def UpperCamelCase ( self: List[Any] , UpperCAmelCase_: List[Any] , UpperCAmelCase_: List[str]=0 ): '''simple docstring''' _SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = image / 2 + 0.5 if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): _SCREAMING_SNAKE_CASE = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: _SCREAMING_SNAKE_CASE = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = { 'prompt': 'An astronaut riding an elephant', 'source_prompt': 'An astronaut riding a horse', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'eta': 0.1, 'strength': 0.8, 'guidance_scale': 3, 'source_guidance_scale': 1, 'output_type': 'numpy', } return inputs def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = 'cpu' # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = CycleDiffusionPipeline(**SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe(**SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = output.images _SCREAMING_SNAKE_CASE = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) _SCREAMING_SNAKE_CASE = np.array([0.44_59, 0.49_43, 0.45_44, 0.66_43, 0.54_74, 0.43_27, 0.57_01, 0.59_59, 0.51_79] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def UpperCamelCase ( self: str ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.get_dummy_components() for name, module in components.items(): if hasattr(SCREAMING_SNAKE_CASE__ , """half""" ): _SCREAMING_SNAKE_CASE = module.half() _SCREAMING_SNAKE_CASE = CycleDiffusionPipeline(**SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe(**SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = output.images _SCREAMING_SNAKE_CASE = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) _SCREAMING_SNAKE_CASE = np.array([0.35_06, 0.45_43, 0.4_46, 0.45_75, 0.51_95, 0.41_55, 0.52_73, 0.5_18, 0.41_16] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def UpperCamelCase ( self: Dict ): '''simple docstring''' return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' return super().test_inference_batch_single_identical() @skip_mps def UpperCamelCase ( self: Any ): '''simple docstring''' return super().test_dict_tuple_outputs_equivalent() @skip_mps def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' return super().test_save_load_optional_components() @skip_mps def UpperCamelCase ( self: Tuple ): '''simple docstring''' return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __UpperCAmelCase (unittest.TestCase ): def UpperCamelCase ( self: List[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) _SCREAMING_SNAKE_CASE = init_image.resize((512, 512) ) _SCREAMING_SNAKE_CASE = 'CompVis/stable-diffusion-v1-4' _SCREAMING_SNAKE_CASE = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="""scheduler""" ) _SCREAMING_SNAKE_CASE = CycleDiffusionPipeline.from_pretrained( SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE = 'A black colored car' _SCREAMING_SNAKE_CASE = 'A blue colored car' _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=SCREAMING_SNAKE_CASE__ , source_prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5E-1 def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) _SCREAMING_SNAKE_CASE = init_image.resize((512, 512) ) _SCREAMING_SNAKE_CASE = 'CompVis/stable-diffusion-v1-4' _SCREAMING_SNAKE_CASE = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="""scheduler""" ) _SCREAMING_SNAKE_CASE = CycleDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE = 'A black colored car' _SCREAMING_SNAKE_CASE = 'A blue colored car' _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=SCREAMING_SNAKE_CASE__ , source_prompt=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=SCREAMING_SNAKE_CASE__ , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images assert np.abs(image - expected_image ).max() < 2E-2
306
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a ={ """facebook/mask2former-swin-small-coco-instance""": ( """https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json""" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } a =logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Dict = '''mask2former''' _UpperCAmelCase : Dict = ['''swin'''] _UpperCAmelCase : Optional[int] = {'''hidden_size''': '''hidden_dim'''} def __init__( self : Optional[Any] ,SCREAMING_SNAKE_CASE__ : Optional[Dict] = None ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 2_5_6 ,SCREAMING_SNAKE_CASE__ : int = 1_0_2_4 ,SCREAMING_SNAKE_CASE__ : str = "relu" ,SCREAMING_SNAKE_CASE__ : int = 6 ,SCREAMING_SNAKE_CASE__ : int = 1_0 ,SCREAMING_SNAKE_CASE__ : int = 8 ,SCREAMING_SNAKE_CASE__ : float = 0.0 ,SCREAMING_SNAKE_CASE__ : int = 2_0_4_8 ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : bool = False ,SCREAMING_SNAKE_CASE__ : int = 4 ,SCREAMING_SNAKE_CASE__ : int = 2_5_5 ,SCREAMING_SNAKE_CASE__ : int = 1_0_0 ,SCREAMING_SNAKE_CASE__ : float = 0.1 ,SCREAMING_SNAKE_CASE__ : float = 2.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : float = 5.0 ,SCREAMING_SNAKE_CASE__ : int = 1_2_5_4_4 ,SCREAMING_SNAKE_CASE__ : float = 3.0 ,SCREAMING_SNAKE_CASE__ : float = 0.75 ,SCREAMING_SNAKE_CASE__ : float = 0.02 ,SCREAMING_SNAKE_CASE__ : float = 1.0 ,SCREAMING_SNAKE_CASE__ : bool = True ,SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 1_6, 3_2] ,SCREAMING_SNAKE_CASE__ : bool = None ,**SCREAMING_SNAKE_CASE__ : Optional[Any] ,): if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.') __lowerCamelCase : Optional[Any] = CONFIG_MAPPING['swin']( image_size=2_2_4 ,in_channels=3 ,patch_size=4 ,embed_dim=9_6 ,depths=[2, 2, 1_8, 2] ,num_heads=[3, 6, 1_2, 2_4] ,window_size=7 ,drop_path_rate=0.3 ,use_absolute_embeddings=SCREAMING_SNAKE_CASE__ ,out_features=['stage1', 'stage2', 'stage3', 'stage4'] ,) if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = backbone_config.pop('model_type') __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : int = config_class.from_dict(SCREAMING_SNAKE_CASE__) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. " F"Supported model types: {','.join(self.backbones_supported)}") __lowerCamelCase : Dict = backbone_config __lowerCamelCase : int = feature_size __lowerCamelCase : List[str] = mask_feature_size __lowerCamelCase : int = hidden_dim __lowerCamelCase : str = encoder_feedforward_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : int = encoder_layers __lowerCamelCase : List[Any] = decoder_layers __lowerCamelCase : Union[str, Any] = num_attention_heads __lowerCamelCase : Tuple = dropout __lowerCamelCase : Dict = dim_feedforward __lowerCamelCase : Union[str, Any] = pre_norm __lowerCamelCase : List[str] = enforce_input_projection __lowerCamelCase : Optional[int] = common_stride __lowerCamelCase : Dict = ignore_value __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : int = no_object_weight __lowerCamelCase : Optional[Any] = class_weight __lowerCamelCase : str = mask_weight __lowerCamelCase : List[str] = dice_weight __lowerCamelCase : Dict = train_num_points __lowerCamelCase : Optional[int] = oversample_ratio __lowerCamelCase : Optional[Any] = importance_sample_ratio __lowerCamelCase : List[Any] = init_std __lowerCamelCase : Tuple = init_xavier_std __lowerCamelCase : Union[str, Any] = use_auxiliary_loss __lowerCamelCase : List[Any] = feature_strides __lowerCamelCase : Any = output_auxiliary_logits __lowerCamelCase : List[Any] = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__) @classmethod def lowerCAmelCase ( cls : str ,SCREAMING_SNAKE_CASE__ : PretrainedConfig ,**SCREAMING_SNAKE_CASE__ : Tuple): return cls( backbone_config=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ,) def lowerCAmelCase ( self : str): __lowerCamelCase : List[Any] = copy.deepcopy(self.__dict__) __lowerCamelCase : List[Any] = self.backbone_config.to_dict() __lowerCamelCase : Union[str, Any] = self.__class__.model_type return output
73
0
from __future__ import annotations from scipy.special import comb # type: ignore class snake_case : '''simple docstring''' def __init__( self : List[str] , lowerCAmelCase : list[tuple[float, float]]) -> Dict: """simple docstring""" _snake_case : Union[str, Any] = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. _snake_case : int = len(SCREAMING_SNAKE_CASE__) - 1 def UpperCamelCase_ ( self : List[Any] , lowerCAmelCase : float) -> str: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." _snake_case : list[float] = [] for i in range(len(self.list_of_points)): # basis function for each i output_values.append( comb(self.degree , SCREAMING_SNAKE_CASE__) * ((1 - t) ** (self.degree - i)) * (t**i)) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(SCREAMING_SNAKE_CASE__) , 5) == 1 return output_values def UpperCamelCase_ ( self : List[Any] , lowerCAmelCase : float) -> Optional[int]: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." _snake_case : Tuple = self.basis_function(SCREAMING_SNAKE_CASE__) _snake_case : List[Any] = 0.0 _snake_case : Optional[Any] = 0.0 for i in range(len(self.list_of_points)): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def UpperCamelCase_ ( self : int , lowerCAmelCase : float = 0.01) -> Optional[Any]: """simple docstring""" from matplotlib import pyplot as plt # type: ignore _snake_case : list[float] = [] # x coordinates of points to plot _snake_case : list[float] = [] # y coordinates of points to plot _snake_case : Any = 0.0 while t <= 1: _snake_case : List[Any] = self.bezier_curve_function(SCREAMING_SNAKE_CASE__) to_plot_x.append(value[0]) to_plot_y.append(value[1]) t += step_size _snake_case : Optional[Any] = [i[0] for i in self.list_of_points] _snake_case : List[str] = [i[1] for i in self.list_of_points] plt.plot( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , color="""blue""" , label="""Curve of Degree """ + str(self.degree) , ) plt.scatter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , color="""red""" , label="""Control Points""") plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
317
import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency a ={ """E""": 12.70, """T""": 9.06, """A""": 8.17, """O""": 7.51, """I""": 6.97, """N""": 6.75, """S""": 6.33, """H""": 6.09, """R""": 5.99, """D""": 4.25, """L""": 4.03, """C""": 2.78, """U""": 2.76, """M""": 2.41, """W""": 2.36, """F""": 2.23, """G""": 2.02, """Y""": 1.97, """P""": 1.93, """B""": 1.29, """V""": 0.98, """K""": 0.77, """J""": 0.15, """X""": 0.15, """Q""": 0.10, """Z""": 0.07, } a ="""ETAOINSHRDLCUMWFGYPBVKJXQZ""" a ="""ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> dict[str, int]: __lowerCamelCase : Tuple = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: return x[0] def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: __lowerCamelCase : List[str] = get_letter_count(lowerCamelCase__ ) __lowerCamelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(lowerCamelCase__ ) __lowerCamelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = ''.join(freq_to_letter[freq] ) __lowerCamelCase : int = list(freq_to_letter_str.items() ) freq_pairs.sort(key=lowerCamelCase__ , reverse=lowerCamelCase__ ) __lowerCamelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> int: __lowerCamelCase : str = get_frequency_order(lowerCamelCase__ ) __lowerCamelCase : Optional[Any] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
73
0
'''simple docstring''' from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class _UpperCAmelCase ( snake_case_ ): """simple docstring""" snake_case = 42 class _UpperCAmelCase ( snake_case_ , snake_case_ ): """simple docstring""" @register_to_config def __init__( self : List[str] , __UpperCAmelCase : int = 32 , __UpperCAmelCase : int = 64 , __UpperCAmelCase : int = 20 , __UpperCAmelCase : int = 768 , __UpperCAmelCase : Any=77 , __UpperCAmelCase : Dict=4 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : str = "silu" , __UpperCAmelCase : Optional[str] = None , __UpperCAmelCase : Optional[str] = None , __UpperCAmelCase : Optional[str] = "linear" , __UpperCAmelCase : Optional[str] = "prd" , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[int] = None , ): '''simple docstring''' super().__init__() _A = num_attention_heads _A = attention_head_dim _A = num_attention_heads * attention_head_dim _A = additional_embeddings _A = time_embed_dim or inner_dim _A = embedding_proj_dim or embedding_dim _A = clip_embed_dim or embedding_dim _A = Timesteps(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 0 ) _A = TimestepEmbedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , out_dim=SCREAMING_SNAKE_CASE__ , act_fn=SCREAMING_SNAKE_CASE__ ) _A = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if embedding_proj_norm_type is None: _A = None elif embedding_proj_norm_type == "layer": _A = nn.LayerNorm(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''' ) _A = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if encoder_hid_proj_type is None: _A = None elif encoder_hid_proj_type == "linear": _A = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''' ) _A = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , SCREAMING_SNAKE_CASE__ ) ) if added_emb_type == "prd": _A = nn.Parameter(torch.zeros(1 , 1 , SCREAMING_SNAKE_CASE__ ) ) elif added_emb_type is None: _A = None else: raise ValueError( f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''' ) _A = nn.ModuleList( [ BasicTransformerBlock( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn="gelu" , attention_bias=SCREAMING_SNAKE_CASE__ , ) for d in range(SCREAMING_SNAKE_CASE__ ) ] ) if norm_in_type == "layer": _A = nn.LayerNorm(SCREAMING_SNAKE_CASE__ ) elif norm_in_type is None: _A = None else: raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.''' ) _A = nn.LayerNorm(SCREAMING_SNAKE_CASE__ ) _A = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _A = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -10000.0 ) causal_attention_mask.triu_(1 ) _A = causal_attention_mask[None, ...] self.register_buffer("causal_attention_mask" , SCREAMING_SNAKE_CASE__ , persistent=SCREAMING_SNAKE_CASE__ ) _A = nn.Parameter(torch.zeros(1 , SCREAMING_SNAKE_CASE__ ) ) _A = nn.Parameter(torch.zeros(1 , SCREAMING_SNAKE_CASE__ ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' _A = {} def fn_recursive_add_processors(__UpperCAmelCase : str , __UpperCAmelCase : torch.nn.Module , __UpperCAmelCase : Dict[str, AttentionProcessor] ): if hasattr(SCREAMING_SNAKE_CASE__ , "set_processor" ): _A = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f'''{name}.{sub_name}''' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return processors for name, module in self.named_children(): fn_recursive_add_processors(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return processors def lowerCAmelCase ( self : Any , __UpperCAmelCase : Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): '''simple docstring''' _A = len(self.attn_processors.keys() ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) != count: raise ValueError( f'''A dict of processors was passed, but the number of processors {len(SCREAMING_SNAKE_CASE__ )} does not match the''' f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''' ) def fn_recursive_attn_processor(__UpperCAmelCase : str , __UpperCAmelCase : torch.nn.Module , __UpperCAmelCase : Tuple ): if hasattr(SCREAMING_SNAKE_CASE__ , "set_processor" ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): module.set_processor(SCREAMING_SNAKE_CASE__ ) else: module.set_processor(processor.pop(f'''{name}.processor''' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f'''{name}.{sub_name}''' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for name, module in self.named_children(): fn_recursive_attn_processor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase ( self : str ): '''simple docstring''' self.set_attn_processor(AttnProcessor() ) def lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Union[torch.Tensor, float, int] , __UpperCAmelCase : torch.FloatTensor , __UpperCAmelCase : Optional[torch.FloatTensor] = None , __UpperCAmelCase : Optional[torch.BoolTensor] = None , __UpperCAmelCase : bool = True , ): '''simple docstring''' _A = hidden_states.shape[0] _A = timestep if not torch.is_tensor(SCREAMING_SNAKE_CASE__ ): _A = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(SCREAMING_SNAKE_CASE__ ) and len(timesteps.shape ) == 0: _A = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _A = timesteps * torch.ones(SCREAMING_SNAKE_CASE__ , dtype=timesteps.dtype , device=timesteps.device ) _A = self.time_proj(SCREAMING_SNAKE_CASE__ ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. _A = timesteps_projected.to(dtype=self.dtype ) _A = self.time_embedding(SCREAMING_SNAKE_CASE__ ) if self.embedding_proj_norm is not None: _A = self.embedding_proj_norm(SCREAMING_SNAKE_CASE__ ) _A = self.embedding_proj(SCREAMING_SNAKE_CASE__ ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: _A = self.encoder_hidden_states_proj(SCREAMING_SNAKE_CASE__ ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set" ) _A = self.proj_in(SCREAMING_SNAKE_CASE__ ) _A = self.positional_embedding.to(hidden_states.dtype ) _A = [] _A = 0 if encoder_hidden_states is not None: additional_embeds.append(SCREAMING_SNAKE_CASE__ ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: _A = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: _A = hidden_states[:, None, :] _A = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: _A = self.prd_embedding.to(hidden_states.dtype ).expand(SCREAMING_SNAKE_CASE__ , -1 , -1 ) additional_embeds.append(SCREAMING_SNAKE_CASE__ ) _A = torch.cat( SCREAMING_SNAKE_CASE__ , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens _A = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: _A = F.pad( SCREAMING_SNAKE_CASE__ , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) _A = hidden_states + positional_embeddings if attention_mask is not None: _A = (1 - attention_mask.to(hidden_states.dtype )) * -10000.0 _A = F.pad(SCREAMING_SNAKE_CASE__ , (0, self.additional_embeddings) , value=0.0 ) _A = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) _A = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: _A = self.norm_in(SCREAMING_SNAKE_CASE__ ) for block in self.transformer_blocks: _A = block(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) _A = self.norm_out(SCREAMING_SNAKE_CASE__ ) if self.prd_embedding is not None: _A = hidden_states[:, -1] else: _A = hidden_states[:, additional_embeddings_len:] _A = self.proj_to_clip_embeddings(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : int ): '''simple docstring''' _A = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
79
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests a =open # noqa: we just need to have a builtin inside this module to test it properly
73
0
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate __A : List[Any] = trt.Logger(trt.Logger.WARNING) __A : Any = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) __A : Union[str, Any] = logging.getLogger(__name__) __A : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--onnx_model_path', default=None, type=str, required=True, help='Path to ONNX model: ', ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='The output directory where the model checkpoints and predictions will be written.', ) # Other parameters parser.add_argument( '--tokenizer_name', default='', type=str, required=True, help='Pretrained tokenizer name or path if not the same as model_name', ) parser.add_argument( '--version_2_with_negative', action='store_true', help='If true, the SQuAD examples contain some that do not have an answer.', ) parser.add_argument( '--null_score_diff_threshold', type=float, default=0.0, help='If null_score - best_non_null is greater than the threshold predict null.', ) parser.add_argument( '--max_seq_length', default=3_84, type=int, help=( 'The maximum total input sequence length after WordPiece tokenization. Sequences ' 'longer than this will be truncated, and sequences shorter than this will be padded.' ), ) parser.add_argument( '--doc_stride', default=1_28, type=int, help='When splitting up a long document into chunks, how much stride to take between chunks.', ) parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.') parser.add_argument( '--n_best_size', default=20, type=int, help='The total number of n-best predictions to generate in the nbest_predictions.json output file.', ) parser.add_argument( '--max_answer_length', default=30, type=int, help=( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ), ) parser.add_argument('--seed', type=int, default=42, help='random seed for initialization') parser.add_argument( '--dataset_name', type=str, default=None, required=True, help='The name of the dataset to use (via the datasets library).', ) parser.add_argument( '--dataset_config_name', type=str, default=None, help='The configuration name of the dataset to use (via the datasets library).', ) parser.add_argument( '--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.' ) parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets') parser.add_argument( '--fp16', action='store_true', help='Whether to use 16-bit (mixed) precision instead of 32-bit', ) parser.add_argument( '--int8', action='store_true', help='Whether to use INT8', ) __A : Optional[int] = parser.parse_args() if args.tokenizer_name: __A : Optional[Any] = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.' ) logger.info('Training/evaluation parameters %s', args) __A : Dict = args.per_device_eval_batch_size __A : Tuple = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties __A : Optional[Any] = True __A : Union[str, Any] = 'temp_engine/bert-fp32.engine' if args.fpaa: __A : str = 'temp_engine/bert-fp16.engine' if args.inta: __A : Any = 'temp_engine/bert-int8.engine' # import ONNX file if not os.path.exists('temp_engine'): os.makedirs('temp_engine') __A : Tuple = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, 'rb') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network __A : Any = [network.get_input(i) for i in range(network.num_inputs)] __A : List[Any] = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: __A : Union[str, Any] = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) __A : Optional[Any] = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) __A : List[str] = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, 'wb') as f: f.write(engine.serialize()) def __UpperCamelCase ( _A : Any , _A : List[str] , _A : List[Any] , _A : str , _A : List[str] , _A : List[str] , _A : Optional[int] , _A : Optional[Any] ) ->List[str]: """simple docstring""" lowerCamelCase_ =np.asarray(inputs["""input_ids"""] , dtype=np.intaa ) lowerCamelCase_ =np.asarray(inputs["""attention_mask"""] , dtype=np.intaa ) lowerCamelCase_ =np.asarray(inputs["""token_type_ids"""] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowerCamelCase__ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowerCamelCase__ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowerCamelCase__ ) # start time lowerCamelCase_ =time.time() # Run inference context.execute_async( bindings=[int(lowerCamelCase__ ) for d_inp in d_inputs] + [int(lowerCamelCase__ ), int(lowerCamelCase__ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) cuda.memcpy_dtoh_async(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # Synchronize the stream and take time stream.synchronize() # end time lowerCamelCase_ =time.time() lowerCamelCase_ =end_time - start_time lowerCamelCase_ =(h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. __A : Optional[int] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. __A : Union[str, Any] = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('Evaluation requires a dataset name') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. __A : Union[str, Any] = raw_datasets['validation'].column_names __A : Union[str, Any] = 'question' if 'question' in column_names else column_names[0] __A : int = 'context' if 'context' in column_names else column_names[1] __A : Any = 'answers' if 'answers' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). __A : Dict = tokenizer.padding_side == 'right' if args.max_seq_length > tokenizer.model_max_length: logger.warning( F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the""" F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.""" ) __A : Dict = min(args.max_seq_length, tokenizer.model_max_length) def __UpperCamelCase ( _A : Union[str, Any] ) ->List[Any]: """simple docstring""" # Some of the questions have lots of whitespace on the left, which is not useful and will make the # truncation of the context fail (the tokenized question will take a lots of space). So we remove that # left whitespace lowerCamelCase_ =[q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. lowerCamelCase_ =tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="""only_second""" if pad_on_right else """only_first""" , max_length=lowerCamelCase__ , stride=args.doc_stride , return_overflowing_tokens=lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , padding="""max_length""" , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. lowerCamelCase_ =tokenized_examples.pop("""overflow_to_sample_mapping""" ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. lowerCamelCase_ =[] for i in range(len(tokenized_examples["""input_ids"""] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). lowerCamelCase_ =tokenized_examples.sequence_ids(lowerCamelCase__ ) lowerCamelCase_ =1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. lowerCamelCase_ =sample_mapping[i] tokenized_examples["example_id"].append(examples["""id"""][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. lowerCamelCase_ =[ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples["""offset_mapping"""][i] ) ] return tokenized_examples __A : str = raw_datasets['validation'] # Validation Feature Creation __A : Union[str, Any] = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='Running tokenizer on validation dataset', ) __A : List[Any] = default_data_collator __A : Optional[int] = eval_dataset.remove_columns(['example_id', 'offset_mapping']) __A : int = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def __UpperCamelCase ( _A : List[Any] , _A : Optional[int] , _A : Tuple , _A : Tuple="eval" ) ->Any: """simple docstring""" # Post-processing: we match the start logits and end logits to answers in the original context. lowerCamelCase_ =postprocess_qa_predictions( examples=lowerCamelCase__ , features=lowerCamelCase__ , predictions=lowerCamelCase__ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowerCamelCase__ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: lowerCamelCase_ =[ {'id': k, 'prediction_text': v, 'no_answer_probability': 0.0} for k, v in predictions.items() ] else: lowerCamelCase_ =[{'id': k, 'prediction_text': v} for k, v in predictions.items()] lowerCamelCase_ =[{'id': ex['id'], 'answers': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowerCamelCase__ , label_ids=lowerCamelCase__ ) __A : List[Any] = load_metric('squad_v2' if args.version_2_with_negative else 'squad') # Evaluation! logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path) with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def __UpperCamelCase ( _A : List[Any] ) ->Optional[Any]: """simple docstring""" return trt.volume(engine.get_binding_shape(lowerCamelCase__ ) ) * engine.get_binding_dtype(lowerCamelCase__ ).itemsize # Allocate device memory for inputs and outputs. __A : Dict = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer __A : List[Any] = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) __A : Optional[Any] = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) __A : Optional[Any] = cuda.mem_alloc(h_outputa.nbytes) __A : Any = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. __A : Union[str, Any] = cuda.Stream() # Evaluation logger.info('***** Running Evaluation *****') logger.info(F""" Num examples = {len(eval_dataset)}""") logger.info(F""" Batch size = {args.per_device_eval_batch_size}""") __A : Any = 0.0 __A : Dict = 0 __A : Optional[Any] = timeit.default_timer() __A : List[str] = None for step, batch in enumerate(eval_dataloader): __A, __A : Tuple = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 __A, __A : List[str] = outputs __A : Union[str, Any] = torch.tensor(start_logits) __A : Any = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered __A : Tuple = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) __A : Any = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) __A : Union[str, Any] = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) __A : List[str] = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: __A : Any = nested_truncate(all_preds, len(eval_dataset)) __A : Optional[Any] = timeit.default_timer() - start_time logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 10_00 / niter)) logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 10_00)) logger.info('Total Number of Inference = %d', niter) __A : str = post_processing_function(eval_examples, eval_dataset, all_preds) __A : List[str] = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F"""Evaluation metrics: {eval_metric}""")
154
# Function to print upper half of diamond (pyramid) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> str: for i in range(0 , lowerCamelCase__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(' ' , end='' ) for _ in range(0 , i + 1 ): # printing stars print('* ' , end='' ) print() def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Tuple: for i in range(lowerCamelCase__ , 0 , -1 ): for _ in range(lowerCamelCase__ , 0 , -1 ): # printing stars print('* ' , end='' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(' ' , end='' ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: if n <= 0: print(' ... .... nothing printing :(' ) return floyd(lowerCamelCase__ ) # upper half reverse_floyd(lowerCamelCase__ ) # lower half if __name__ == "__main__": print(r"""| /\ | |- | |- |--| |\ /| |-""") print(r"""|/ \| |- |_ |_ |__| | \/ | |_""") a =1 while K: a =int(input("""enter the number and , and see the magic : """)) print() pretty_print(user_number) a =int(input("""press 0 to exit... and 1 to continue...""")) print("""Good Bye...""")
73
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase__ = logging.get_logger(__name__) class __snake_case ( _lowercase): snake_case__ : Dict = ['''pixel_values'''] def __init__( self : List[Any] , __lowerCAmelCase : bool = True , __lowerCAmelCase : Dict[str, int] = None , __lowerCAmelCase : float = None , __lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , __lowerCAmelCase : bool = True , __lowerCAmelCase : Union[int, float] = 1 / 2_5_5 , __lowerCAmelCase : bool = True , __lowerCAmelCase : Optional[Union[float, List[float]]] = None , __lowerCAmelCase : Optional[Union[float, List[float]]] = None , **__lowerCAmelCase : Tuple , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Tuple = size if size is not None else {'shortest_edge': 3_8_4} _lowerCamelCase : Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Any = do_resize _lowerCamelCase : Optional[Any] = size # Default value set here for backwards compatibility where the value in config is None _lowerCamelCase : Optional[int] = crop_pct if crop_pct is not None else 2_2_4 / 2_5_6 _lowerCamelCase : str = resample _lowerCamelCase : Optional[int] = do_rescale _lowerCamelCase : int = rescale_factor _lowerCamelCase : Union[str, Any] = do_normalize _lowerCamelCase : Tuple = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _lowerCamelCase : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : np.ndarray , __lowerCAmelCase : Dict[str, int] , __lowerCAmelCase : float , __lowerCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , __lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCAmelCase : Optional[int] , ): """simple docstring""" _lowerCamelCase : Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''' ) _lowerCamelCase : List[str] = size['shortest_edge'] if shortest_edge < 3_8_4: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct _lowerCamelCase : Tuple = int(shortest_edge / crop_pct ) _lowerCamelCase : Any = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Union[str, Any] = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : np.ndarray , __lowerCAmelCase : Union[int, float] , __lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCAmelCase : int , ): """simple docstring""" return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : np.ndarray , __lowerCAmelCase : Union[float, List[float]] , __lowerCAmelCase : Union[float, List[float]] , __lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **__lowerCAmelCase : List[str] , ): """simple docstring""" return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : ImageInput , __lowerCAmelCase : bool = None , __lowerCAmelCase : Dict[str, int] = None , __lowerCAmelCase : float = None , __lowerCAmelCase : PILImageResampling = None , __lowerCAmelCase : bool = None , __lowerCAmelCase : float = None , __lowerCAmelCase : bool = None , __lowerCAmelCase : Optional[Union[float, List[float]]] = None , __lowerCAmelCase : Optional[Union[float, List[float]]] = None , __lowerCAmelCase : Optional[Union[str, TensorType]] = None , __lowerCAmelCase : ChannelDimension = ChannelDimension.FIRST , **__lowerCAmelCase : Any , ): """simple docstring""" _lowerCamelCase : Optional[Any] = do_resize if do_resize is not None else self.do_resize _lowerCamelCase : str = crop_pct if crop_pct is not None else self.crop_pct _lowerCamelCase : int = resample if resample is not None else self.resample _lowerCamelCase : Tuple = do_rescale if do_rescale is not None else self.do_rescale _lowerCamelCase : int = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCamelCase : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize _lowerCamelCase : str = image_mean if image_mean is not None else self.image_mean _lowerCamelCase : Any = image_std if image_std is not None else self.image_std _lowerCamelCase : List[Any] = size if size is not None else self.size _lowerCamelCase : Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Union[str, Any] = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None: raise ValueError('''crop_pct must be specified if size < 384.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _lowerCamelCase : Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: _lowerCamelCase : Union[str, Any] = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: _lowerCamelCase : List[Any] = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: _lowerCamelCase : Union[str, Any] = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] _lowerCamelCase : List[str] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] _lowerCamelCase : Tuple = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
72
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A_ ( SCREAMING_SNAKE_CASE ): _UpperCAmelCase : Any = ['''image_processor''', '''tokenizer'''] _UpperCAmelCase : List[Any] = '''AutoImageProcessor''' _UpperCAmelCase : Dict = '''AutoTokenizer''' def __init__( self : Union[str, Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]=None ,SCREAMING_SNAKE_CASE__ : List[Any]=None ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): __lowerCamelCase : List[str] = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,SCREAMING_SNAKE_CASE__ ,) __lowerCamelCase : Union[str, Any] = kwargs.pop('feature_extractor') __lowerCamelCase : Dict = 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__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Dict = self.image_processor __lowerCamelCase : Optional[int] = False def __call__( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Union[str, Any]): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) __lowerCamelCase : Optional[int] = kwargs.pop('images' ,SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = kwargs.pop('text' ,SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__) > 0: __lowerCamelCase : int = args[0] __lowerCamelCase : List[str] = args[1:] if images is None and text is None: raise ValueError('You need to specify either an `images` or `text` input to process.') if images is not None: __lowerCamelCase : Optional[int] = self.image_processor(SCREAMING_SNAKE_CASE__ ,*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is not None: __lowerCamelCase : List[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : Optional[Any] = encodings['input_ids'] return inputs def lowerCAmelCase ( self : int ,*SCREAMING_SNAKE_CASE__ : Union[str, Any] ,**SCREAMING_SNAKE_CASE__ : Dict): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) def lowerCAmelCase ( self : Optional[Any] ,*SCREAMING_SNAKE_CASE__ : List[Any] ,**SCREAMING_SNAKE_CASE__ : Any): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__) @contextmanager def lowerCAmelCase ( self : Tuple): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your images inputs, or in a separate call.') __lowerCamelCase : List[Any] = True __lowerCamelCase : str = self.tokenizer yield __lowerCamelCase : Tuple = self.image_processor __lowerCamelCase : Tuple = False def lowerCAmelCase ( self : Any ,SCREAMING_SNAKE_CASE__ : str ,SCREAMING_SNAKE_CASE__ : int=False ,SCREAMING_SNAKE_CASE__ : List[Any]=None): if added_vocab is None: __lowerCamelCase : str = self.tokenizer.get_added_vocab() __lowerCamelCase : Union[str, Any] = {} while tokens: __lowerCamelCase : Tuple = re.search(R'<s_(.*?)>' ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if start_token is None: break __lowerCamelCase : Dict = start_token.group(1) __lowerCamelCase : List[str] = re.search(RF"</s_{key}>" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) __lowerCamelCase : Optional[int] = start_token.group() if end_token is None: __lowerCamelCase : List[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ ,'') else: __lowerCamelCase : Tuple = end_token.group() __lowerCamelCase : int = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : str = re.escape(SCREAMING_SNAKE_CASE__) __lowerCamelCase : Union[str, Any] = re.search(F"{start_token_escaped}(.*?){end_token_escaped}" ,SCREAMING_SNAKE_CASE__ ,re.IGNORECASE) if content is not None: __lowerCamelCase : List[Any] = content.group(1).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node __lowerCamelCase : str = self.tokenajson(SCREAMING_SNAKE_CASE__ ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if value: if len(SCREAMING_SNAKE_CASE__) == 1: __lowerCamelCase : Tuple = value[0] __lowerCamelCase : int = value else: # leaf nodes __lowerCamelCase : Tuple = [] for leaf in content.split(R'<sep/>'): __lowerCamelCase : List[Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": __lowerCamelCase : str = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__) if len(output[key]) == 1: __lowerCamelCase : Dict = output[key][0] __lowerCamelCase : Dict = tokens[tokens.find(SCREAMING_SNAKE_CASE__) + len(SCREAMING_SNAKE_CASE__) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] ,is_inner_value=SCREAMING_SNAKE_CASE__ ,added_vocab=SCREAMING_SNAKE_CASE__) if len(SCREAMING_SNAKE_CASE__): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def lowerCAmelCase ( self : List[str]): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor_class @property def lowerCAmelCase ( self : List[Any]): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,SCREAMING_SNAKE_CASE__ ,) return self.image_processor
73
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __snake_case = {'''processing_layoutxlm''': ['''LayoutXLMProcessor''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''LayoutXLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ['''LayoutXLMTokenizerFast'''] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys __snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
97
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ ) -> int: __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : Dict = len(lowerCamelCase__ ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : str = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None __lowerCamelCase : Tuple = sorted_collection[point] if current_item == item: return point else: if point < left: __lowerCamelCase : List[Any] = left __lowerCamelCase : Tuple = point elif point > right: __lowerCamelCase : Dict = right __lowerCamelCase : str = point else: if item < current_item: __lowerCamelCase : Dict = point - 1 else: __lowerCamelCase : Dict = point + 1 return None def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Any: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None __lowerCamelCase : Optional[int] = left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowerCamelCase__ ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) elif point > right: return interpolation_search_by_recursion(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , point - 1 ) else: return interpolation_search_by_recursion( lowerCamelCase__ , lowerCamelCase__ , point + 1 , lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]: if collection != sorted(lowerCamelCase__ ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys a =0 if debug == 1: a =[10, 30, 40, 45, 50, 66, 77, 93] try: __assert_sorted(collection) except ValueError: sys.exit("""Sequence must be ascending sorted to apply interpolation search""") a =67 a =interpolation_search(collection, target) if result is not None: print(F"""{target} found at positions: {result}""") else: print("""Not found""")
73
0